[
  {
    "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": ""
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug.yml",
    "content": "name: Bug Report\ndescription: Something isn't working as it should\nlabels: \"bug\"\n\nbody:\n  - type: textarea\n    attributes:\n      label: Describe the problem\n      description: add expected and actual result if it's not blatantly obvious\n  - type: textarea\n    attributes:\n      label: Gist to reproduce\n      description: >\n        Full source code is appreciated. We also very much appreciate\n        it if you try to narrow the source down to a small stand-alone example.\n      render: python\n  - type: dropdown\n    attributes:\n      label: Severity\n      description: How does this affect you?\n      options:\n        - annoying but workaround is available\n        - annoying but i can live with it\n        - blocker (literally unusable)\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Your Environment\n      description: include any relevant information such as operating system and the output of `mypy --version`\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "contact_links:\n  - about: \"Please ask and answer usage questions in our official Discord.\"\n    name: Questions, help and discussion\n    url: \"https://discord.gg/7y9upqPrk2\"\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/documentation.md",
    "content": "---\nname: Documentation\nabout: Report a problem with the documentation\nlabels: \"documentation\"\n---\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 based new mypy feature\nlabels: \"feature\"\n---\n\n<!-- Please explain why this feature is based -->\n\n<!-- Please explain why this feature should be implemented and how it would be used. Please include a full usage example. -->\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "![image](https://github.com/KotlinIsland/basedmypy/blob/master/.github/pull_request.png?raw=true)\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 == 'KotlinIsland/basedmypy'\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    - '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.21.2\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]\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.12\"\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 5 --shard-index ${{ matrix.shard-index }} \\\n            --debug \\\n            --additional-flags=\"--debug-serialize --no-color-output --enable-error-code=helpful-string\" \\\n            --output concise \\\n            `# We don't want to run on spack because it has massive inferred types` \\\n            `#  https://github.com/KotlinIsland/basedmypy/issues/399` \\\n            --project-selector \"^(?!https://github.com/(spack/spack|mitmproxy/mitmproxy))\" \\\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 = 261544\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, suffix='') {\n              maxLength -= suffix.length\n              if (original.length <= maxLength) {\n                return original + suffix\n              }\n              suffix += '\\n\\n... (truncated {lines_truncated} lines) ...'\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}${suffix.replace(\"{lines_truncated}\", lines_truncated)}`\n            }\n\n            if (data.length >= MAX_CHARACTERS) {\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            }\n            console.log(\"Diff from mypy_primer:\")\n            console.log(data)\n\n            let body\n            if (data.trim()) {\n              data = '```diff\\n' + data\n              if (data.split('\\n').length > 500) {\n                data = '<details><summary></summary>\\n\\n' + data + '```'\n              }\n              body = 'Diff from [mypy_primer](https://github.com/hauntsaninja/mypy_primer), showing the effect of this PR on open source code:\\n' + data\n              body = truncateIfNeeded(body, MAX_CHARACTERS, data.split('\\n').length > 500 ? '```</details>' : '')\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/publish.yml",
    "content": "name: Publish\n\non:\n  release:\n    types: [published]\n\njobs:\n  pypi:\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.13'\n      - name: publish\n        env:\n          TWINE_USERNAME: __token__\n          TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}\n        shell: bash\n        run: |\n          version=$(python -c \"import mypy.version; print(mypy.version.__based_version__)\")\n          python misc/upload-pypi.py $version --save-dist\n\n      # Upload wheels as a release asset\n      - name: Upload Release Assets\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        run: gh release upload ${{ github.event.release.tag_name }} ./dist/*  # zizmor: ignore[template-injection]\n\n  docs:\n    permissions:\n      pages: write      # to deploy to Pages\n      id-token: write   # to verify the deployment originates from an appropriate source\n\n    runs-on: ubuntu-latest\n    env:\n      TOXENV: docs\n      TOX_SKIP_MISSING_INTERPRETERS: False\n    environment:\n      name: docs\n      url: ${{ steps.deployment.outputs.page_url }}\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 --upgrade 'setuptools!=50' tox==4.11.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      - name: Setup Pages\n        uses: actions/configure-pages@v4\n      - name: Upload artifact\n        uses: actions/upload-pages-artifact@v3\n        with:\n          path: \".tox/docs_out\"\n      - name: Deploy to GitHub Pages\n        uses: actions/deploy-pages@v4\n        id: deployment\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*', 'merge-mypy-*', 'merge-upstream']\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 py39-ubuntu, mypyc-compiled\n          python: '3.9'\n          arch: x64\n          os: ubuntu-latest\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py39-windows-64\n          python: '3.9'\n          arch: x64\n          os: windows-latest\n          toxenv: py39\n          tox_extra_args: \"-n 4\"\n        - name: Test suite with py310-ubuntu\n          python: '3.10'\n          arch: x64\n          os: ubuntu-latest\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n        - name: Test suite with py311-ubuntu, mypyc-compiled\n          python: '3.11'\n          arch: x64\n          os: ubuntu-latest\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py312-ubuntu, mypyc-compiled\n          python: '3.12'\n          arch: x64\n          os: ubuntu-latest\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py313-ubuntu, mypyc-compiled\n          python: '3.13'\n          arch: x64\n          os: ubuntu-latest\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n\n        # - name: Test suite with py314-dev-ubuntu\n        #   python: '3.14-dev'\n        #   arch: x64\n        #   os: ubuntu-latest\n        #   toxenv: py\n        #   tox_extra_args: \"-n 4\"\n        #   allow_failure: true\n        #   test_mypyc: true\n\n        - name: mypyc runtime tests with py39-macos\n          python: '3.9.21'\n          arch: x64\n          # TODO: macos-13 is the last one to support Python 3.9, change it to macos-latest when updating the Python version\n          os: macos-13\n          toxenv: py\n          tox_extra_args: \"-n 3 mypyc/test/test_run.py mypyc/test/test_external.py\"\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 py38-debug-build-ubuntu\n        #   python: '3.9.21'\n        #   arch: x64\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: Type check our own code (py39-ubuntu)\n          python: '3.9'\n          arch: x64\n          os: ubuntu-latest\n          toxenv: type\n        - name: Type check our own code (py39-windows-64)\n          python: '3.9'\n          arch: x64\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          arch: x64\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      # Pytest\n      PYTEST_ADDOPTS: --color=yes\n\n    steps:\n    - uses: actions/checkout@v4\n      with:\n        persist-credentials: false\n\n    - name: Debug build\n      if: ${{ matrix.debug_build }}\n      run: |\n        PYTHONVERSION=${{ matrix.python }}\n        PYTHONDIR=~/python-debug/python-$PYTHONVERSION\n        VENV=$PYTHONDIR/env\n        ./misc/build-debug-python.sh $PYTHONVERSION $PYTHONDIR $VENV\n        # TODO: does this do anything? env vars aren't passed to the next step right\n        source $VENV/bin/activate\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\n          sudo apt-get install -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    - uses: actions/setup-python@v5\n      if: ${{ !(matrix.debug_build || endsWith(matrix.python, '-dev')) }}\n      with:\n        python-version: ${{ matrix.python }}\n        architecture: ${{ matrix.arch }}\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 setuptools==75.1.0 tox==4.21.2\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      # 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 setuptools==75.1.0 tox==4.21.2\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/stubgen/**'\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.9\n      uses: actions/setup-python@v5\n      with:\n        python-version: 3.9\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\n.pyprojectx\n"
  },
  {
    "path": ".mypy/baseline.json",
    "content": "{\n  \"files\": {\n    \"mypy/__main__.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"int | Any\\\")\",\n        \"offset\": 22,\n        \"src\": \"os.dup2(devnull, sys.stdout.fileno())\",\n        \"target\": \"mypy.__main__.console_entry\"\n      }\n    ],\n    \"mypy/build.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 343,\n        \"src\": \"plugin_data: Any  # config data from plugins\",\n        \"target\": \"mypy.build\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 15,\n        \"src\": \"def cache_meta_from_dict(meta: dict[str, Any], data_json: str) -> CacheMeta:\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 7,\n        \"src\": \"sentinel: Any = None  # Values to be validated by the caller\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"return CacheMeta(\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"id\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"id\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"id\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"path\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"path\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"path\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"int | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"int(meta[\\\"mtime\\\"]) if \\\"mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"mtime\\\"]) if \\\"mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"mtime\\\"]) if \\\"mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"mtime\\\"]) if \\\"mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"mtime\\\"]) if \\\"mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"size\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"size\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"size\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"hash\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"hash\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"hash\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"dependencies\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"dependencies\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"dependencies\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"int | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"int(meta[\\\"data_mtime\\\"]) if \\\"data_mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"data_mtime\\\"]) if \\\"data_mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"data_mtime\\\"]) if \\\"data_mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"data_mtime\\\"]) if \\\"data_mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"int(meta[\\\"data_mtime\\\"]) if \\\"data_mtime\\\" in meta else sentinel,\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"meta.get(\\\"suppressed\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"suppressed\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"suppressed\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"options\\\"),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"options\\\"),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"dep_prios\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"dep_prios\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"dep_prios\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"dep_lines\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"dep_lines\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"dep_lines\\\", []),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"interface_hash\\\", \\\"\\\"),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"interface_hash\\\", \\\"\\\"),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"version_id\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"version_id\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"version_id\\\", sentinel),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"ignore_all\\\", True),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"ignore_all\\\", True),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"plugin_data\\\", None),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"plugin_data\\\", None),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"meta.get(\\\"baseline_hash\\\", None),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta.get(\\\"baseline_hash\\\", None),\",\n        \"target\": \"mypy.build.cache_meta_from_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 93,\n        \"src\": \"plugin_type = getattr(module, func_name)(__version__)\",\n        \"target\": \"mypy.build.load_plugins_from_config\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if not isinstance(plugin_type, type):\",\n        \"target\": \"mypy.build.load_plugins_from_config\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"plugin_type, plugin_path\",\n        \"target\": \"mypy.build.load_plugins_from_config\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 52,\n        \"src\": \"ver = getattr(module, \\\"__version__\\\", \\\"none\\\")\",\n        \"target\": \"mypy.build.take_module_snapshot\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 1,\n        \"src\": \"return f\\\"{ver}:{digest}\\\"\",\n        \"target\": \"mypy.build.take_module_snapshot\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 86,\n        \"src\": \"self.stats: dict[str, Any] = {}  # Values are ints or floats\",\n        \"target\": \"mypy.build.BuildManager.__init__\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 38,\n        \"message\": \"The string for \\\"object\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 102,\n        \"src\": \"print(f\\\"{key + ':':24}{value}\\\")\",\n        \"target\": \"mypy.build.BuildManager.dump_stats\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 145,\n        \"src\": \"deps: Any = json_loads(self.metastore.read(self.fg_deps_meta[id][\\\"path\\\"]))\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"deps: Any = json_loads(self.metastore.read(self.fg_deps_meta[id][\\\"path\\\"]))\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[Any, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"deps = {}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"val = {k: set(v) for k, v in deps.items()}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[Any, set[Any]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = {k: set(v) for k, v in deps.items()}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = {k: set(v) for k, v in deps.items()}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = {k: set(v) for k, v in deps.items()}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = {k: set(v) for k, v in deps.items()}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = {k: set(v) for k, v in deps.items()}\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[Any, set[Any]]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return val\",\n        \"target\": \"mypy.build.BuildManager.load_fine_grained_deps\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 37,\n        \"src\": \"def add_stats(self, **kwds: Any) -> None:\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"for key, value in kwds.items():\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for key, value in kwds.items():\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for key, value in kwds.items():\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict_items[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for key, value in kwds.items():\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if key in self.stats:\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.stats[key] += value\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.stats[key] += value\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.stats[key] += value\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"self.stats[key] = value\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.stats[key] = value\",\n        \"target\": \"mypy.build.BuildManager.add_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"return self.stats\",\n        \"target\": \"mypy.build.BuildManager.stats_summary\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 66,\n        \"src\": \"if st.meta:\",\n        \"target\": \"mypy.build.write_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"hash = st.meta.hash\",\n        \"target\": \"mypy.build.write_deps_cache\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 139,\n        \"src\": \"data: Any = json.loads(file.read_text())\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 24,\n        \"src\": \"if not isinstance(data, dict) and error():\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"baseline_format = data.get(\\\"format\\\")\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not baseline_format:\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"metadata = data.get(\\\"__baseline_metadata__\\\")\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"baseline_format = metadata.get(\\\"format\\\") if isinstance(metadata, dict) else None\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if baseline_format is None and error():\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 9,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif baseline_format != \\\"1.7\\\":\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"not isinstance(data.get(\\\"files\\\"), dict) or not isinstance(data.get(\\\"targets\\\"), list)\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"not isinstance(data.get(\\\"files\\\"), dict) or not isinstance(data.get(\\\"targets\\\"), list)\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"baseline_errors = data.get(\\\"files\\\", {})\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"targets = data.get(\\\"targets\\\")\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if baseline_errors and targets:\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if baseline_errors and targets:\",\n        \"target\": \"mypy.build.load_baseline\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 27,\n        \"src\": \"snapshot = _load_json_file(\",\n        \"target\": \"mypy.build.read_plugins_snapshot\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 6,\n        \"src\": \"if snapshot is None:\",\n        \"target\": \"mypy.build.read_plugins_snapshot\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 7,\n        \"message\": \"Condition is always false\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(snapshot, dict):\",\n        \"target\": \"mypy.build.read_plugins_snapshot\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if not isinstance(snapshot, dict):\",\n        \"target\": \"mypy.build.read_plugins_snapshot\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"manager.log(f\\\"Could not load plugins snapshot: cache is not a dict: {type(snapshot)}\\\")\",\n        \"target\": \"mypy.build.read_plugins_snapshot\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"raw_quickstart = json_loads(f.read())\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\",\n        \"target\": \"mypy.build.read_quickstart_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 14,\n        \"src\": \"deps_meta = _load_json_file(\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 6,\n        \"src\": \"if deps_meta is None:\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"meta_snapshot = deps_meta[\\\"snapshot\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"meta_snapshot = deps_meta[\\\"snapshot\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"common = set(meta_snapshot.keys()) & set(current_meta_snapshot.keys())\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"common = set(meta_snapshot.keys()) & set(current_meta_snapshot.keys())\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common):\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common):\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common):\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common):\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 68,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common):\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"module_deps_metas = deps_meta[\\\"deps_meta\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"module_deps_metas = deps_meta[\\\"deps_meta\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(module_deps_metas, dict)\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"matched = manager.getmtime(meta[\\\"path\\\"]) == meta[\\\"mtime\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"matched = manager.getmtime(meta[\\\"path\\\"]) == meta[\\\"mtime\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"matched = manager.getmtime(meta[\\\"path\\\"]) == meta[\\\"mtime\\\"]\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if not matched:\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 74,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"manager.log(f\\\"Invalid or missing fine-grained deps cache: {meta['path']}\\\")\",\n        \"target\": \"mypy.build.read_deps_cache\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"def _load_json_file(\",\n        \"target\": \"mypy.build._load_json_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 16,\n        \"src\": \"result = json_loads(data)\",\n        \"target\": \"mypy.build._load_json_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 15,\n        \"src\": \"assert isinstance(result, dict)\",\n        \"target\": \"mypy.build._load_json_file\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 92,\n        \"src\": \"def find_cache_meta(id: str, path: str, manager: BuildManager) -> CacheMeta | None:\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 16,\n        \"src\": \"meta = _load_json_file(\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 4,\n        \"src\": \"if meta is None:\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 7,\n        \"message\": \"Condition is always false\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(meta, dict):\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if not isinstance(meta, dict):\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"manager.log(f\\\"Could not load cache for {id}: meta cache is not a dict: {repr(meta)}\\\")\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"m = cache_meta_from_dict(meta, data_json)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 8,\n        \"src\": \"m.id != id\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or m.mtime is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Left operand of \\\"or\\\" is always false\",\n        \"offset\": 0,\n        \"src\": \"or m.mtime is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or m.size is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Left operand of \\\"or\\\" is always false\",\n        \"offset\": 0,\n        \"src\": \"or m.size is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or m.dependencies is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Left operand of \\\"or\\\" is always false\",\n        \"offset\": 0,\n        \"src\": \"or m.dependencies is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or m.data_mtime is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 9,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 7,\n        \"src\": \"(m.version_id != manager.version_id and not manager.options.skip_version_check)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or m.options is None\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or len(m.dependencies) + len(m.suppressed) != len(m.dep_prios)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"or len(m.dependencies) + len(m.suppressed) != len(m.dep_prios)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"or len(m.dependencies) + len(m.suppressed) != len(m.dep_prios)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"or len(m.dependencies) + len(m.suppressed) != len(m.dep_lines)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"or len(m.dependencies) + len(m.suppressed) != len(m.dep_lines)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"or len(m.dependencies) + len(m.suppressed) != len(m.dep_lines)\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 7,\n        \"src\": \"cached_options = m.options\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 24,\n        \"message\": \"The string for \\\"object\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 14,\n        \"src\": \"\\\"    {}: {} != {}\\\".format(\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 13,\n        \"src\": \"plugin_data = json_loads(\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"json_dumps(manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=True)))\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"if m.plugin_data != plugin_data:\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if m.plugin_data != plugin_data:\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if m.plugin_data != plugin_data:\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 17,\n        \"src\": \"if baseline_hash != m.baseline_hash:\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 7,\n        \"src\": \"return m\",\n        \"target\": \"mypy.build.find_cache_meta\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def validate_meta(\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 15,\n        \"src\": \"if meta is None:\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 4,\n        \"src\": \"if meta.ignore_all and not ignore_all:\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 10,\n        \"src\": \"data_mtime = manager.getmtime(meta.data_json)\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 4,\n        \"src\": \"if data_mtime != meta.data_mtime:\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 34,\n        \"src\": \"if size != meta.size and not bazel and not fine_grained_cache:\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 6,\n        \"src\": \"if not bazel and (mtime != meta.mtime or path != meta.path):\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"if not bazel and (mtime != meta.mtime or path != meta.path):\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 7,\n        \"src\": \"if int(qmtime) == mtime and qsize == size and qhash == meta.hash:\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"meta = meta._replace(mtime=mtime, path=path)\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"return meta\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 12,\n        \"src\": \"if source_hash != meta.hash:\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 3,\n        \"src\": \"return meta\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 7,\n        \"src\": \"meta = meta._replace(mtime=mtime, path=path)\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, str | int | list[str] | Mapping[str, object] | list[int] | Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"meta_dict = {\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 6,\n        \"src\": \"\\\"data_mtime\\\": meta.data_mtime,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"dependencies\\\": meta.dependencies,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"suppressed\\\": meta.suppressed,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"dep_prios\\\": meta.dep_prios,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"dep_lines\\\": meta.dep_lines,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"interface_hash\\\": meta.interface_hash,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"ignore_all\\\": meta.ignore_all,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"plugin_data\\\": meta.plugin_data,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"plugin_data\\\": meta.plugin_data,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"\\\"plugin_data\\\": meta.plugin_data,\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, str | int | list[str] | Mapping[str, object] | list[int] | Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"meta_bytes = json_dumps(meta_dict, manager.options.debug_cache)\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 4,\n        \"src\": \"id, path, meta_json, meta.mtime\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 6,\n        \"src\": \"return meta\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 4,\n        \"src\": \"return meta\",\n        \"target\": \"mypy.build.validate_meta\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 12,\n        \"src\": \"def write_cache(\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 56,\n        \"src\": \"plugin_data = manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=False))\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, str | int | list[str] | Mapping[str, object] | list[int] | Any | None]\\\")\",\n        \"offset\": 64,\n        \"src\": \"meta = {\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 15,\n        \"src\": \"\\\"plugin_data\\\": plugin_data,\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"\\\"plugin_data\\\": plugin_data,\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, str | int | list[str] | Mapping[str, object] | list[int] | Any | None]\\\")\",\n        \"offset\": 5,\n        \"src\": \"meta_str = json_dumps(meta, manager.options.debug_cache)\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, CacheMeta)\\\")\",\n        \"offset\": 7,\n        \"src\": \"return interface_hash, cache_meta_from_dict(meta, data_json)\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"return interface_hash, cache_meta_from_dict(meta, data_json)\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, str | int | list[str] | Mapping[str, object] | list[int] | Any | None]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return interface_hash, cache_meta_from_dict(meta, data_json)\",\n        \"target\": \"mypy.build.write_cache\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 68,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 22,\n        \"src\": \"manager.log(f\\\"Error deleting cache file {filename}: {e.strerror}\\\")\",\n        \"target\": \"mypy.build.delete_cache\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 161,\n        \"src\": \"meta: CacheMeta | None = None\",\n        \"target\": \"mypy.build\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 120,\n        \"src\": \"if self.meta is not None:\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.interface_hash = self.meta.interface_hash\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.meta_source_hash = self.meta.hash\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 7,\n        \"src\": \"self.meta = validate_meta(self.meta, self.id, self.path, self.ignore_all, manager)\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"if self.meta:\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 3,\n        \"src\": \"self.dependencies = list(self.meta.dependencies)\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"self.suppressed = list(self.meta.suppressed)\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 3,\n        \"src\": \"assert len(all_deps) == len(self.meta.dep_prios)\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 68,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.priorities = {id: pri for id, pri in zip(all_deps, self.meta.dep_prios)}\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"assert len(all_deps) == len(self.meta.dep_lines)\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 72,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.dep_line_map = {id: line for id, line in zip(all_deps, self.meta.dep_lines)}\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 70,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 21,\n        \"src\": \"manager.log(f\\\"Deferring module to fine-grained update {path} ({id})\\\")\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 78,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 0,\n        \"src\": \"manager.log(f\\\"Deferring module to fine-grained update {path} ({id})\\\")\",\n        \"target\": \"mypy.build.State.__init__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 8,\n        \"src\": \"def xmeta(self) -> CacheMeta:\",\n        \"target\": \"mypy.build.State.xmeta\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (self: State) -> CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"def xmeta(self) -> CacheMeta:\",\n        \"target\": \"mypy.build\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"assert self.meta, \\\"missing meta on allegedly fresh module\\\"\",\n        \"target\": \"mypy.build.State.xmeta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.meta\",\n        \"target\": \"mypy.build.State.xmeta\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 25,\n        \"src\": \"self.meta is not None\",\n        \"target\": \"mypy.build.State.is_fresh\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"and self.dependencies == self.meta.dependencies\",\n        \"target\": \"mypy.build.State.is_fresh\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 59,\n        \"src\": \"self.meta is not None\",\n        \"target\": \"mypy.build.State.load_tree\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 3,\n        \"src\": \"data = _load_json_file(\",\n        \"target\": \"mypy.build.State.load_tree\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.meta.data_json, self.manager, \\\"Load tree \\\", \\\"Could not load tree: \\\"\",\n        \"target\": \"mypy.build.State.load_tree\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"if data is None:\",\n        \"target\": \"mypy.build.State.load_tree\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"self.tree = MypyFile.deserialize(data)\",\n        \"target\": \"mypy.build.State.load_tree\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, CacheMeta | None)\\\")\",\n        \"offset\": 409,\n        \"src\": \"new_interface_hash, self.meta = write_cache(\",\n        \"target\": \"mypy.build.State.write_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 80,\n        \"src\": \"if self.meta:\",\n        \"target\": \"mypy.build.State.generate_unused_ignore_notes\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 347,\n        \"src\": \"elif manager.stats.get(\\\"fresh_metas\\\", 0) > 0:\",\n        \"target\": \"mypy.build.dispatch\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"elif manager.stats.get(\\\"fresh_metas\\\", 0) > 0:\",\n        \"target\": \"mypy.build.dispatch\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"manager.stats.clear()\",\n        \"target\": \"mypy.build.dispatch\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 339,\n        \"src\": \"oldest_in_scc = min(graph[id].xmeta.data_mtime for id in scc)\",\n        \"target\": \"mypy.build.process_graph\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"viable = {id for id in stale_deps if graph[id].meta is not None}\",\n        \"target\": \"mypy.build.process_graph\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 2,\n        \"src\": \"0 if not viable else max(graph[dep].xmeta.data_mtime for dep in viable)\",\n        \"target\": \"mypy.build.process_graph\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 3,\n        \"src\": \"all_ids = sorted(ascc | viable, key=lambda id: graph[id].xmeta.data_mtime)\",\n        \"target\": \"mypy.build.process_graph\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 3,\n        \"src\": \"if graph[id].xmeta.data_mtime < newest_in_deps:\",\n        \"target\": \"mypy.build.process_graph\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 5,\n        \"src\": \"if graph[id].xmeta.data_mtime > oldest_in_scc:\",\n        \"target\": \"mypy.build.process_graph\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 4,\n        \"src\": \"manager.trace(\\\" %5s %.0f %s\\\" % (key, graph[id].xmeta.data_mtime, id))\",\n        \"target\": \"mypy.build.process_graph\"\n      }\n    ],\n    \"mypy/checker.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 781,\n        \"src\": \"elif isinstance(defn.impl, Decorator):\",\n        \"target\": \"mypy.checker.TypeChecker.check_overlapping_overloads\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 2246,\n        \"src\": \"if isinstance(sym.node, FuncBase):\",\n        \"target\": \"mypy.checker.TypeChecker.determine_type_of_member\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"return self.function_type(sym.node)\",\n        \"target\": \"mypy.checker.TypeChecker.determine_type_of_member\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 23,\n        \"message\": \"\\\"signature\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 409,\n        \"src\": \"if signature:\",\n        \"target\": \"mypy.checker.TypeChecker.check_assignment\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 24,\n        \"message\": \"\\\"rvalue_type\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 164,\n        \"src\": \"and rvalue_type\",\n        \"target\": \"mypy.checker.TypeChecker.check_assignment\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"\\\"compare_type\\\" has type \\\"ProperType\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 184,\n        \"src\": \"if compare_type:\",\n        \"target\": \"mypy.checker.TypeChecker.check_compatibility_super\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[tuple[Any, ...]]\\\")\",\n        \"offset\": 533,\n        \"src\": \"types, declared_types = zip(*clean_items)\",\n        \"target\": \"mypy.checker.TypeChecker.check_multi_assignment_from_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"types, declared_types = zip(*clean_items)\",\n        \"target\": \"mypy.checker.TypeChecker.check_multi_assignment_from_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 3,\n        \"src\": \"make_simplified_union(list(types)),\",\n        \"target\": \"mypy.checker.TypeChecker.check_multi_assignment_from_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"make_simplified_union(list(declared_types)),\",\n        \"target\": \"mypy.checker.TypeChecker.check_multi_assignment_from_union\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"\\\"var\\\" has type \\\"Var\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 364,\n        \"src\": \"if var and not self.current_node_deferred:\",\n        \"target\": \"mypy.checker.TypeChecker.set_inferred_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always false\",\n        \"offset\": 41,\n        \"src\": \"if isinstance(rvalue.callee, RefExpr) and isinstance(rvalue.callee.node, FuncBase):\",\n        \"target\": \"mypy.checker.TypeChecker.simple_rvalue\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"typ = rvalue.callee.node.type\",\n        \"target\": \"mypy.checker.TypeChecker.simple_rvalue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1828,\n        \"src\": \"if called_type.items[0].def_extras.get(\\\"first_arg\\\"):\",\n        \"target\": \"mypy.checker.TypeChecker.find_isinstance_check_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if called_type.items[0].def_extras.get(\\\"first_arg\\\"):\",\n        \"target\": \"mypy.checker.TypeChecker.find_isinstance_check_helper\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 9,\n        \"message\": \"Condition is always true\",\n        \"offset\": 2313,\n        \"src\": \"elif isinstance(t, FunctionLike):\",\n        \"target\": \"mypy.checker.is_more_general_arg_prefix\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(s, FunctionLike):\",\n        \"target\": \"mypy.checker.is_more_general_arg_prefix\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 9,\n        \"message\": \"Condition is always true\",\n        \"offset\": 418,\n        \"src\": \"elif isinstance(func, FuncBase):\",\n        \"target\": \"mypy.checker.is_static\"\n      }\n    ],\n    \"mypy/checkexpr.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 61,\n        \"message\": \"The type \\\"type[mypy.nodes.RefExpr]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 286,\n        \"src\": \"raise AssertionError(f\\\"Unknown RefExpr subclass: {type(expr)}\\\")\",\n        \"target\": \"mypy.checkexpr.extract_refexpr_names\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 34,\n        \"message\": \"\\\"item_name_expr\\\" has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 631,\n        \"src\": \"key_context = item_name_expr or item_arg\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.validate_typeddict_kwargs\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 23,\n        \"message\": \"Name \\\"actual_types\\\" may be undefined\",\n        \"offset\": 1762,\n        \"src\": \"assert len(actual_types) == len(actuals) == len(actual_kinds)\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 19,\n        \"message\": \"Name \\\"callee_arg_types\\\" may be undefined\",\n        \"offset\": 2,\n        \"src\": \"if len(callee_arg_types) != len(actual_types):\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 48,\n        \"message\": \"Name \\\"callee_arg_kinds\\\" may be undefined\",\n        \"offset\": 8,\n        \"src\": \"assert len(callee_arg_types) == len(callee_arg_kinds)\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always false\",\n        \"offset\": 4,\n        \"src\": \"if actual_type is None:\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_argument_types\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"continue  # Some kind of error was already reported.\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_argument_types\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[tuple[Any, ...]]\\\")\",\n        \"offset\": 126,\n        \"src\": \"returns, inferred_types = zip(*unioned_return)\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_overload_call\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"returns, inferred_types = zip(*unioned_return)\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_overload_call\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 6,\n        \"src\": \"make_simplified_union(list(returns), context.line, context.column),\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_overload_call\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 74,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.combine_function_signatures(get_proper_types(inferred_types)),\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_overload_call\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 46,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 634,\n        \"src\": \"name = f\\\"{context.callee.name} of {object_type}\\\"\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.check_intersection_call\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 224,\n        \"src\": \"elif use_reverse is UseReverse.ALWAYS:\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.visit_op_expr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 16,\n        \"message\": \"Name \\\"left_map\\\" may be undefined\",\n        \"offset\": 739,\n        \"src\": \"and left_map is None\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 16,\n        \"message\": \"Name \\\"right_map\\\" may be undefined\",\n        \"offset\": 8,\n        \"src\": \"and right_map is None\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 22,\n        \"message\": \"Name \\\"restricted_left_type\\\" may be undefined\",\n        \"offset\": 27,\n        \"src\": \"if isinstance(restricted_left_type, UninhabitedType):\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 13,\n        \"message\": \"Name \\\"result_is_left\\\" may be undefined\",\n        \"offset\": 3,\n        \"src\": \"elif result_is_left:\",\n        \"target\": \"mypy.checkexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1173,\n        \"src\": \"if called_type.items[0].def_extras.get(\\\"first_arg\\\") == target:\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.visit_lambda_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if called_type.items[0].def_extras.get(\\\"first_arg\\\") == target:\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.visit_lambda_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if called_type.items[0].def_extras.get(\\\"first_arg\\\") == target:\",\n        \"target\": \"mypy.checkexpr.ExpressionChecker.visit_lambda_expr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 82,\n        \"message\": \"Name \\\"t0\\\" may be undefined\",\n        \"offset\": 577,\n        \"src\": \"self.per_line_checking_time_ns[node.line] += time.perf_counter_ns() - t0\",\n        \"target\": \"mypy.checkexpr\"\n      }\n    ],\n    \"mypy/checkmember.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 7,\n        \"message\": \"\\\"result\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 890,\n        \"src\": \"if result and not mx.is_lvalue and not implicit:\",\n        \"target\": \"mypy.checkmember.analyze_var\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 48,\n        \"message\": \"Right operand of \\\"and\\\" is never evaluated\",\n        \"offset\": 267,\n        \"src\": \"isinstance(node.node, FuncBase) and node.node.is_class\",\n        \"target\": \"mypy.checkmember.analyze_class_attribute_access\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 48,\n        \"message\": \"Right operand of \\\"and\\\" is never evaluated\",\n        \"offset\": 3,\n        \"src\": \"isinstance(node.node, FuncBase) and node.node.is_static\",\n        \"target\": \"mypy.checkmember.analyze_class_attribute_access\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 47,\n        \"src\": \"typ = function_type(node.node, mx.named_type(\\\"builtins.function\\\"))\",\n        \"target\": \"mypy.checkmember.analyze_class_attribute_access\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 7,\n        \"message\": \"Condition is always false\",\n        \"offset\": 258,\n        \"src\": \"if isinstance(n, FuncBase):\",\n        \"target\": \"mypy.checkmember.is_valid_constructor\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"return True\",\n        \"target\": \"mypy.checkmember.is_valid_constructor\"\n      }\n    ],\n    \"mypy/checkpattern.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 218,\n        \"src\": \"elif value is None:\",\n        \"target\": \"mypy.checkpattern.PatternChecker.visit_singleton_pattern\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 20,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 468,\n        \"src\": \"message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format(\",\n        \"target\": \"mypy.checkpattern.PatternChecker.visit_class_pattern\"\n      }\n    ],\n    \"mypy/checkstrformat.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 16,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 724,\n        \"src\": \"\\\"Only index and member expressions are allowed in\\\"\",\n        \"target\": \"mypy.checkstrformat.StringFormatterChecker.validate_and_transform_accessors\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 55,\n        \"src\": \"elif isinstance(expr, StrExpr):\",\n        \"target\": \"mypy.checkstrformat.StringFormatterChecker.check_str_interpolation\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 163,\n        \"src\": \"elif isinstance(expr, StrExpr):\",\n        \"target\": \"mypy.checkstrformat.StringFormatterChecker.build_dict_type\"\n      }\n    ],\n    \"mypy/config_parser.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 28,\n        \"src\": \"_INI_PARSER_CALLABLE: _TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]\",\n        \"target\": \"mypy.config_parser\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 163,\n        \"src\": \"\\\"exclude\\\": lambda s: [s.strip()],\",\n        \"target\": \"\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 59,\n        \"src\": \"toml_data = tomllib.load(f)\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"toml_data = toml_data.get(\\\"tool\\\", {})\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[Any, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"toml_data = toml_data.get(\\\"tool\\\", {})\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if \\\"mypy\\\" not in toml_data:\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 2,\n        \"src\": \"toml_data = {\\\"mypy\\\": toml_data[\\\"mypy\\\"]}\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"toml_data = {\\\"mypy\\\": toml_data[\\\"mypy\\\"]}\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"toml_data = {\\\"mypy\\\": toml_data[\\\"mypy\\\"]}\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 16,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"parser: MutableMapping[str, Any] = destructure_overrides(toml_data)\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 73,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"parser: MutableMapping[str, Any] = destructure_overrides(toml_data)\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 77,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | RawConfigParser\\\")\",\n        \"offset\": 9,\n        \"src\": \"if config_file in defaults.SHARED_CONFIG_FILES and \\\"mypy\\\" not in parser:\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | RawConfigParser\\\")\",\n        \"offset\": 10,\n        \"src\": \"if \\\"mypy\\\" not in parser:\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 21,\n        \"message\": \"Name \\\"parser\\\" may be undefined\",\n        \"offset\": 0,\n        \"src\": \"if \\\"mypy\\\" not in parser:\",\n        \"target\": \"mypy.config_parser\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 23,\n        \"message\": \"Name \\\"file_read\\\" may be undefined\",\n        \"offset\": 1,\n        \"src\": \"if filename or file_read not in defaults.SHARED_CONFIG_FILES:\",\n        \"target\": \"mypy.config_parser\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | RawConfigParser\\\")\",\n        \"offset\": 3,\n        \"src\": \"section = parser[\\\"mypy\\\"]\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | SectionProxy\\\")\",\n        \"offset\": 0,\n        \"src\": \"section = parser[\\\"mypy\\\"]\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 19,\n        \"message\": \"Name \\\"file_read\\\" may be undefined\",\n        \"offset\": 1,\n        \"src\": \"prefix = f\\\"{file_read}: [mypy]: \\\"\",\n        \"target\": \"mypy.config_parser\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | SectionProxy\\\")\",\n        \"offset\": 2,\n        \"src\": \"prefix, options, set_strict_flags, section, config_types, stderr\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 56,\n        \"message\": \"Name \\\"config_types\\\" may be undefined\",\n        \"offset\": 0,\n        \"src\": \"prefix, options, set_strict_flags, section, config_types, stderr\",\n        \"target\": \"mypy.config_parser\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any) | (str, SectionProxy)\\\")\",\n        \"offset\": 6,\n        \"src\": \"for name, section in parser.items():\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | RawConfigParser\\\")\",\n        \"offset\": 0,\n        \"src\": \"for name, section in parser.items():\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict_items[str, Any] | ItemsView[str, SectionProxy]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for name, section in parser.items():\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | SectionProxy\\\")\",\n        \"offset\": 4,\n        \"src\": \"prefix, options, set_strict_flags, section, config_types, stderr\",\n        \"target\": \"mypy.config_parser.parse_config_file\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 60,\n        \"message\": \"Name \\\"config_types\\\" may be undefined\",\n        \"offset\": 0,\n        \"src\": \"prefix, options, set_strict_flags, section, config_types, stderr\",\n        \"target\": \"mypy.config_parser\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 53,\n        \"src\": \"def destructure_overrides(toml_data: dict[str, Any]) -> dict[str, Any]:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 32,\n        \"src\": \"if \\\"overrides\\\" not in toml_data[\\\"mypy\\\"]:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if \\\"overrides\\\" not in toml_data[\\\"mypy\\\"]:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return toml_data\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(toml_data[\\\"mypy\\\"][\\\"overrides\\\"], list):\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not isinstance(toml_data[\\\"mypy\\\"][\\\"overrides\\\"], list):\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"result = toml_data.copy()\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"for override in result[\\\"mypy\\\"][\\\"overrides\\\"]:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for override in result[\\\"mypy\\\"][\\\"overrides\\\"]:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for override in result[\\\"mypy\\\"][\\\"overrides\\\"]:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if \\\"module\\\" not in override:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"if isinstance(override[\\\"module\\\"], str):\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"modules = [override[\\\"module\\\"]]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(override[\\\"module\\\"], list):\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"modules = override[\\\"module\\\"]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"module_overrides = override.copy()\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"del module_overrides[\\\"module\\\"]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"del module_overrides[\\\"module\\\"]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"if old_config_name not in result:\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"result[old_config_name] = module_overrides\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"result[old_config_name] = module_overrides\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"for new_key, new_value in module_overrides.items():\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for new_key, new_value in module_overrides.items():\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"new_key in result[old_config_name]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"False | Any\\\")\",\n        \"offset\": 0,\n        \"src\": \"new_key in result[old_config_name]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"new_key in result[old_config_name]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"new_key in result[old_config_name]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"and result[old_config_name][new_key] != new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"and result[old_config_name][new_key] != new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"and result[old_config_name][new_key] != new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"and result[old_config_name][new_key] != new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"result[old_config_name][new_key] = new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"result[old_config_name][new_key] = new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"result[old_config_name][new_key] = new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"result[old_config_name][new_key] = new_value\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"del result[\\\"mypy\\\"][\\\"overrides\\\"]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"del result[\\\"mypy\\\"][\\\"overrides\\\"]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"del result[\\\"mypy\\\"][\\\"overrides\\\"]\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return result\",\n        \"target\": \"mypy.config_parser.destructure_overrides\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def parse_section(\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 22,\n        \"src\": \"for key in section:\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"if key in config_types:\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"ct = config_types[key]\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ct = config_types[key]\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"f\\\"{prefix}Unrecognized option: {key} = {section[key]}\\\"\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"f\\\"{prefix}Unrecognized option: {key} = {section[key]}\\\"\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 11,\n        \"src\": \"report_dirs[report_type] = str(section[key])\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"report_dirs[report_type] = str(section[key])\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 21,\n        \"src\": \"print(f\\\"{prefix}Unrecognized option: {key} = {section[key]}\\\", file=stderr)\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"print(f\\\"{prefix}Unrecognized option: {key} = {section[key]}\\\", file=stderr)\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"v: Any = None\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if ct is bool:\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(section, dict):\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"v = section.getboolean(key)  # type: ignore[attr-defined]  # Until better stub\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": null,\n        \"column\": 24,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"v = section.getboolean(key)  # type: ignore[attr-defined]  # Until better stub\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"v = not v\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif callable(ct):\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"v = ct(section.get(key))\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"v = ct(section.get(key))\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"v = ct(section.get(key))\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"if v:\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"results[options_key] = v\",\n        \"target\": \"mypy.config_parser.parse_section\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 11,\n        \"src\": \"def convert_to_boolean(value: Any | None) -> bool:\",\n        \"target\": \"mypy.config_parser.convert_to_boolean\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(value, bool):\",\n        \"target\": \"mypy.config_parser.convert_to_boolean\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(value, str):\",\n        \"target\": \"mypy.config_parser.convert_to_boolean\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"value = str(value)\",\n        \"target\": \"mypy.config_parser.convert_to_boolean\"\n      }\n    ],\n    \"mypy/constant_fold.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 144,\n        \"src\": \"ret = left**right\",\n        \"target\": \"mypy.constant_fold.constant_fold_binary_int_op\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(ret, int)\",\n        \"target\": \"mypy.constant_fold.constant_fold_binary_int_op\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | float\\\")\",\n        \"offset\": 25,\n        \"src\": \"ret = left**right\",\n        \"target\": \"mypy.constant_fold.constant_fold_binary_float_op\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | float\\\")\",\n        \"offset\": 4,\n        \"src\": \"assert isinstance(ret, float), ret\",\n        \"target\": \"mypy.constant_fold.constant_fold_binary_float_op\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert isinstance(ret, float), ret\",\n        \"target\": \"mypy.constant_fold.constant_fold_binary_float_op\"\n      }\n    ],\n    \"mypy/constraints.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always false\",\n        \"offset\": 133,\n        \"src\": \"if actual is None and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):\",\n        \"target\": \"mypy.constraints.infer_constraints_for_callable\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 34,\n        \"message\": \"Right operand of \\\"and\\\" is never evaluated\",\n        \"offset\": 0,\n        \"src\": \"if actual is None and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):\",\n        \"target\": \"mypy.constraints.infer_constraints_for_callable\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 3,\n        \"src\": \"incomplete_star_mapping = True\",\n        \"target\": \"mypy.constraints.infer_constraints_for_callable\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 52,\n        \"src\": \"elif isinstance(unpacked_type, TupleType):\",\n        \"target\": \"mypy.constraints.infer_constraints_for_callable\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always true\",\n        \"offset\": 405,\n        \"src\": \"if option is not None:\",\n        \"target\": \"mypy.constraints.any_constraints\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 3,\n        \"src\": \"merged_option = None\",\n        \"target\": \"mypy.constraints.any_constraints\"\n      }\n    ],\n    \"mypy/copytype.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 44,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 130,\n        \"src\": \"return self.copy_common(t, TypeType(cast(Any, t.item)))\",\n        \"target\": \"mypy.copytype.TypeShallowCopier.visit_type_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return self.copy_common(t, TypeType(cast(Any, t.item)))\",\n        \"target\": \"mypy.copytype.TypeShallowCopier.visit_type_type\"\n      }\n    ],\n    \"mypy/dmypy/client.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 274,\n        \"src\": \"if args.version:\",\n        \"target\": \"mypy.dmypy.client.main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"if not args.action:\",\n        \"target\": \"mypy.dmypy.client.main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 6,\n        \"src\": \"fail(err.args[0])\",\n        \"target\": \"mypy.dmypy.client.main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"fail(err.args[0])\",\n        \"target\": \"mypy.dmypy.client.main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 42,\n        \"src\": \"get_status(args.status_file)\",\n        \"target\": \"mypy.dmypy.client.do_start\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 34,\n        \"src\": \"start_options = process_start_options(args.flags, allow_sources)\",\n        \"target\": \"mypy.dmypy.client.start_server\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if daemonize(start_options, args.status_file, timeout=args.timeout, log_file=args.log_file):\",\n        \"target\": \"mypy.dmypy.client.start_server\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if daemonize(start_options, args.status_file, timeout=args.timeout, log_file=args.log_file):\",\n        \"target\": \"mypy.dmypy.client.start_server\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 81,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if daemonize(start_options, args.status_file, timeout=args.timeout, log_file=args.log_file):\",\n        \"target\": \"mypy.dmypy.client.start_server\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"wait_for_server(args.status_file)\",\n        \"target\": \"mypy.dmypy.client.start_server\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 37,\n        \"src\": \"if not is_running(args.status_file):\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"response = request(\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"args.status_file,\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"args=args.flags,\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"export_types=args.export_types,\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"if \\\"restart\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"print(f\\\"Restarting: {response['restart']}\\\")\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"print(f\\\"Restarting: {response['restart']}\\\")\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"args.status_file,\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"args=args.flags,\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"export_types=args.export_types,\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"response[\\\"roundtrip_time\\\"] = t1 - t0\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"status = read_status(args.status_file)\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if args.verbose:\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"response = request(\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"args.status_file, \\\"status\\\", fswatcher_dump_file=args.fswatcher_dump_file, timeout=5\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"args.status_file, \\\"status\\\", fswatcher_dump_file=args.fswatcher_dump_file, timeout=5\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if args.verbose or \\\"error\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if args.verbose or \\\"error\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if args.verbose or \\\"error\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"show_stats(response)\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if \\\"error\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.do_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 9,\n        \"src\": \"response = request(args.status_file, \\\"stop\\\", timeout=5)\",\n        \"target\": \"mypy.dmypy.client.do_stop\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response = request(args.status_file, \\\"stop\\\", timeout=5)\",\n        \"target\": \"mypy.dmypy.client.do_stop\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if \\\"error\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.do_stop\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"show_stats(response)\",\n        \"target\": \"mypy.dmypy.client.do_stop\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"pid, _ = get_status(args.status_file)\",\n        \"target\": \"mypy.dmypy.client.do_kill\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 13,\n        \"src\": \"response = request(args.status_file, \\\"check\\\", files=args.files, export_types=args.export_types)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response = request(args.status_file, \\\"check\\\", files=args.files, export_types=args.export_types)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response = request(args.status_file, \\\"check\\\", files=args.files, export_types=args.export_types)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 81,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response = request(args.status_file, \\\"check\\\", files=args.files, export_types=args.export_types)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"response[\\\"roundtrip_time\\\"] = t1 - t0\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 19,\n        \"src\": \"if args.remove is not None or args.update is not None:\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if args.remove is not None or args.update is not None:\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"response = request(\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"args.status_file,\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"export_types=args.export_types,\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"remove=args.remove,\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"update=args.update,\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"response = request(args.status_file, \\\"recheck\\\", export_types=args.export_types)\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 69,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response = request(args.status_file, \\\"recheck\\\", export_types=args.export_types)\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"response[\\\"roundtrip_time\\\"] = t1 - t0\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\",\n        \"target\": \"mypy.dmypy.client.do_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 10,\n        \"src\": \"response = request(\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"args.status_file,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"function=args.function,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"json=args.json,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"callsites=args.callsites,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"no_errors=args.no_errors,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"no_any=args.no_any,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"flex_any=args.flex_any,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"use_fixme=args.use_fixme,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"max_guesses=args.max_guesses,\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"check_output(response, verbose=False, junit_xml=None, perf_stats_file=None)\",\n        \"target\": \"mypy.dmypy.client.do_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"response = request(\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"args.status_file,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"show=args.show,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"location=args.location,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"verbosity=args.verbose,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"limit=args.limit,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"include_span=args.include_span,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"include_kind=args.include_kind,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"include_object_attrs=args.include_object_attrs,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"union_attrs=args.union_attrs,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"force_reload=args.force_reload,\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"check_output(response, verbose=False, junit_xml=None, perf_stats_file=None)\",\n        \"target\": \"mypy.dmypy.client.do_inspect\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def check_output(\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"if \\\"error\\\" in response:\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"fail(response[\\\"error\\\"])\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"fail(response[\\\"error\\\"])\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"out, err, status_code = response[\\\"out\\\"], response[\\\"err\\\"], response[\\\"status\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"out, err, status_code = response[\\\"out\\\"], response[\\\"err\\\"], response[\\\"status\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"out, err, status_code = response[\\\"out\\\"], response[\\\"err\\\"], response[\\\"status\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"out, err, status_code = response[\\\"out\\\"], response[\\\"err\\\"], response[\\\"status\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"out, err, status_code = response[\\\"out\\\"], response[\\\"err\\\"], response[\\\"status\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"out, err, status_code = response[\\\"out\\\"], response[\\\"err\\\"], response[\\\"status\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"fail(f\\\"Response: {str(response)}\\\")\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"sys.stdout.write(out)\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"sys.stderr.write(err)\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"show_stats(response)\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"messages = (out + err).splitlines()\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"messages = (out + err).splitlines()\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"messages = (out + err).splitlines()\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"response[\\\"roundtrip_time\\\"],\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response[\\\"roundtrip_time\\\"],\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"bool(err),\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(None, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"{None: messages} if messages else {},\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{None: messages} if messages else {},\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{None: messages} if messages else {},\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"response[\\\"python_version\\\"],\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response[\\\"python_version\\\"],\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"response[\\\"platform\\\"],\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"response[\\\"platform\\\"],\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"telemetry = response.get(\\\"stats\\\", {})\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"telemetry = response.get(\\\"stats\\\", {})\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[Any, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"telemetry = response.get(\\\"stats\\\", {})\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"json.dump(telemetry, f)\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if status_code:\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"sys.exit(status_code)\",\n        \"target\": \"mypy.dmypy.client.check_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 18,\n        \"src\": \"print(request(args.status_file, \\\"hang\\\", timeout=1))\",\n        \"target\": \"mypy.dmypy.client.do_hang\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"print(request(args.status_file, \\\"hang\\\", timeout=1))\",\n        \"target\": \"mypy.dmypy.client.do_hang\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"if args.log_file:\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"sys.stdout = sys.stderr = open(args.log_file, \\\"a\\\", buffering=1)\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if args.legacy:\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if args.options_data:\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"options_dict = pickle.loads(base64.b64decode(args.options_data))\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"options_dict = pickle.loads(base64.b64decode(args.options_data))\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"options = options_obj.apply_changes(options_dict)\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"options = process_start_options(args.flags, allow_sources=False)\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if args.legacy:\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"Server(options, args.status_file, timeout=args.timeout).serve()\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"Server(options, args.status_file, timeout=args.timeout).serve()\",\n        \"target\": \"mypy.dmypy.client.do_daemon\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 12,\n        \"src\": \"def request(\",\n        \"target\": \"mypy.dmypy.client.request\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 19,\n        \"src\": \"args[\\\"is_tty\\\"] = sys.stdout.isatty() or should_force_color()\",\n        \"target\": \"mypy.dmypy.client.request\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"args[\\\"is_tty\\\"] = sys.stdout.isatty() or should_force_color()\",\n        \"target\": \"mypy.dmypy.client.request\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 21,\n        \"src\": \"return {\\\"error\\\": str(err)}\",\n        \"target\": \"mypy.dmypy.client.request\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 17,\n        \"src\": \"def check_status(data: dict[str, Any]) -> tuple[int, str]:\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"if \\\"pid\\\" not in data:\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"pid = data[\\\"pid\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"pid = data[\\\"pid\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not isinstance(pid, int):\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"if \\\"connection_name\\\" not in data:\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"connection_name = data[\\\"connection_name\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"connection_name = data[\\\"connection_name\\\"]\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not isinstance(connection_name, str):\",\n        \"target\": \"mypy.dmypy.client.check_status\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 15,\n        \"src\": \"data: Any = json.load(f)\",\n        \"target\": \"mypy.dmypy.client.read_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if not isinstance(data, dict):\",\n        \"target\": \"mypy.dmypy.client.read_status\"\n      }\n    ],\n    \"mypy/dmypy_server.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 210,\n        \"src\": \"return {\\\"platform\\\": self.options.platform, \\\"python_version\\\": py_version}\",\n        \"target\": \"mypy.dmypy_server.Server._response_metadata\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {\\\"platform\\\": self.options.platform, \\\"python_version\\\": py_version}\",\n        \"target\": \"mypy.dmypy_server.Server._response_metadata\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 16,\n        \"src\": \"data = receive(server)\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"sys.stdout = WriteToConn(server, \\\"stdout\\\", sys.stdout.isatty())\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"sys.stderr = WriteToConn(server, \\\"stderr\\\", sys.stderr.isatty())\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 20,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"resp: dict[str, Any] = {}\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if \\\"command\\\" not in data:\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"command = data[\\\"command\\\"]\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not isinstance(command, str):\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"command = data.pop(\\\"command\\\")\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"resp = self.run_command(command, data)\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"resp = self.run_command(command, data)\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"resp.update(self._response_metadata())\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"resp[\\\"final\\\"] = True\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"send(server, resp)\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | dict[str, object]\\\")\",\n        \"offset\": 2,\n        \"src\": \"resp[\\\"final\\\"] = True\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | dict[str, object]\\\")\",\n        \"offset\": 2,\n        \"src\": \"resp.update(self._response_metadata())\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | dict[str, object]\\\")\",\n        \"offset\": 1,\n        \"src\": \"send(server, resp)\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 3,\n        \"src\": \"if command == \\\"stop\\\":\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if command == \\\"stop\\\":\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 13,\n        \"src\": \"if command != \\\"stop\\\":\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if command != \\\"stop\\\":\",\n        \"target\": \"mypy.dmypy_server.Server.serve\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 13,\n        \"src\": \"method = getattr(self.__class__, key, None)\",\n        \"target\": \"mypy.dmypy_server.Server.run_command\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if method is None:\",\n        \"target\": \"mypy.dmypy_server.Server.run_command\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"ret = method(self, **data)\",\n        \"target\": \"mypy.dmypy_server.Server.run_command\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(ret, dict)\",\n        \"target\": \"mypy.dmypy_server.Server.run_command\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"res.update(get_meminfo())\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 59,\n        \"src\": \"return self.check(sources, export_types, is_tty, terminal_width)\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 10,\n        \"src\": \"return self.check(sources, export_types, is_tty, terminal_width)\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 47,\n        \"src\": \"res = self.increment_output(messages, sources, is_tty, terminal_width)\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"self.update_stats(res)\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_recheck\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return res\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_recheck\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def check(\",\n        \"target\": \"mypy.dmypy_server.Server.check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 11,\n        \"src\": \"res = self.initialize_fine_grained(sources, is_tty, terminal_width)\",\n        \"target\": \"mypy.dmypy_server.Server.check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 10,\n        \"src\": \"self.update_stats(res)\",\n        \"target\": \"mypy.dmypy_server.Server.check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return res\",\n        \"target\": \"mypy.dmypy_server.Server.check\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 7,\n        \"src\": \"def update_stats(self, res: dict[str, Any]) -> None:\",\n        \"target\": \"mypy.dmypy_server.Server.update_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"res[\\\"stats\\\"] = manager.stats\",\n        \"target\": \"mypy.dmypy_server.Server.update_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"res[\\\"stats\\\"] = manager.stats\",\n        \"target\": \"mypy.dmypy_server.Server.update_stats\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 8,\n        \"src\": \"def initialize_fine_grained(\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 15,\n        \"src\": \"return {\\\"out\\\": out, \\\"err\\\": err, \\\"status\\\": 2}\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 19,\n        \"src\": \"meta = state.meta\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if meta is None:\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 5,\n        \"src\": \"FileData(st_mtime=float(meta.mtime), st_size=meta.size, hash=meta.hash),\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"FileData(st_mtime=float(meta.mtime), st_size=meta.size, hash=meta.hash),\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 81,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta\\\")\",\n        \"offset\": 0,\n        \"src\": \"FileData(st_mtime=float(meta.mtime), st_size=meta.size, hash=meta.hash),\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 46,\n        \"src\": \"return {\\\"out\\\": \\\"\\\".join(s + \\\"\\\\n\\\" for s in messages), \\\"err\\\": \\\"\\\", \\\"status\\\": status}\",\n        \"target\": \"mypy.dmypy_server.Server.initialize_fine_grained\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 277,\n        \"src\": \"def increment_output(\",\n        \"target\": \"mypy.dmypy_server.Server.increment_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"return {\\\"out\\\": \\\"\\\".join(s + \\\"\\\\n\\\" for s in messages), \\\"err\\\": \\\"\\\", \\\"status\\\": status}\",\n        \"target\": \"mypy.dmypy_server.Server.increment_output\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 144,\n        \"src\": \"def cmd_suggest(self, function: str, callsites: bool, **kwargs: Any) -> dict[str, object]:\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"engine = SuggestionEngine(self.fine_grained_manager, **kwargs)\",\n        \"target\": \"mypy.dmypy_server.Server.cmd_suggest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 29,\n        \"src\": \"def get_meminfo() -> dict[str, Any]:\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"res: dict[str, Any] = {}\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"res[\\\"memory_psutil_missing\\\"] = (\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"pmem\\\")\",\n        \"offset\": 6,\n        \"src\": \"meminfo = process.memory_info()\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"res[\\\"memory_rss_mib\\\"] = meminfo.rss / MiB\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"pmem\\\")\",\n        \"offset\": 0,\n        \"src\": \"res[\\\"memory_rss_mib\\\"] = meminfo.rss / MiB\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"res[\\\"memory_rss_mib\\\"] = meminfo.rss / MiB\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"res[\\\"memory_vms_mib\\\"] = meminfo.vms / MiB\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"pmem\\\")\",\n        \"offset\": 0,\n        \"src\": \"res[\\\"memory_vms_mib\\\"] = meminfo.vms / MiB\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"res[\\\"memory_vms_mib\\\"] = meminfo.vms / MiB\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 13,\n        \"src\": \"return res\",\n        \"target\": \"mypy.dmypy_server.get_meminfo\"\n      }\n    ],\n    \"mypy/dmypy_util.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 19,\n        \"src\": \"def receive(connection: IPCBase) -> Any:\",\n        \"target\": \"mypy.dmypy_util.receive\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 53,\n        \"message\": \"The type \\\"type[list[dict[str, ...] | list[...] | float | int | bool | str | None]]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 14,\n        \"src\": \"raise OSError(f\\\"Data received is not a dict ({type(data)})\\\")\",\n        \"target\": \"mypy.dmypy_util.receive\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 53,\n        \"message\": \"The type \\\"type[float]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 0,\n        \"src\": \"raise OSError(f\\\"Data received is not a dict ({type(data)})\\\")\",\n        \"target\": \"mypy.dmypy_util.receive\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 53,\n        \"message\": \"The type \\\"type[int]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 0,\n        \"src\": \"raise OSError(f\\\"Data received is not a dict ({type(data)})\\\")\",\n        \"target\": \"mypy.dmypy_util.receive\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 53,\n        \"message\": \"The type \\\"type[str]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 0,\n        \"src\": \"raise OSError(f\\\"Data received is not a dict ({type(data)})\\\")\",\n        \"target\": \"mypy.dmypy_util.receive\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 53,\n        \"message\": \"The type \\\"type[None]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 0,\n        \"src\": \"raise OSError(f\\\"Data received is not a dict ({type(data)})\\\")\",\n        \"target\": \"mypy.dmypy_util.receive\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 4,\n        \"src\": \"def send(connection: IPCBase, data: Any) -> None:\",\n        \"target\": \"mypy.dmypy_util.send\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"connection.write(json.dumps(data))\",\n        \"target\": \"mypy.dmypy_util.send\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 65,\n        \"src\": \"resp: dict[str, Any] = {self.output_key: output}\",\n        \"target\": \"mypy.dmypy_util.WriteToConn.write\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"send(self.server, resp)\",\n        \"target\": \"mypy.dmypy_util.WriteToConn.write\"\n      }\n    ],\n    \"mypy/errors.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 232,\n        \"src\": \"elif callable(self._filter):\",\n        \"target\": \"mypy.errors.ErrorWatcher.on_error\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"options\\\" has type \\\"Options\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 516,\n        \"src\": \"if self.options:\",\n        \"target\": \"mypy.errors.Errors.is_error_code_enabled\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 69,\n        \"message\": \"Member \\\"options\\\" has type \\\"Options\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 33,\n        \"src\": \"is_typeshed_file(self.options.abs_custom_typeshed_dir if self.options else None, file)\",\n        \"target\": \"mypy.errors.Errors.generate_unused_ignore_errors\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 69,\n        \"message\": \"Member \\\"options\\\" has type \\\"Options\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 53,\n        \"src\": \"is_typeshed_file(self.options.abs_custom_typeshed_dir if self.options else None, file)\",\n        \"target\": \"mypy.errors.Errors.generate_ignore_without_code_errors\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always false\",\n        \"offset\": 423,\n        \"src\": \"if isinstance(e.message, ErrorMessage):\",\n        \"target\": \"mypy.errors.Errors.render_messages\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"result.append(\",\n        \"target\": \"mypy.errors.Errors.render_messages\"\n      }\n    ],\n    \"mypy/evalexpr.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 30,\n        \"src\": \"return ast.literal_eval(f\\\"b'{o.value}'\\\")\",\n        \"target\": \"mypy.evalexpr._NodeEvaluator.visit_bytes_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"return ast.literal_eval(f'b\\\"{o.value}\\\"')\",\n        \"target\": \"mypy.evalexpr._NodeEvaluator.visit_bytes_expr\"\n      }\n    ],\n    \"mypy/fastparse.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 169,\n        \"src\": \"Match = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchValue = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchSingleton = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchSequence = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchStar = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchMapping = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchClass = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchAs = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"MatchOr = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"TryStar = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 8,\n        \"src\": \"ast_TypeAlias = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"ast_ParamSpec = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"ast_TypeVar = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"ast_TypeVarTuple = Any\",\n        \"target\": \"mypy.fastparse\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 46,\n        \"src\": \"tree = ASTConverter(\",\n        \"target\": \"mypy.fastparse.parse\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 21,\n        \"src\": \"assert isinstance(tree, MypyFile)\",\n        \"target\": \"mypy.fastparse.parse\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 153,\n        \"src\": \"self.visitor_cache: dict[type, Callable[[AST | None], Any]] = {}\",\n        \"target\": \"mypy.fastparse.ASTConverter.__init__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 21,\n        \"src\": \"def visit(self, node: AST | None) -> Any:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[type, (AST | None) -> Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"visitor = self.visitor_cache.get(typeobj)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(AST | None) -> Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"visitor = self.visitor_cache.get(typeobj)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(AST | None) -> Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if visitor is None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[type, (AST | None) -> Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"self.visitor_cache[typeobj] = visitor\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(AST | None) -> Any | Any\\\")\",\n        \"offset\": 0,\n        \"src\": \"self.visitor_cache[typeobj] = visitor\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return visitor(node)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 13,\n        \"src\": \"exp = self.visit(e)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_opt_expr_list\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"res.append(exp)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_opt_expr_list\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 60,\n        \"src\": \"node = self.visit(stmt)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_stmt_list\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"res.append(node)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_stmt_list\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 436,\n        \"src\": \"and func_type_ast.argtypes[0].value is Ellipsis\",\n        \"target\": \"mypy.fastparse.ASTConverter.do_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 74,\n        \"src\": \"end_line = getattr(n, \\\"end_lineno\\\", None)\",\n        \"target\": \"mypy.fastparse.ASTConverter.do_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"end_column = getattr(n, \\\"end_col_offset\\\", None)\",\n        \"target\": \"mypy.fastparse.ASTConverter.do_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 25,\n        \"src\": \"deco.set_line(first.lineno, first.col_offset, end_line, end_column)\",\n        \"target\": \"mypy.fastparse.ASTConverter.do_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 68,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"deco.set_line(first.lineno, first.col_offset, end_line, end_column)\",\n        \"target\": \"mypy.fastparse.ASTConverter.do_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 23,\n        \"src\": \"posonlyargs = getattr(args, \\\"posonlyargs\\\", cast(list[ast3.arg], []))\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 1,\n        \"src\": \"args_args = posonlyargs + args.args\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 2,\n        \"src\": \"num_no_defaults = len(args_args) - len(args_defaults)\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(int, Any | arg)\\\")\",\n        \"offset\": 2,\n        \"src\": \"for i, a in enumerate(args_args[:num_no_defaults]):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | arg\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, a in enumerate(args_args[:num_no_defaults]):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"enumerate[Any | arg]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, a in enumerate(args_args[:num_no_defaults]):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, a in enumerate(args_args[:num_no_defaults]):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 1,\n        \"src\": \"pos_only = i < len(posonlyargs)\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | arg\\\")\",\n        \"offset\": 1,\n        \"src\": \"new_args.append(self.make_argument(a, None, ARG_POS, no_type_check, pos_only))\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | arg\\\")\",\n        \"offset\": 1,\n        \"src\": \"names.append(a)\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(int, (Any | arg, expr))\\\")\",\n        \"offset\": 3,\n        \"src\": \"for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any | arg, expr)\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"enumerate[(Any | arg, expr)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[(Any | arg, expr)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | list[arg]\\\")\",\n        \"offset\": 1,\n        \"src\": \"pos_only = num_no_defaults + i < len(posonlyargs)\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | arg\\\")\",\n        \"offset\": 1,\n        \"src\": \"new_args.append(self.make_argument(a, d, ARG_OPT, no_type_check, pos_only))\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | arg\\\")\",\n        \"offset\": 1,\n        \"src\": \"names.append(a)\",\n        \"target\": \"mypy.fastparse.ASTConverter.transform_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 48,\n        \"src\": \"argument = Argument(Var(arg.arg, arg_type), arg_type, self.visit(default), kind, pos_only)\",\n        \"target\": \"mypy.fastparse.ASTConverter.make_argument\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | int | None\\\")\",\n        \"offset\": 4,\n        \"src\": \"getattr(arg, \\\"end_lineno\\\", None),\",\n        \"target\": \"mypy.fastparse.ASTConverter.make_argument\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | int | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"getattr(arg, \\\"end_col_offset\\\", None),\",\n        \"target\": \"mypy.fastparse.ASTConverter.make_argument\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 14,\n        \"src\": \"keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 13,\n        \"src\": \"metaclass=dict(keywords).get(\\\"metaclass\\\"),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"metaclass=dict(keywords).get(\\\"metaclass\\\"),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"metaclass=dict(keywords).get(\\\"metaclass\\\"),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 1,\n        \"src\": \"keywords=keywords,\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ClassDef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 72,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 15,\n        \"src\": \"incorrect_expr = find_disallowed_expression_in_annotation_scope(type_param.bound)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"type_param.lineno,\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_param.col_offset,\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"type_param.lineno,\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_param.col_offset,\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"type_param.lineno,\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_param.col_offset,\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_param\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def translate_type_params(self, type_params: list[Any]) -> list[TypeParam]:\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"for p in type_params:\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for p in type_params:\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"if isinstance(p, ast_ParamSpec):  # type: ignore[misc]\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": null,\n        \"column\": 26,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"if isinstance(p, ast_ParamSpec):  # type: ignore[misc]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if isinstance(p, ast_ParamSpec):  # type: ignore[misc]\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": null,\n        \"column\": 29,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"if isinstance(p, ast_ParamSpec):  # type: ignore[misc]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"explicit_type_params.append(TypeParam(p.name, PARAM_SPEC_KIND, None, [], default))\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(p, ast_TypeVarTuple):  # type: ignore[misc]\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": null,\n        \"column\": 28,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"elif isinstance(p, ast_TypeVarTuple):  # type: ignore[misc]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"elif isinstance(p, ast_TypeVarTuple):  # type: ignore[misc]\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": null,\n        \"column\": 31,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"elif isinstance(p, ast_TypeVarTuple):  # type: ignore[misc]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"TypeParam(p.name, TYPE_VAR_TUPLE_KIND, None, [], default)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(p.bound, ast3.Tuple):\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if len(p.bound.elts) < 2:\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"p.lineno,\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"p.col_offset,\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"conv = TypeConverter(self.errors, line=p.lineno)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"values = [conv.visit(t) for t in p.bound.elts]\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif p.bound is not None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.validate_type_param(p)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"bound = TypeConverter(self.errors, line=p.lineno).visit(p.bound)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 76,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"bound = TypeConverter(self.errors, line=p.lineno).visit(p.bound)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"TypeParam(p.name, TYPE_VAR_KIND, bound, values, default)\",\n        \"target\": \"mypy.fastparse.ASTConverter.translate_type_params\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"node = ReturnStmt(self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Return\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"node = DelStmt(self.visit(n.targets[0]))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Delete\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"rvalue = self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Assign\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"s = AssignmentStmt(lvalues, rvalue, type=typ, new_syntax=False)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Assign\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"s = AssignmentStmt([self.visit(n.target)], rvalue, type=typ, new_syntax=True)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AnnAssign\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"self.from_operator(n.op), self.visit(n.target), self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AugAssign\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.from_operator(n.op), self.visit(n.target), self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AugAssign\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"self.visit(n.target),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_For\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.visit(n.iter),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_For\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"self.visit(n.target),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AsyncFor\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.visit(n.iter),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AsyncFor\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"self.visit(n.test), self.as_required_block(n.body), self.as_block(n.orelse)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_While\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"[self.visit(n.test)], [self.as_required_block(n.body)], self.as_block(n.orelse)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_If\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"[self.visit(i.context_expr) for i in n.items],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_With\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[self.visit(i.optional_vars) for i in n.items],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_With\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"[self.visit(i.context_expr) for i in n.items],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AsyncWith\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[self.visit(i.optional_vars) for i in n.items],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_AsyncWith\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"node = RaiseStmt(self.visit(n.exc), self.visit(n.cause))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Raise\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = RaiseStmt(self.visit(n.exc), self.visit(n.cause))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Raise\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Try\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Try\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"types,\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Try\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"vs = [\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 88,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"types = [self.visit(h.type) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"handlers = [self.as_required_block(h.body) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"handlers = [self.as_required_block(h.body) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"handlers = [self.as_required_block(h.body) for h in n.handlers]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"self.as_required_block(n.body),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"types,\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.as_block(n.orelse),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.as_block(n.finalbody),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TryStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"node = AssertStmt(self.visit(n.test), self.visit(n.msg))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Assert\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = AssertStmt(self.visit(n.test), self.visit(n.msg))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Assert\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 46,\n        \"src\": \"value = self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"node = ExpressionStmt(value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 21,\n        \"src\": \"s = AssignmentExpr(self.visit(n.target), self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_NamedExpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"s = AssignmentExpr(self.visit(n.target), self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_NamedExpr\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 29,\n        \"src\": \"if op is None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_BinOp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"e = OpExpr(op, self.visit(n.left), self.visit(n.right))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_BinOp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"e = OpExpr(op, self.visit(n.left), self.visit(n.right))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_BinOp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 18,\n        \"src\": \"e = UnaryExpr(op, self.visit(n.operand))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_UnaryOp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 17,\n        \"src\": \"e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_IfExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_IfExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 68,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_IfExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 27,\n        \"src\": \"targets = [self.visit(c.target) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"targets = [self.visit(c.target) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"iters = [self.visit(c.iter) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"iters = [self.visit(c.iter) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_DictComp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"targets = [self.visit(c.target) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"targets = [self.visit(c.target) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"iters = [self.visit(c.iter) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"iters = [self.visit(c.iter) for c in n.generators]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_GeneratorExp\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"v = self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Await\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"e = AwaitExpr(v)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Await\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"e = YieldExpr(self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Yield\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"e = YieldFromExpr(self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_YieldFrom\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 23,\n        \"src\": \"self.visit(n.func),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Call\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"cast(\\\"list[Optional[str]]\\\", [None] * len(args)) + keyword_names,\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Call\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"def visit_Constant(self, n: Constant) -> Any:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"val = n.value\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"e: Any = None\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if val is None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(val, str):\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(val, bytes):\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(val, bool):  # Must check before int!\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(val, int):\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(val, float):\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(val, complex):\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif val is Ellipsis:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 69,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"raise RuntimeError(\\\"Constant not implemented for \\\" + str(type(val)))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 74,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"raise RuntimeError(\\\"Constant not implemented for \\\" + str(type(val)))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return self.set_line(e, n)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return self.set_line(e, n)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 32,\n        \"src\": \"val_exp = self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_FormattedValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"val_exp.set_line(n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_FormattedValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"format_spec_exp = self.visit(n.format_spec) if n.format_spec is not None else StrExpr(\\\"\\\")\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_FormattedValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | StrExpr\\\")\",\n        \"offset\": 0,\n        \"src\": \"format_spec_exp = self.visit(n.format_spec) if n.format_spec is not None else StrExpr(\\\"\\\")\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_FormattedValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"format_method, [val_exp, format_spec_exp], [ARG_POS, ARG_POS], [None, None]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_FormattedValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | StrExpr\\\")\",\n        \"offset\": 0,\n        \"src\": \"format_method, [val_exp, format_spec_exp], [ARG_POS, ARG_POS], [None, None]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_FormattedValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"member_expr = MemberExpr(self.visit(value), n.attr)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Attribute\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"e = IndexExpr(self.visit(n.value), self.visit(n.slice))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Subscript\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"e = IndexExpr(self.visit(n.value), self.visit(n.slice))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Subscript\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"e = StarExpr(self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Starred\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"expr_list: list[Expression] = [self.visit(e) for e in n.elts]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_List\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 17,\n        \"src\": \"e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Slice\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Slice\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Slice\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 50,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"return TupleExpr(self.translate_expr_list(cast(Any, n).dims))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ExtSlice\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return TupleExpr(self.translate_expr_list(cast(Any, n).dims))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_ExtSlice\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"value = self.visit(cast(Any, n).value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Index\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 27,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 0,\n        \"src\": \"value = self.visit(cast(Any, n).value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Index\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"value = self.visit(cast(Any, n).value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Index\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(value, Node)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Index\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"self.visit(n.subject),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.visit(n.subject),\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[self.visit(c.pattern) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.visit(c.pattern) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.visit(c.pattern) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.visit(c.pattern) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[self.visit(c.guard) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.visit(c.guard) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.visit(c.guard) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.visit(c.guard) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[self.as_required_block(c.body) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.as_required_block(c.body) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[self.as_required_block(c.body) for c in n.cases],\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_Match\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"node = ValuePattern(self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = ValuePattern(self.visit(n.value))\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchValue\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"node = SingletonPattern(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSingleton\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"patterns = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"patterns = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"patterns = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"patterns = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"patterns = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"stars = [p for p in patterns if isinstance(p, StarredPattern)]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"stars = [p for p in patterns if isinstance(p, StarredPattern)]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"stars = [p for p in patterns if isinstance(p, StarredPattern)]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"node = SequencePattern(patterns)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchSequence\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if n.name is None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"name = self.set_line(NameExpr(n.name), n)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchStar\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"keys = [self.visit(k) for k in n.keys]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"keys = [self.visit(k) for k in n.keys]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keys = [self.visit(k) for k in n.keys]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keys = [self.visit(k) for k in n.keys]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keys = [self.visit(k) for k in n.keys]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"values = [self.visit(v) for v in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"values = [self.visit(v) for v in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"values = [self.visit(v) for v in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"values = [self.visit(v) for v in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"values = [self.visit(v) for v in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if n.rest is None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"rest = NameExpr(n.rest)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"node = MappingPattern(keys, values, rest)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"node = MappingPattern(keys, values, rest)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchMapping\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"class_ref = self.visit(n.cls)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"class_ref = self.visit(n.cls)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(class_ref, RefExpr)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"positionals = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"positionals = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"positionals = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"positionals = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"positionals = [self.visit(p) for p in n.patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"keyword_keys = n.kwd_attrs\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"keyword_values = [self.visit(p) for p in n.kwd_patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"keyword_values = [self.visit(p) for p in n.kwd_patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keyword_values = [self.visit(p) for p in n.kwd_patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keyword_values = [self.visit(p) for p in n.kwd_patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"keyword_values = [self.visit(p) for p in n.kwd_patterns]\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchClass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if n.name is None:\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchAs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"name = NameExpr(n.name)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchAs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"node = AsPattern(self.visit(n.pattern), name)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchAs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = AsPattern(self.visit(n.pattern), name)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchAs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"node = OrPattern([self.visit(pattern) for pattern in n.patterns])\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchOr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = OrPattern([self.visit(pattern) for pattern in n.patterns])\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchOr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = OrPattern([self.visit(pattern) for pattern in n.patterns])\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchOr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"node = OrPattern([self.visit(pattern) for pattern in n.patterns])\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_MatchOr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 72,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"incorrect_expr = find_disallowed_expression_in_annotation_scope(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 73,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"self.fail(message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION, n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 83,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.fail(message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION, n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 73,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.fail(message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION, n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 83,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.fail(message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION, n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 73,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.fail(message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION, n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 83,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.fail(message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION, n.lineno, n.col_offset)\",\n        \"target\": \"mypy.fastparse.ASTConverter.validate_type_alias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"type_params = self.translate_type_params(n.type_params)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"value = self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"value = self.visit(n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"ret = ReturnStmt(value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.set_line(ret, n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.set_line(value_func, n.value)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"node = TypeAliasStmt(self.visit_Name(n.name), type_params, value_func)\",\n        \"target\": \"mypy.fastparse.ASTConverter.visit_TypeAlias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | int\\\")\",\n        \"offset\": 40,\n        \"src\": \"None, \\\"typing.Any\\\", line=self.line, column=getattr(node, \\\"col_offset\\\", -1), note=note\",\n        \"target\": \"mypy.fastparse.TypeConverter.invalid_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 16,\n        \"src\": \"visitor = getattr(self, method, None)\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if visitor is not None:\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"typ = visitor(node)\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(typ, ProperType)\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 81,\n        \"src\": \"if isinstance(n, Constant) and isinstance(n.value, str):\",\n        \"target\": \"mypy.fastparse.TypeConverter._extract_argument_name\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(n, Constant) and n.value is None:\",\n        \"target\": \"mypy.fastparse.TypeConverter._extract_argument_name\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 69,\n        \"src\": \"val = n.value\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if val is None:\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(val, str):\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if val is Ellipsis:\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(val, bool):\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(val, (int, float, complex)):\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(val, bytes):\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Constant\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | int\\\")\",\n        \"offset\": 38,\n        \"src\": \"numeric_value, type_name, line=self.line, column=getattr(n, \\\"col_offset\\\", -1)\",\n        \"target\": \"mypy.fastparse.TypeConverter.numeric_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 27,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"value = self.visit(cast(Any, n).value)\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Index\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"value = self.visit(cast(Any, n).value)\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Index\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 74,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 44,\n        \"src\": \"if not isinstance(item_name, ast3.Constant) or not isinstance(item_name.value, str):\",\n        \"target\": \"mypy.fastparse.TypeConverter.visit_Dict\"\n      }\n    ],\n    \"mypy/fixup.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 15,\n        \"message\": \"Member \\\"defn\\\" has type \\\"ClassDef\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 70,\n        \"src\": \"if info.defn:\",\n        \"target\": \"mypy.fixup.NodeFixer.visit_type_info\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"func\\\" has type \\\"FuncDef\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 113,\n        \"src\": \"if d.func:\",\n        \"target\": \"mypy.fixup.NodeFixer.visit_decorator\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"var\\\" has type \\\"Var\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 2,\n        \"src\": \"if d.var:\",\n        \"target\": \"mypy.fixup.NodeFixer.visit_decorator\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 74,\n        \"src\": \"def visit_any(self, o: Any) -> None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_any\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"fallback\\\" has type \\\"Instance\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 4,\n        \"src\": \"if ct.fallback:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_callable_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always true\",\n        \"offset\": 4,\n        \"src\": \"if argt is not None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_callable_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 2,\n        \"src\": \"if ct.ret_type is not None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_callable_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 16,\n        \"src\": \"def visit_erased_type(self, o: Any) -> None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_erased_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"raise RuntimeError(\\\"Shouldn't get here\\\", o)\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_erased_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def visit_deleted_type(self, o: Any) -> None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_deleted_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def visit_none_type(self, o: Any) -> None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_none_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def visit_uninhabited_type(self, o: Any) -> None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_uninhabited_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def visit_partial_type(self, o: Any) -> None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_partial_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"raise RuntimeError(\\\"Shouldn't get here\\\", o)\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_partial_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 6,\n        \"src\": \"if tt.partial_fallback is not None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_tuple_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 7,\n        \"src\": \"if tdt.fallback is not None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_typeddict_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always true\",\n        \"offset\": 39,\n        \"src\": \"if argt is not None:\",\n        \"target\": \"mypy.fixup.TypeFixer.visit_parameters\"\n      }\n    ],\n    \"mypy/fscache.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 296,\n        \"src\": \"new = OSError(*e.args)\",\n        \"target\": \"mypy.fscache.copy_os_error\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"new.filename = e.filename\",\n        \"target\": \"mypy.fscache.copy_os_error\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if e.filename2:\",\n        \"target\": \"mypy.fscache.copy_os_error\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"new.filename2 = e.filename2\",\n        \"target\": \"mypy.fscache.copy_os_error\"\n      }\n    ],\n    \"mypy/inspections.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 43,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 57,\n        \"src\": \"return f\\\"{expr.line}:{expr.column + 1}:{expr.end_line}:{expr.end_column}\\\"\",\n        \"target\": \"mypy.inspections.expr_span\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 59,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 0,\n        \"src\": \"return f\\\"{expr.line}:{expr.column + 1}:{expr.end_line}:{expr.end_column}\\\"\",\n        \"target\": \"mypy.inspections.expr_span\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 17,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 305,\n        \"src\": \"return f\\\"{module.path}:{node.line}:{node.column + 1}:{node.name}\\\"\",\n        \"target\": \"mypy.inspections.InspectionEngine.format_node\"\n      }\n    ],\n    \"mypy/literals.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 132,\n        \"src\": \"Key: _TypeAlias = tuple[Any, ...]\",\n        \"target\": \"mypy.literals\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 16,\n        \"src\": \"if len(key) == 2 and key[0] == \\\"Var\\\" and isinstance(key[1], Var):\",\n        \"target\": \"mypy.literals.extract_var_from_literal_hash\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if len(key) == 2 and key[0] == \\\"Var\\\" and isinstance(key[1], Var):\",\n        \"target\": \"mypy.literals.extract_var_from_literal_hash\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[str | Any, ...]\\\")\",\n        \"offset\": 41,\n        \"src\": \"return (\\\"Comparison\\\",) + rest\",\n        \"target\": \"mypy.literals._Hasher.visit_comparison_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[str | Any, ...]\\\")\",\n        \"offset\": 8,\n        \"src\": \"return (name,) + rest\",\n        \"target\": \"mypy.literals._Hasher.seq_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[str | Any, ...]\\\")\",\n        \"offset\": 11,\n        \"src\": \"return (\\\"Dict\\\",) + rest\",\n        \"target\": \"mypy.literals._Hasher.visit_dict_expr\"\n      }\n    ],\n    \"mypy/main.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 12,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 249,\n        \"src\": \"\\\"Warning: unused section(s) in {}: {}\\\".format(\",\n        \"target\": \"mypy.main.run_build\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 110,\n        \"src\": \"python_executable = special_opts.python_executable or options.python_executable\",\n        \"target\": \"mypy.main.infer_python_executable\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"python_executable = special_opts.python_executable or options.python_executable\",\n        \"target\": \"mypy.main.infer_python_executable\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"if python_executable is None:\",\n        \"target\": \"mypy.main.infer_python_executable\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not special_opts.no_executable and not options.no_site_packages:\",\n        \"target\": \"mypy.main.infer_python_executable\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 48,\n        \"src\": \"def __init__(self, *args: Any, **kwargs: Any) -> None:\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.stdout = kwargs.pop(\\\"stdout\\\", sys.stdout)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.stdout = kwargs.pop(\\\"stdout\\\", sys.stdout)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.stderr = kwargs.pop(\\\"stderr\\\", sys.stderr)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.stderr = kwargs.pop(\\\"stderr\\\", sys.stderr)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"super().__init__(*args, **kwargs)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"super().__init__(*args, **kwargs)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"file = self.stdout\",\n        \"target\": \"mypy.main.CapturableArgumentParser.print_usage\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"SupportsWrite[str] | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"self._print_message(self.format_usage(), file)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.print_usage\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"file = self.stdout\",\n        \"target\": \"mypy.main.CapturableArgumentParser.print_help\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"SupportsWrite[str] | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"self._print_message(self.format_help(), file)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.print_help\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"file = self.stderr\",\n        \"target\": \"mypy.main.CapturableArgumentParser._print_message\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"SupportsWrite[str] | Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"file.write(message)\",\n        \"target\": \"mypy.main.CapturableArgumentParser._print_message\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"self._print_message(message, self.stderr)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.exit\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 12,\n        \"src\": \"self.print_usage(self.stderr)\",\n        \"target\": \"mypy.main.CapturableArgumentParser.error\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 31,\n        \"src\": \"def __call__(\",\n        \"target\": \"mypy.main.CapturableVersionAction.__call__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 270,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 69,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 171,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 295,\n        \"src\": \"\\\"--package-root\\\", metavar=\\\"ROOT\\\", action=\\\"append\\\", default=[], help=argparse.SUPPRESS\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 53,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 12,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 9,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 23,\n        \"src\": \"config_file = dummy.config_file\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if config_file and not os.path.exists(config_file):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if config_file and not os.path.exists(config_file):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if config_file and not os.path.exists(config_file):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"parser.error(f\\\"Cannot find config file '{config_file}'\\\")\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 46,\n        \"src\": \"parse_config_file(options, set_strict_flags, config_file, stdout, stderr)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if dummy.ide:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 15,\n        \"src\": \"options.python_version = special_opts.python_version or options.python_version\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | (int, int)\\\")\",\n        \"offset\": 1,\n        \"src\": \"if options.python_version < (3,):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if options.python_version < (3,):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"if special_opts.no_executable or options.no_site_packages:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if special_opts.no_executable or options.no_site_packages:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if not (special_opts.files or special_opts.packages or special_opts.modules):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not (special_opts.files or special_opts.packages or special_opts.modules):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 59,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not (special_opts.files or special_opts.packages or special_opts.modules):\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"code_methods = sum(\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"bool(c)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"for c in [\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"special_opts.modules + special_opts.packages,\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"special_opts.modules + special_opts.packages,\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"special_opts.command,\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"special_opts.files,\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 33,\n        \"src\": \"if special_opts.find_occurrences:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"_find_occurrences = tuple(special_opts.find_occurrences.split(\\\".\\\"))\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"_find_occurrences = tuple(special_opts.find_occurrences.split(\\\".\\\"))\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if len(_find_occurrences) < 2:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 2,\n        \"src\": \"if len(_find_occurrences) != 2:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 5,\n        \"src\": \"for flag, val in vars(special_opts).items():\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for flag, val in vars(special_opts).items():\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for flag, val in vars(special_opts).items():\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict_items[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for flag, val in vars(special_opts).items():\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if flag.endswith(\\\"_report\\\") and val is not None:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"report_dir = val\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"options.report_dirs[report_type] = report_dir\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"if special_opts.cache_map:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 35,\n        \"src\": \"[f\\\"module:{el}\\\" for el in special_opts.modules]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[f\\\"module:{el}\\\" for el in special_opts.modules]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[f\\\"module:{el}\\\" for el in special_opts.modules]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"+ [f\\\"package:{el}\\\" for el in special_opts.packages]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"+ [f\\\"package:{el}\\\" for el in special_opts.packages]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"+ [f\\\"package:{el}\\\" for el in special_opts.packages]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 10,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"+ [f\\\"file:{el}\\\" for el in special_opts.files]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"+ [f\\\"file:{el}\\\" for el in special_opts.files]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"+ [f\\\"file:{el}\\\" for el in special_opts.files]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if special_opts.modules + special_opts.packages:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if special_opts.modules + special_opts.packages:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"for p in special_opts.packages:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for p in special_opts.packages:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if os.sep in p or os.altsep and os.altsep in p:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if os.sep in p or os.altsep and os.altsep in p:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"fail(f\\\"Package name '{p}' cannot have a slash in it.\\\", stderr, options)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"p_targets = cache.find_modules_recursive(p)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"reason = cache.find_module(p)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"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        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"fail(f\\\"Can't find package '{p}'\\\", stderr, options)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"for m in special_opts.modules:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for m in special_opts.modules:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"targets.append(BuildSource(None, m, None))\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 9,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif special_opts.command:\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"targets = [BuildSource(None, None, \\\"\\\\n\\\".join(special_opts.command))]\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"targets = create_source_list(special_opts.files, options, fscache)\",\n        \"target\": \"mypy.main.process_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 48,\n        \"src\": \"n = len(special_opts.cache_map)\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"source, meta_file, data_file = special_opts.cache_map[i : i + 3]\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if source in options.cache_map:\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"parser.error(f\\\"Duplicate --cache-map source {source})\\\")\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not source.endswith(\\\".py\\\") and not source.endswith(\\\".pyi\\\"):\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not source.endswith(\\\".py\\\") and not source.endswith(\\\".pyi\\\"):\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"parser.error(f\\\"Invalid --cache-map source {source} (triple[0] must be *.py[i])\\\")\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not meta_file.endswith(\\\".meta.json\\\"):\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 85,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"\\\"Invalid --cache-map meta_file %s (triple[1] must be *.meta.json)\\\" % meta_file\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if not data_file.endswith(\\\".data.json\\\"):\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 85,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"\\\"Invalid --cache-map data_file %s (triple[2] must be *.data.json)\\\" % data_file\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"options.cache_map[source] = (meta_file, data_file)\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"options.cache_map[source] = (meta_file, data_file)\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"options.cache_map[source] = (meta_file, data_file)\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"options.cache_map[source] = (meta_file, data_file)\",\n        \"target\": \"mypy.main.process_cache_map\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 19,\n        \"src\": \"options.platform,\",\n        \"target\": \"mypy.main.maybe_write_junit_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 78,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"td, serious, messages_by_file, options.junit_xml, py_version, options.platform\",\n        \"target\": \"mypy.main.maybe_write_junit_xml\"\n      }\n    ],\n    \"mypy/meet.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 40,\n        \"message\": \"The type \\\"type[mypy.types.ProperType]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 623,\n        \"src\": \"assert type(left) != type(right), f\\\"{type(left)} vs {type(right)}\\\"\",\n        \"target\": \"mypy.meet.is_overlapping_types\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 56,\n        \"message\": \"The type \\\"type[mypy.types.ProperType]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 0,\n        \"src\": \"assert type(left) != type(right), f\\\"{type(left)} vs {type(right)}\\\"\",\n        \"target\": \"mypy.meet.is_overlapping_types\"\n      }\n    ],\n    \"mypy/memprofile.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 27,\n        \"src\": \"objs = gc.get_objects()\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"find_recursive_objects(objs)\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"for obj in objs:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for obj in objs:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if type(obj) is FakeInfo:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if type(obj) is FakeInfo:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"n = type(obj).__name__\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"n = type(obj).__name__\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if hasattr(obj, \\\"__dict__\\\"):\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"inferred[id(obj.__dict__)] = f\\\"{n} (__dict__)\\\"\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(obj, (Node, Type)):  # type: ignore[misc]\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": null,\n        \"column\": 22,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"if isinstance(obj, (Node, Type)):  # type: ignore[misc]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 19,\n        \"src\": \"for obj in objs:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for obj in objs:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if id(obj) in inferred:\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"name = inferred[id(obj)]\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"name = type(obj).__name__\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"name = type(obj).__name__\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 59,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"memuse[name] = memuse.get(name, 0) + sys.getsizeof(obj)\",\n        \"target\": \"mypy.memprofile.collect_memory_stats\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 56,\n        \"src\": \"for slot in getattr(base, \\\"__slots__\\\", ()):\",\n        \"target\": \"mypy.memprofile.find_recursive_objects\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | ()\\\")\",\n        \"offset\": 0,\n        \"src\": \"for slot in getattr(base, \\\"__slots__\\\", ()):\",\n        \"target\": \"mypy.memprofile.find_recursive_objects\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if hasattr(obj, slot):\",\n        \"target\": \"mypy.memprofile.find_recursive_objects\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"visit(getattr(obj, slot))\",\n        \"target\": \"mypy.memprofile.find_recursive_objects\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"visit(getattr(obj, slot))\",\n        \"target\": \"mypy.memprofile.find_recursive_objects\"\n      }\n    ],\n    \"mypy/messages.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 575,\n        \"src\": \"def unsupported_operand_types(\",\n        \"target\": \"mypy.messages.MessageBuilder.unsupported_operand_types\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"if isinstance(left_type, str):\",\n        \"target\": \"mypy.messages.MessageBuilder.unsupported_operand_types\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"left_str = format_type(left_type, self.options)\",\n        \"target\": \"mypy.messages.MessageBuilder.unsupported_operand_types\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(right_type, str):\",\n        \"target\": \"mypy.messages.MessageBuilder.unsupported_operand_types\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"right_str = format_type(right_type, self.options)\",\n        \"target\": \"mypy.messages.MessageBuilder.unsupported_operand_types\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 46,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 352,\n        \"src\": \"f'This is likely because \\\"{original_caller_type.name}\\\" has named arguments: '\",\n        \"target\": \"mypy.messages.MessageBuilder.maybe_note_concatenate_pos_args\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 18,\n        \"message\": \"Name \\\"msg\\\" may be undefined\",\n        \"offset\": 84,\n        \"src\": \"self.fail(msg, context)\",\n        \"target\": \"mypy.messages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 14,\n        \"src\": \"first_arg = callee.def_extras.get(\\\"first_arg\\\")\",\n        \"target\": \"mypy.messages.MessageBuilder.maybe_note_about_special_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"first_arg = callee.def_extras.get(\\\"first_arg\\\")\",\n        \"target\": \"mypy.messages.MessageBuilder.maybe_note_about_special_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if first_arg and first_arg not in {\\\"self\\\", \\\"cls\\\", \\\"mcs\\\"}:\",\n        \"target\": \"mypy.messages.MessageBuilder.maybe_note_about_special_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if first_arg and first_arg not in {\\\"self\\\", \\\"cls\\\", \\\"mcs\\\"}:\",\n        \"target\": \"mypy.messages.MessageBuilder.maybe_note_about_special_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if first_arg and first_arg not in {\\\"self\\\", \\\"cls\\\", \\\"mcs\\\"}:\",\n        \"target\": \"mypy.messages.MessageBuilder.maybe_note_about_special_args\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 12,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 51,\n        \"src\": \"'{} gets multiple values for keyword argument \\\"{}\\\"'.format(\",\n        \"target\": \"mypy.messages.MessageBuilder.duplicate_argument_value\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 202,\n        \"src\": \"elif isinstance(tp, Overloaded):\",\n        \"target\": \"mypy.messages.MessageBuilder.pretty_callable_or_overload\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 37,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 530,\n        \"src\": \"self.note(f\\\"    {k}: {v.accept(visitor) if v is not None else None}\\\", context)\",\n        \"target\": \"mypy.messages.MessageBuilder.reveal_locals\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always false\",\n        \"offset\": 384,\n        \"src\": \"if not isinstance(subtype.partial_fallback, Instance):\",\n        \"target\": \"mypy.messages.MessageBuilder.report_protocol_problems\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"return\",\n        \"target\": \"mypy.messages.MessageBuilder.report_protocol_problems\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always false\",\n        \"offset\": 3,\n        \"src\": \"if not isinstance(subtype.fallback, Instance):\",\n        \"target\": \"mypy.messages.MessageBuilder.report_protocol_problems\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"return\",\n        \"target\": \"mypy.messages.MessageBuilder.report_protocol_problems\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 189,\n        \"src\": \"def print_more(\",\n        \"target\": \"mypy.messages.MessageBuilder.print_more\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Sequence[Any]\\\")\",\n        \"offset\": 9,\n        \"src\": \"if len(conflicts) > max_items:\",\n        \"target\": \"mypy.messages.MessageBuilder.print_more\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Sequence[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"f\\\"<{len(conflicts) - max_items} more conflict(s) not shown>\\\",\",\n        \"target\": \"mypy.messages.MessageBuilder.print_more\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 37,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 164,\n        \"src\": \"arg_strings.append(f\\\"{arg_name}: {format(arg_type)}\\\")\",\n        \"target\": \"mypy.messages.format_callable_args\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 37,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 3,\n        \"src\": \"arg_strings.append(f\\\"{arg_name}: {format(arg_type)}\\\")\",\n        \"target\": \"mypy.messages.format_callable_args\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 37,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 6,\n        \"src\": \"arg_strings.append(f\\\"{arg_name}: {format(arg_type)}=...\\\")\",\n        \"target\": \"mypy.messages.format_callable_args\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 37,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 3,\n        \"src\": \"arg_strings.append(f\\\"{arg_name}: {format(arg_type)} = ...\\\")\",\n        \"target\": \"mypy.messages.format_callable_args\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 7,\n        \"src\": \"elif arg_kind is ARG_STAR2:\",\n        \"target\": \"mypy.messages.format_callable_args\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 9,\n        \"message\": \"Condition is always false\",\n        \"offset\": 293,\n        \"src\": \"elif typ is None:\",\n        \"target\": \"mypy.messages.format_type_inner\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 21,\n        \"message\": \"Name \\\"strs\\\" may be undefined\",\n        \"offset\": 135,\n        \"src\": \"return tuple(strs)\",\n        \"target\": \"mypy.messages\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 51,\n        \"message\": \"Name \\\"strs\\\" may be undefined\",\n        \"offset\": 2,\n        \"src\": \"return tuple(quote_type_string(s) for s in strs)\",\n        \"target\": \"mypy.messages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 74,\n        \"src\": \"first_arg = tp.def_extras.get(\\\"first_arg\\\")\",\n        \"target\": \"mypy.messages.pretty_callable\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"first_arg = tp.def_extras.get(\\\"first_arg\\\")\",\n        \"target\": \"mypy.messages.pretty_callable\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if first_arg:\",\n        \"target\": \"mypy.messages.pretty_callable\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"s = first_arg + s\",\n        \"target\": \"mypy.messages.pretty_callable\"\n      }\n    ],\n    \"mypy/metastore.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 168,\n        \"src\": \"def _query(self, name: str, field: str) -> Any:\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore._query\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"results = cur.fetchall()\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore._query\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if not results:\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore._query\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"assert len(results) == 1\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore._query\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return results[0][0]\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore._query\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return results[0][0]\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore._query\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"mtime = self._query(name, \\\"mtime\\\")\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore.getmtime\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(mtime, float)\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore.getmtime\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"data = self._query(name, \\\"data\\\")\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore.read\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(data, bytes)\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore.read\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 31,\n        \"src\": \"for row in self.db.execute(\\\"SELECT path FROM files2\\\"):\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore.list_all\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield row[0]\",\n        \"target\": \"mypy.metastore.SqliteMetadataStore.list_all\"\n      }\n    ],\n    \"mypy/modulefinder.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 103,\n        \"src\": \"elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\",\n        \"target\": \"mypy.modulefinder.ModuleNotFoundReason.error_message_templates\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 32,\n        \"message\": \"Name \\\"parent_id\\\" may be undefined\",\n        \"offset\": 496,\n        \"src\": \"if self.find_module(parent_id) is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\",\n        \"target\": \"mypy.modulefinder\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 184,\n        \"src\": \"sys_path, site_packages = ast.literal_eval(\",\n        \"target\": \"mypy.modulefinder.get_search_dirs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"print(err.stderr)\",\n        \"target\": \"mypy.modulefinder.get_search_dirs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"print(err.stdout)\",\n        \"target\": \"mypy.modulefinder.get_search_dirs\"\n      }\n    ],\n    \"mypy/moduleinspect.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 37,\n        \"src\": \"if module.__dict__.get(\\\"__file__\\\") is None:\",\n        \"target\": \"mypy.moduleinspect.is_c_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if module.__dict__.get(\\\"__file__\\\") is None:\",\n        \"target\": \"mypy.moduleinspect.is_c_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any)\\\")\",\n        \"offset\": 4,\n        \"src\": \"return os.path.splitext(module.__dict__[\\\"__file__\\\"])[-1] in [\\\".so\\\", \\\".pyd\\\", \\\".dll\\\"]\",\n        \"target\": \"mypy.moduleinspect.is_c_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return os.path.splitext(module.__dict__[\\\"__file__\\\"])[-1] in [\\\".so\\\", \\\".pyd\\\", \\\".dll\\\"]\",\n        \"target\": \"mypy.moduleinspect.is_c_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return os.path.splitext(module.__dict__[\\\"__file__\\\"])[-1] in [\\\".so\\\", \\\".pyd\\\", \\\".dll\\\"]\",\n        \"target\": \"mypy.moduleinspect.is_c_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return os.path.splitext(module.__dict__[\\\"__file__\\\"])[-1] in [\\\".so\\\", \\\".pyd\\\", \\\".dll\\\"]\",\n        \"target\": \"mypy.moduleinspect.is_c_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 17,\n        \"src\": \"name = getattr(package, \\\"__name__\\\", package_id)\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"file = getattr(package, \\\"__file__\\\", None)\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(path, list):\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"pkg_all = getattr(package, \\\"__all__\\\", None)\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if pkg_all is not None:\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"pkg_all = list(pkg_all)\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 11,\n        \"src\": \"subpackages = [\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"subpackages = [\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 2,\n        \"src\": \"for name, val in inspect.getmembers(package)\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if inspect.ismodule(val) and val.__name__ == package.__name__ + \\\".\\\" + name\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 11,\n        \"src\": \"name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages\",\n        \"target\": \"mypy.moduleinspect.get_package_properties\"\n      }\n    ],\n    \"mypy/mro.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 22,\n        \"message\": \"Name \\\"head\\\" may be undefined\",\n        \"offset\": 59,\n        \"src\": \"result.append(head)\",\n        \"target\": \"mypy.mro\"\n      }\n    ],\n    \"mypy/nodes.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 71,\n        \"src\": \"JsonDict: _TypeAlias = dict[str, Any]\",\n        \"target\": \"mypy.nodes\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 116,\n        \"src\": \"if ans is None:\",\n        \"target\": \"mypy.nodes.Node.__str__\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"return repr(self)\",\n        \"target\": \"mypy.nodes.Node.__str__\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-unreachable for more info\",\n        \"offset\": 0,\n        \"src\": \"return repr(self)\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 198,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.MypyFile.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 7,\n        \"src\": \"\\\"future_import_flags\\\": list(self.future_import_flags),\",\n        \"target\": \"mypy.nodes.MypyFile.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"future_import_flags\\\": list(self.future_import_flags),\",\n        \"target\": \"mypy.nodes.MypyFile.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"MypyFile\\\", data\",\n        \"target\": \"mypy.nodes.MypyFile.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 197,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.OverloadedFuncDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"items\\\": [i.serialize() for i in self.items],\",\n        \"target\": \"mypy.nodes.OverloadedFuncDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"items\\\": [i.serialize() for i in self.items],\",\n        \"target\": \"mypy.nodes.OverloadedFuncDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"OverloadedFuncDef\\\"\",\n        \"target\": \"mypy.nodes.OverloadedFuncDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"[cast(OverloadPart, SymbolNode.deserialize(d)) for d in data[\\\"items\\\"]]\",\n        \"target\": \"mypy.nodes.OverloadedFuncDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[cast(OverloadPart, SymbolNode.deserialize(d)) for d in data[\\\"items\\\"]]\",\n        \"target\": \"mypy.nodes.OverloadedFuncDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 227,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.FuncDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 5,\n        \"src\": \"\\\"arg_kinds\\\": [int(x.value) for x in self.arg_kinds],\",\n        \"target\": \"mypy.nodes.FuncDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"arg_kinds\\\": [int(x.value) for x in self.arg_kinds],\",\n        \"target\": \"mypy.nodes.FuncDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 15,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"FuncDef\\\"\",\n        \"target\": \"mypy.nodes.FuncDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 16,\n        \"src\": \"ret.arg_kinds = [ArgKind(x) for x in data[\\\"arg_kinds\\\"]]\",\n        \"target\": \"mypy.nodes.FuncDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ret.arg_kinds = [ArgKind(x) for x in data[\\\"arg_kinds\\\"]]\",\n        \"target\": \"mypy.nodes.FuncDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 70,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.Decorator.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"Decorator\\\"\",\n        \"target\": \"mypy.nodes.Decorator.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 152,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"Var\\\"\",\n        \"target\": \"mypy.nodes.Var.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 98,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.ClassDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 4,\n        \"src\": \"\\\"type_vars\\\": [v.serialize() for v in self.type_vars],\",\n        \"target\": \"mypy.nodes.ClassDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"type_vars\\\": [v.serialize() for v in self.type_vars],\",\n        \"target\": \"mypy.nodes.ClassDef.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"ClassDef\\\"\",\n        \"target\": \"mypy.nodes.ClassDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"[\",\n        \"target\": \"mypy.nodes.ClassDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 77,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v))\",\n        \"target\": \"mypy.nodes.ClassDef.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1413,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.TypeVarExpr.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 4,\n        \"src\": \"\\\"values\\\": [t.serialize() for t in self.values],\",\n        \"target\": \"mypy.nodes.TypeVarExpr.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"values\\\": [t.serialize() for t in self.values],\",\n        \"target\": \"mypy.nodes.TypeVarExpr.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeVarExpr\\\"\",\n        \"target\": \"mypy.nodes.TypeVarExpr.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"[mypy.types.deserialize_type(v) for v in data[\\\"values\\\"]],\",\n        \"target\": \"mypy.nodes.TypeVarExpr.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[mypy.types.deserialize_type(v) for v in data[\\\"values\\\"]],\",\n        \"target\": \"mypy.nodes.TypeVarExpr.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 16,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.ParamSpecExpr.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"ParamSpecExpr\\\"\",\n        \"target\": \"mypy.nodes.ParamSpecExpr.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 37,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.TypeVarTupleExpr.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 12,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeVarTupleExpr\\\"\",\n        \"target\": \"mypy.nodes.TypeVarTupleExpr.deserialize\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always false\",\n        \"offset\": 569,\n        \"src\": \"if isinstance(node, FuncBase):\",\n        \"target\": \"mypy.nodes.TypeInfo.get_method\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"return node\",\n        \"target\": \"mypy.nodes.TypeInfo.get_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 153,\n        \"src\": \"ti.abstract_attributes = [(attr[0], attr[1]) for attr in data[\\\"abstract_attributes\\\"]]\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"ti.abstract_attributes = [(attr[0], attr[1]) for attr in data[\\\"abstract_attributes\\\"]]\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ti.abstract_attributes = [(attr[0], attr[1]) for attr in data[\\\"abstract_attributes\\\"]]\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ti.abstract_attributes = [(attr[0], attr[1]) for attr in data[\\\"abstract_attributes\\\"]]\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"ti.bases = [mypy.types.Instance.deserialize(b) for b in data[\\\"bases\\\"]]\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ti.bases = [mypy.types.Instance.deserialize(b) for b in data[\\\"bases\\\"]]\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"for p in data[\\\"_promote\\\"]:\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"t = mypy.types.deserialize_type(p)\",\n        \"target\": \"mypy.nodes.TypeInfo.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 286,\n        \"src\": \"\\\"alias_tvars\\\": [v.serialize() for v in self.alias_tvars],\",\n        \"target\": \"mypy.nodes.TypeAlias.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"alias_tvars\\\": [v.serialize() for v in self.alias_tvars],\",\n        \"target\": \"mypy.nodes.TypeAlias.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeAlias\\\"\",\n        \"target\": \"mypy.nodes.TypeAlias.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"alias_tvars = [mypy.types.deserialize_type(v) for v in data[\\\"alias_tvars\\\"]]\",\n        \"target\": \"mypy.nodes.TypeAlias.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"alias_tvars = [mypy.types.deserialize_type(v) for v in data[\\\"alias_tvars\\\"]]\",\n        \"target\": \"mypy.nodes.TypeAlias.deserialize\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always true\",\n        \"offset\": 240,\n        \"src\": \"if prefix is not None:\",\n        \"target\": \"mypy.nodes.SymbolTableNode.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 17,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"SymbolTableNode\\\"\",\n        \"target\": \"mypy.nodes.SymbolTableNode.deserialize\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always true\",\n        \"offset\": 33,\n        \"src\": \"if isinstance(value, SymbolTableNode):\",\n        \"target\": \"mypy.nodes.SymbolTable.__str__\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 7,\n        \"src\": \"a.append(\\\"  <invalid item>\\\")\",\n        \"target\": \"mypy.nodes.SymbolTable.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 23,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"SymbolTable\\\"\",\n        \"target\": \"mypy.nodes.SymbolTable.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 39,\n        \"src\": \"return {\",\n        \"target\": \"mypy.nodes.DataclassTransformSpec.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 5,\n        \"src\": \"\\\"field_specifiers\\\": list(self.field_specifiers),\",\n        \"target\": \"mypy.nodes.DataclassTransformSpec.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"field_specifiers\\\": list(self.field_specifiers),\",\n        \"target\": \"mypy.nodes.DataclassTransformSpec.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 10,\n        \"src\": \"field_specifiers=tuple(data.get(\\\"field_specifiers\\\", [])),\",\n        \"target\": \"mypy.nodes.DataclassTransformSpec.deserialize\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 69,\n        \"src\": \"elif kind == ARG_STAR2:\",\n        \"target\": \"mypy.nodes.check_arg_kinds\"\n      }\n    ],\n    \"mypy/options.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 135,\n        \"src\": \"MACHDEP = sysconfig.get_config_var(\\\"MACHDEP\\\")\",\n        \"target\": \"mypy.options.Options.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if MACHDEP == \\\"emscripten\\\":\",\n        \"target\": \"mypy.options.Options.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.platform = MACHDEP\",\n        \"target\": \"mypy.options.Options.__init__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 281,\n        \"src\": \"self.transform_source: Callable[[Any], Any] | None = None\",\n        \"target\": \"mypy.options.Options.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Iterable[(Any, Any)]\\\")\",\n        \"offset\": 53,\n        \"src\": \"d = dict(getattr(self, \\\"__dict__\\\", ()))\",\n        \"target\": \"mypy.options.Options.snapshot\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"d[k] = getattr(self, k)\",\n        \"target\": \"mypy.options.Options.snapshot\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"d = {k: v for k, v in d.items() if not k.startswith(\\\"_\\\")}\",\n        \"target\": \"mypy.options.Options.snapshot\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"def process_error_codes(\",\n        \"target\": \"mypy.options.Options.process_error_codes\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 20,\n        \"src\": \"def process_incomplete_features(\",\n        \"target\": \"mypy.options.Options.process_incomplete_features\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 150,\n        \"src\": \"val = getattr(self, opt)\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"val = sorted([code.code for code in val])\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = sorted([code.code for code in val])\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = sorted([code.code for code in val])\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = sorted([code.code for code in val])\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = sorted([code.code for code in val])\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"result[opt] = val\",\n        \"target\": \"mypy.options.Options.select_options_affecting_cache\"\n      }\n    ],\n    \"mypy/parse.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any) -> Any | None\\\")\",\n        \"offset\": 23,\n        \"src\": \"if options.transform_source is not None:\",\n        \"target\": \"mypy.parse.parse\"\n      }\n    ],\n    \"mypy/partially_defined.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 15,\n        \"message\": \"Member \\\"else_body\\\" has type \\\"Block\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 603,\n        \"src\": \"if o.else_body:\",\n        \"target\": \"mypy.partially_defined.PossiblyUndefinedVariableVisitor.visit_while_stmt\"\n      }\n    ],\n    \"mypy/plugin.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 388,\n        \"src\": \"def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> Any:\",\n        \"target\": \"mypy.plugin.SemanticAnalyzerPluginInterface.add_symbol_table_node\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (self: SemanticAnalyzerPluginInterface, name: str, symbol: SymbolTableNode) -> Any\\\")\",\n        \"offset\": 0,\n        \"src\": \"def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> Any:\",\n        \"target\": \"mypy.plugin\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 158,\n        \"src\": \"def report_config_data(self, ctx: ReportConfigContext) -> Any:\",\n        \"target\": \"mypy.plugin.Plugin.report_config_data\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 289,\n        \"src\": \"def report_config_data(self, ctx: ReportConfigContext) -> Any:\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"config_data = [plugin.report_config_data(ctx) for plugin in self._plugins]\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"config_data = [plugin.report_config_data(ctx) for plugin in self._plugins]\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return config_data if any(x is not None for x in config_data) else None\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any] | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"return config_data if any(x is not None for x in config_data) else None\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return config_data if any(x is not None for x in config_data) else None\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return config_data if any(x is not None for x in config_data) else None\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return config_data if any(x is not None for x in config_data) else None\",\n        \"target\": \"mypy.plugin.ChainedPlugin.report_config_data\"\n      }\n    ],\n    \"mypy/plugins/attrs.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 19,\n        \"message\": \"\\\"init_type\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 136,\n        \"src\": \"if init_type and self.init_type and self.converter.ret_type:\",\n        \"target\": \"mypy.plugins.attrs.Attribute.argument\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 47,\n        \"src\": \"return {\",\n        \"target\": \"mypy.plugins.attrs.Attribute.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 116,\n        \"src\": \"ctx.cls.info.metadata[\\\"attrs_tag\\\"] = {}\",\n        \"target\": \"mypy.plugins.attrs.attr_tag_callback\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 75,\n        \"src\": \"ctx.cls.info.metadata[\\\"attrs\\\"] = {\",\n        \"target\": \"mypy.plugins.attrs.attr_class_maker_callback_impl\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"attributes\\\": [attr.serialize() for attr in attributes],\",\n        \"target\": \"mypy.plugins.attrs.attr_class_maker_callback_impl\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"attributes\\\": [attr.serialize() for attr in attributes],\",\n        \"target\": \"mypy.plugins.attrs.attr_class_maker_callback_impl\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 92,\n        \"src\": \"for data in super_info.metadata[\\\"attrs\\\"][\\\"attributes\\\"]:\",\n        \"target\": \"mypy.plugins.attrs._analyze_class\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if data[\\\"name\\\"] not in taken_attr_names:\",\n        \"target\": \"mypy.plugins.attrs._analyze_class\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"a = Attribute.deserialize(super_info, data, ctx.api)\",\n        \"target\": \"mypy.plugins.attrs._analyze_class\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 31,\n        \"src\": \"info.metadata[\\\"attrs\\\"] = {\\\"attributes\\\": [], \\\"frozen\\\": False}\",\n        \"target\": \"mypy.plugins.attrs._add_empty_metadata\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"info.metadata[\\\"attrs\\\"] = {\\\"attributes\\\": [], \\\"frozen\\\": False}\",\n        \"target\": \"mypy.plugins.attrs._add_empty_metadata\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"info.metadata[\\\"attrs\\\"] = {\\\"attributes\\\": [], \\\"frozen\\\": False}\",\n        \"target\": \"mypy.plugins.attrs._add_empty_metadata\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 205,\n        \"src\": \"and converter_expr.args[0]\",\n        \"target\": \"mypy.plugins.attrs._parse_converter\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 24,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 417,\n        \"src\": \"ctx.api.fail(f'\\\"{ctx.default_signature.name}\\\" has unexpected type annotation', ctx.context)\",\n        \"target\": \"mypy.plugins.attrs.evolve_function_sig_callback\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 15,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 21,\n        \"src\": \"name=f\\\"{ctx.default_signature.name} of {inst_type_str}\\\",\",\n        \"target\": \"mypy.plugins.attrs.evolve_function_sig_callback\"\n      }\n    ],\n    \"mypy/plugins/dataclasses.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 140,\n        \"src\": \"elif of == \\\"__post_init__\\\":\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassAttribute.to_argument\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 17,\n        \"message\": \"Name \\\"arg_kind\\\" may be undefined\",\n        \"offset\": 18,\n        \"src\": \"kind=arg_kind,\",\n        \"target\": \"mypy.plugins.dataclasses\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 20,\n        \"src\": \"return {\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassAttribute.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 219,\n        \"src\": \"info.metadata[\\\"dataclass\\\"] = {\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassTransformer.transform\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"attributes\\\": [attr.serialize() for attr in attributes],\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassTransformer.transform\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"attributes\\\": [attr.serialize() for attr in attributes],\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassTransformer.transform\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 161,\n        \"src\": \"for data in info.metadata[\\\"dataclass\\\"][\\\"attributes\\\"]:\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassTransformer.collect_attributes\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"name: str = data[\\\"name\\\"]\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassTransformer.collect_attributes\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"attr = DataclassAttribute.deserialize(info, data, self._api)\",\n        \"target\": \"mypy.plugins.dataclasses.DataclassTransformer.collect_attributes\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 390,\n        \"src\": \"info.metadata[\\\"dataclass_tag\\\"] = {}\",\n        \"target\": \"mypy.plugins.dataclasses.add_dataclass_tag\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 24,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 128,\n        \"src\": \"ctx.api.fail(f'\\\"{ctx.default_signature.name}\\\" has unexpected type annotation', ctx.context)\",\n        \"target\": \"mypy.plugins.dataclasses.replace_function_sig_callback\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 15,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 21,\n        \"src\": \"name=f\\\"{ctx.default_signature.name} of {inst_type_str}\\\",\",\n        \"target\": \"mypy.plugins.dataclasses.replace_function_sig_callback\"\n      }\n    ],\n    \"mypy/plugins/default.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 9,\n        \"message\": \"Condition is always false\",\n        \"offset\": 591,\n        \"src\": \"elif isinstance(ctx.type, LiteralType):\",\n        \"target\": \"mypy.plugins.default.tuple_mul_callback\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Intersection of \\\"TupleType & LiteralType\\\" cannot exist: would have incompatible method signatures\",\n        \"offset\": 0,\n        \"src\": \"elif isinstance(ctx.type, LiteralType):\",\n        \"target\": \"mypy.plugins.default.tuple_mul_callback\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"value = arg_type.value\",\n        \"target\": \"mypy.plugins.default.tuple_mul_callback\"\n      }\n    ],\n    \"mypy/plugins/enums.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always true\",\n        \"offset\": 216,\n        \"src\": \"if underlying_type is not None:\",\n        \"target\": \"mypy.plugins.enums.enum_value_callback\"\n      }\n    ],\n    \"mypy/plugins/functools.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always false\",\n        \"offset\": 111,\n        \"src\": \"if isinstance(node, FuncItem) and isinstance(node.type, CallableType):\",\n        \"target\": \"mypy.plugins.functools._analyze_class\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 50,\n        \"message\": \"Right operand of \\\"and\\\" is never evaluated\",\n        \"offset\": 0,\n        \"src\": \"if isinstance(node, FuncItem) and isinstance(node.type, CallableType):\",\n        \"target\": \"mypy.plugins.functools._analyze_class\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"comparison_methods[name] = _MethodInfo(node.is_static, node.type)\",\n        \"target\": \"mypy.plugins.functools._analyze_class\"\n      }\n    ],\n    \"mypy/reachability.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 150,\n        \"src\": \"result = consider_sys_platform(expr, options.platform)\",\n        \"target\": \"mypy.reachability.infer_condition_value\"\n      }\n    ],\n    \"mypy/report.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 474,\n        \"src\": \"self.schema = etree.XMLSchema(etree.parse(xsd_path))\",\n        \"target\": \"mypy.report.MemoryXmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.schema = etree.XMLSchema(etree.parse(xsd_path))\",\n        \"target\": \"mypy.report.MemoryXmlReporter.__init__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"self.last_xml: Any | None = None\",\n        \"target\": \"mypy.report.MemoryXmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 34,\n        \"src\": \"root = etree.Element(\\\"mypy-report-file\\\", name=path, module=tree._fullname)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"doc = etree.ElementTree(root)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"doc = etree.ElementTree(root)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 6,\n        \"src\": \"etree.SubElement(\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"root,\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 9,\n        \"src\": \"transform_pi = etree.ProcessingInstruction(\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"root.addprevious(transform_pi)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"root.addprevious(transform_pi)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.schema.assertValid(doc)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.schema.assertValid(doc)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.last_xml = doc\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 21,\n        \"src\": \"root = etree.Element(\\\"mypy-report-index\\\", name=\\\"index\\\")\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"doc = etree.ElementTree(root)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"doc = etree.ElementTree(root)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"etree.SubElement(\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"root,\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 8,\n        \"src\": \"transform_pi = etree.ProcessingInstruction(\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"root.addprevious(transform_pi)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"root.addprevious(transform_pi)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.schema.assertValid(doc)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.schema.assertValid(doc)\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.last_xml = doc\",\n        \"target\": \"mypy.report.MemoryXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 18,\n        \"src\": \"self.classes: dict[str, Any] = {}\",\n        \"target\": \"mypy.report.CoberturaPackage.__init__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"def as_xml(self) -> Any:\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"package_element = etree.Element(\\\"package\\\", complexity=\\\"1.0\\\", name=self.name)\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"package_element.attrib[\\\"branch-rate\\\"] = \\\"0\\\"\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"package_element.attrib[\\\"line-rate\\\"] = get_line_rate(self.covered_lines, self.total_lines)\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"classes_element = etree.SubElement(package_element, \\\"classes\\\")\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"classes_element = etree.SubElement(package_element, \\\"classes\\\")\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"for class_name in sorted(self.classes):\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"classes_element.append(self.classes[class_name])\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"classes_element.append(self.classes[class_name])\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"classes_element.append(self.classes[class_name])\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.add_packages(package_element)\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"return package_element\",\n        \"target\": \"mypy.report.CoberturaPackage.as_xml\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def add_packages(self, parent_element: Any) -> None:\",\n        \"target\": \"mypy.report.CoberturaPackage.add_packages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 2,\n        \"src\": \"packages_element = etree.SubElement(parent_element, \\\"packages\\\")\",\n        \"target\": \"mypy.report.CoberturaPackage.add_packages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"packages_element = etree.SubElement(parent_element, \\\"packages\\\")\",\n        \"target\": \"mypy.report.CoberturaPackage.add_packages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"attrgetter[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"for package in sorted(self.packages.values(), key=attrgetter(\\\"name\\\")):\",\n        \"target\": \"mypy.report.CoberturaPackage.add_packages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"packages_element.append(package.as_xml())\",\n        \"target\": \"mypy.report.CoberturaPackage.add_packages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"packages_element.append(package.as_xml())\",\n        \"target\": \"mypy.report.CoberturaPackage.add_packages\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 9,\n        \"src\": \"self.root = etree.Element(\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"self.doc = etree.ElementTree(self.root)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.doc = etree.ElementTree(self.root)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 22,\n        \"src\": \"class_element = etree.Element(\\\"class\\\", complexity=\\\"1.0\\\", filename=path, name=class_name)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"etree.SubElement(class_element, \\\"methods\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"etree.SubElement(class_element, \\\"methods\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"lines_element = etree.SubElement(class_element, \\\"lines\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"lines_element = etree.SubElement(class_element, \\\"lines\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 17,\n        \"src\": \"line_element = etree.SubElement(\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"lines_element,\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 8,\n        \"src\": \"line_element.attrib[\\\"condition-coverage\\\"] = \\\"50% (1/2)\\\"\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"class_element.attrib[\\\"branch-rate\\\"] = \\\"0\\\"\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"class_element.attrib[\\\"line-rate\\\"] = get_line_rate(class_lines_covered, class_total_lines)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 15,\n        \"src\": \"current_package.classes[class_name] = class_element\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"current_package.classes[class_name] = class_element\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"self.root.attrib[\\\"line-rate\\\"] = get_line_rate(\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"self.root.attrib[\\\"branch-rate\\\"] = \\\"0\\\"\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.root.attrib[\\\"lines-covered\\\"] = str(self.root_package.covered_lines)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.root.attrib[\\\"lines-valid\\\"] = str(self.root_package.total_lines)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"sources = etree.SubElement(self.root, \\\"sources\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"sources = etree.SubElement(self.root, \\\"sources\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"source_element = etree.SubElement(sources, \\\"source\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"source_element = etree.SubElement(sources, \\\"source\\\")\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"source_element.text = os.getcwd()\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.root_package.add_packages(self.root)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.doc.write(out_path, encoding=\\\"utf-8\\\", pretty_print=True)\",\n        \"target\": \"mypy.report.CoberturaXmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 36,\n        \"src\": \"last_xml = self.memory_xml.last_xml\",\n        \"target\": \"mypy.report.XmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if last_xml is None:\",\n        \"target\": \"mypy.report.XmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"last_xml.write(out_path, encoding=\\\"utf-8\\\")\",\n        \"target\": \"mypy.report.XmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 3,\n        \"src\": \"last_xml = self.memory_xml.last_xml\",\n        \"target\": \"mypy.report.XmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"assert last_xml is not None\",\n        \"target\": \"mypy.report.XmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"last_xml.write(out_path, encoding=\\\"utf-8\\\")\",\n        \"target\": \"mypy.report.XmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 19,\n        \"src\": \"self.xslt_html = etree.XSLT(etree.parse(self.memory_xml.xslt_html_path))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.xslt_html = etree.XSLT(etree.parse(self.memory_xml.xslt_html_path))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.param_html = etree.XSLT.strparam(\\\"html\\\")\",\n        \"target\": \"mypy.report.XsltHtmlReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 9,\n        \"src\": \"last_xml = self.memory_xml.last_xml\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if last_xml is None:\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 7,\n        \"src\": \"transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 5,\n        \"src\": \"last_xml = self.memory_xml.last_xml\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"assert last_xml is not None\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 3,\n        \"src\": \"transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\",\n        \"target\": \"mypy.report.XsltHtmlReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 19,\n        \"src\": \"self.xslt_txt = etree.XSLT(etree.parse(self.memory_xml.xslt_txt_path))\",\n        \"target\": \"mypy.report.XsltTxtReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.xslt_txt = etree.XSLT(etree.parse(self.memory_xml.xslt_txt_path))\",\n        \"target\": \"mypy.report.XsltTxtReporter.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 12,\n        \"src\": \"last_xml = self.memory_xml.last_xml\",\n        \"target\": \"mypy.report.XsltTxtReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"assert last_xml is not None\",\n        \"target\": \"mypy.report.XsltTxtReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 2,\n        \"src\": \"transformed_txt = bytes(self.xslt_txt(last_xml))\",\n        \"target\": \"mypy.report.XsltTxtReporter.on_finish\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"transformed_txt = bytes(self.xslt_txt(last_xml))\",\n        \"target\": \"mypy.report.XsltTxtReporter.on_finish\"\n      }\n    ],\n    \"mypy/scope.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 19,\n        \"message\": \"Member \\\"function\\\" has type \\\"FuncBase\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 82,\n        \"src\": \"assert self.function\",\n        \"target\": \"mypy.scope.Scope.function_scope\"\n      }\n    ],\n    \"mypy/semanal.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 60,\n        \"message\": \"Name \\\"old_return_stmt_flag\\\" may be undefined\",\n        \"offset\": 550,\n        \"src\": \"self.return_stmt_inside_except_star_block = old_return_stmt_flag\",\n        \"target\": \"mypy.semanal\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 21,\n        \"message\": \"Condition is always true\",\n        \"offset\": 426,\n        \"src\": \"elif self.options.infer_function_types:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.analyze_func_def\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 41,\n        \"message\": \"Name \\\"original_target\\\" may be undefined\",\n        \"offset\": 73,\n        \"src\": \"if defn.info and original_target == defn.arguments[0].variable.name:\",\n        \"target\": \"mypy.semanal\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always true\",\n        \"offset\": 20,\n        \"src\": \"if isinstance(defn, FuncDef):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.analyze_func_def\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 39,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 62,\n        \"src\": \"overlapped = \\\", \\\".join([f'\\\"{name}\\\"' for name in overlap])\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.remove_unpack_kwargs\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 349,\n        \"src\": \"elif isinstance(item, FuncDef):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.analyze_overload_sigs_and_impl\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 89,\n        \"src\": \"elif isinstance(item, FuncDef):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_static_or_class_method_in_overload\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 10,\n        \"src\": \"elif isinstance(defn.impl, FuncDef):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_static_or_class_method_in_overload\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 35,\n        \"message\": \"Name \\\"type_params_names\\\" may be undefined\",\n        \"offset\": 501,\n        \"src\": \"self.locals.append(type_params_names)\",\n        \"target\": \"mypy.semanal\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 59,\n        \"message\": \"The type \\\"type[mypy.types.ProperType]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 39,\n        \"src\": \"assert False, f\\\"Unexpected special alias type: {type(target)}\\\"\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.setup_alias_type_vars\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always false\",\n        \"offset\": 1110,\n        \"src\": \"if node is None:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_import_all\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"continue\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_import_all\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"rvalue\\\" has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 439,\n        \"src\": \"if s.rvalue:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.analyze_lvalues\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 286,\n        \"src\": \"elif isinstance(value, float):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.analyze_simple_literal_type\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 38,\n        \"message\": \"Name \\\"type_name\\\" may be undefined\",\n        \"offset\": 3,\n        \"src\": \"typ = self.named_type_or_none(type_name)\",\n        \"target\": \"mypy.semanal\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 71,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 963,\n        \"src\": \"f'{message_registry.TYPEVAR_UNEXPECTED_ARGUMENT}: \\\"{param_name}\\\"', context\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_typevar_parameters\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 15,\n        \"message\": \"\\\"call\\\" has type \\\"CallExpr\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 75,\n        \"src\": \"if not call:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.extract_typevarlike_name\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 57,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 112,\n        \"src\": \"self.fail(f'Unexpected keyword argument \\\"{param_name}\\\" for \\\"TypeVarTuple\\\"', s)\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_typevartuple_declaration\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[tuple[Any, ...]]\\\")\",\n        \"offset\": 165,\n        \"src\": \"elementwise_assignments = zip(rval.items, *[v.items for v in seq_lvals])\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"for rv, *lvs in elementwise_assignments:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for rv, *lvs in elementwise_assignments:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for rv, *lvs in elementwise_assignments:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[tuple[Any, ...]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for rv, *lvs in elementwise_assignments:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.process_module_assignment(lvs, rv, ctx)\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.process_module_assignment(lvs, rv, ctx)\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.process_module_assignment\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"expr\\\" has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 164,\n        \"src\": \"if s.expr:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_assert_stmt\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"expr\\\" has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 403,\n        \"src\": \"if e.expr:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_yield_from_expr\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 16,\n        \"message\": \"Condition is always false\",\n        \"offset\": 45,\n        \"src\": \"reveal_type_node\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_call_expr\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 20,\n        \"message\": \"Right operand of \\\"and\\\" is never evaluated\",\n        \"offset\": 2,\n        \"src\": \"and reveal_type_node.fullname in IMPORTED_REVEAL_TYPE_NAMES\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_call_expr\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 2,\n        \"src\": \"reveal_imported = True\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_call_expr\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always true\",\n        \"offset\": 30,\n        \"src\": \"if self.locals is not None:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_call_expr\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 27,\n        \"message\": \"\\\"n\\\" has type \\\"SymbolTableNode\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 154,\n        \"src\": \"if not n:\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.visit_member_expr\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 23,\n        \"message\": \"Name \\\"implicit_node\\\" may be undefined\",\n        \"offset\": 407,\n        \"src\": \"return implicit_node\",\n        \"target\": \"mypy.semanal\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 15,\n        \"message\": \"\\\"sym\\\" has type \\\"SymbolTableNode\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 273,\n        \"src\": \"assert sym, \\\"Internal error: attempted to construct unknown type\\\"\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer.named_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 207,\n        \"src\": \"f = cast(Callable[[object], Any], lambda x: x)\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(object) -> Any\\\")\",\n        \"offset\": 0,\n        \"src\": \"f = cast(Callable[[object], Any], lambda x: x)\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(f(symbol_node), (Decorator, FuncBase, Var)):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 7,\n        \"src\": \"existing is not None\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"and isinstance(f(existing.node), (Decorator, FuncBase, Var))\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"True | Any\\\")\",\n        \"offset\": 2,\n        \"src\": \"isinstance(f(existing.type), f(AnyType))\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"isinstance(f(existing.type), f(AnyType))\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"isinstance(f(existing.type), f(AnyType))\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"or f(existing.type) == f(symbol_node).type\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"or f(existing.type) == f(symbol_node).type\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"if isinstance(f(symbol_node), (FuncBase, Decorator)):\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"typ = f(symbol_node).type\",\n        \"target\": \"mypy.semanal.SemanticAnalyzer._get_node_for_class_scoped_import\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 19,\n        \"message\": \"Name \\\"names\\\" may be undefined\",\n        \"offset\": 288,\n        \"src\": \"assert names is not None\",\n        \"target\": \"mypy.semanal\"\n      }\n    ],\n    \"mypy/semanal_enum.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 71,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 174,\n        \"src\": \"self.fail_enum_call_arg(f'Unexpected keyword argument \\\"{arg_name}\\\"', call)\",\n        \"target\": \"mypy.semanal_enum.EnumCallAnalyzer.parse_enum_call_args\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always false\",\n        \"offset\": 25,\n        \"src\": \"if is_StrExpr_list(seq_items):\",\n        \"target\": \"mypy.semanal_enum.EnumCallAnalyzer.parse_enum_call_args\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 31,\n        \"message\": \"Intersection of \\\"list[Expression] & list[StrExpr]\\\" cannot exist: would have inconsistent method resolution order\",\n        \"offset\": 0,\n        \"src\": \"if is_StrExpr_list(seq_items):\",\n        \"target\": \"mypy.semanal_enum.EnumCallAnalyzer.parse_enum_call_args\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"it = cast(list[StrExpr], seq_items)\",\n        \"target\": \"mypy.semanal_enum.EnumCallAnalyzer.parse_enum_call_args\"\n      }\n    ],\n    \"mypy/semanal_main.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 4,\n        \"message\": \"Name \\\"state\\\" may be undefined\",\n        \"offset\": 191,\n        \"src\": \"state.manager.incomplete_namespaces.update(scc)\",\n        \"target\": \"mypy.semanal_main\"\n      }\n    ],\n    \"mypy/semanal_namedtuple.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 19,\n        \"message\": \"Condition is always true\",\n        \"offset\": 415,\n        \"src\": \"if not is_StrExpr_list(listexpr.items):\",\n        \"target\": \"mypy.semanal_namedtuple.NamedTupleAnalyzer.parse_namedtuple_args\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 39,\n        \"message\": \"Intersection of \\\"list[Expression] & list[StrExpr]\\\" cannot exist: would have inconsistent method resolution order\",\n        \"offset\": 0,\n        \"src\": \"if not is_StrExpr_list(listexpr.items):\",\n        \"target\": \"mypy.semanal_namedtuple.NamedTupleAnalyzer.parse_namedtuple_args\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 3,\n        \"src\": \"it = cast(list[StrExpr], listexpr.items)\",\n        \"target\": \"mypy.semanal_namedtuple.NamedTupleAnalyzer.parse_namedtuple_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 119,\n        \"src\": \"info.metadata[\\\"namedtuple\\\"] = {\\\"fields\\\": items.copy()}\",\n        \"target\": \"mypy.semanal_namedtuple.NamedTupleAnalyzer.build_namedtuple_typeinfo\"\n      }\n    ],\n    \"mypy/semanal_pass1.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 59,\n        \"src\": \"self.platform = options.platform\",\n        \"target\": \"mypy.semanal_pass1.SemanticAnalyzerPreAnalysis.visit_file\"\n      }\n    ],\n    \"mypy/semanal_typeargs.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 57,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 92,\n        \"src\": \"assert t.alias is not None, f\\\"Unfixed type alias {t.type_ref}\\\"\",\n        \"target\": \"mypy.semanal_typeargs.TypeArgumentAnalyzer.visit_type_alias_type\"\n      }\n    ],\n    \"mypy/semanal_typeddict.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 47,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 514,\n        \"src\": \"f'Unexpected keyword argument \\\"{call.arg_names[2]}\\\" for \\\"TypedDict\\\"', call\",\n        \"target\": \"mypy.semanal_typeddict.TypedDictAnalyzer.parse_typeddict_args\"\n      }\n    ],\n    \"mypy/server/astdiff.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 7,\n        \"message\": \"Condition is always false\",\n        \"offset\": 238,\n        \"src\": \"if isinstance(node, FuncBase):\",\n        \"target\": \"mypy.server.astdiff.snapshot_definition\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 2,\n        \"src\": \"if node.type:\",\n        \"target\": \"mypy.server.astdiff.snapshot_definition\"\n      }\n    ],\n    \"mypy/server/astmerge.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 305,\n        \"src\": \"if isinstance(node.analyzed, SymbolNode):\",\n        \"target\": \"mypy.server.astmerge.NodeReplaceVisitor.visit_call_expr\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"node.analyzed = self.fixup(node.analyzed)\",\n        \"target\": \"mypy.server.astmerge.NodeReplaceVisitor.visit_call_expr\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 143,\n        \"src\": \"if typ.fallback is not None:\",\n        \"target\": \"mypy.server.astmerge.TypeReplaceVisitor.visit_callable_type\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 12,\n        \"src\": \"if t.fallback is not None:\",\n        \"target\": \"mypy.server.astmerge.TypeReplaceVisitor.visit_overloaded\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 17,\n        \"src\": \"if typ.partial_fallback is not None:\",\n        \"target\": \"mypy.server.astmerge.TypeReplaceVisitor.visit_tuple_type\"\n      }\n    ],\n    \"mypy/server/deps.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 23,\n        \"message\": \"Condition is always false\",\n        \"offset\": 505,\n        \"src\": \"if init and isinstance(init.node, FuncBase):\",\n        \"target\": \"mypy.server.deps.DependencyVisitor.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 24,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"fname = init.node.fullname\",\n        \"target\": \"mypy.server.deps.DependencyVisitor.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"upper_bound\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 534,\n        \"src\": \"if typ.upper_bound:\",\n        \"target\": \"mypy.server.deps.TypeTriggersVisitor.visit_type_var\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"default\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 2,\n        \"src\": \"if typ.default:\",\n        \"target\": \"mypy.server.deps.TypeTriggersVisitor.visit_type_var\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"upper_bound\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 10,\n        \"src\": \"if typ.upper_bound:\",\n        \"target\": \"mypy.server.deps.TypeTriggersVisitor.visit_param_spec\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"default\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 2,\n        \"src\": \"if typ.default:\",\n        \"target\": \"mypy.server.deps.TypeTriggersVisitor.visit_param_spec\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"upper_bound\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 9,\n        \"src\": \"if typ.upper_bound:\",\n        \"target\": \"mypy.server.deps.TypeTriggersVisitor.visit_type_var_tuple\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"default\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 2,\n        \"src\": \"if typ.default:\",\n        \"target\": \"mypy.server.deps.TypeTriggersVisitor.visit_type_var_tuple\"\n      }\n    ],\n    \"mypy/server/mergecheck.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 31,\n        \"src\": \"if fn is None:\",\n        \"target\": \"mypy.server.mergecheck.check_consistency\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"continue\",\n        \"target\": \"mypy.server.mergecheck.check_consistency\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 29,\n        \"message\": \"The string for \\\"object\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 44,\n        \"src\": \"result += f\\\".{attr}({t}:{obj.name})\\\"\",\n        \"target\": \"mypy.server.mergecheck.path_to_str\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 29,\n        \"message\": \"The string for \\\"object\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 4,\n        \"src\": \"result += f\\\".{attr}\\\"\",\n        \"target\": \"mypy.server.mergecheck.path_to_str\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 29,\n        \"message\": \"The string for \\\"object\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 2,\n        \"src\": \"result += f\\\".{attr}({t})\\\"\",\n        \"target\": \"mypy.server.mergecheck.path_to_str\"\n      }\n    ],\n    \"mypy/server/objgraph.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 43,\n        \"src\": \"if \\\"__getattribute__\\\" in getattr(type(o), \\\"__dict__\\\"):\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"e = getattr(o, attr)\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if type(e) not in ATOMIC_TYPE_BLACKLIST:\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if type(e) not in ATOMIC_TYPE_BLACKLIST:\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"yield attr, e\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"yield attr, e\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(int, Any)\\\")\",\n        \"offset\": 6,\n        \"src\": \"for i, e in enumerate(o):\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for i, e in enumerate(o):\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"enumerate[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, e in enumerate(o):\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(int, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"yield i, e\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"yield i, e\",\n        \"target\": \"mypy.server.objgraph.get_edge_candidates\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"((object, str), tuple[CellType, ...] | None | Any (unannotated))\\\")\",\n        \"offset\": 10,\n        \"src\": \"yield (s, \\\"__closure__\\\"), e.__closure__\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[CellType, ...] | None | Any (unannotated)\\\")\",\n        \"offset\": 0,\n        \"src\": \"yield (s, \\\"__closure__\\\"), e.__closure__\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"object | Any (unannotated)\\\")\",\n        \"offset\": 2,\n        \"src\": \"se = e.__self__\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"object | Any (unannotated)\\\")\",\n        \"offset\": 1,\n        \"src\": \"if se is not o and se is not type(o) and hasattr(s, \\\"__self__\\\"):\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"object | Any (unannotated)\\\")\",\n        \"offset\": 0,\n        \"src\": \"if se is not o and se is not type(o) and hasattr(s, \\\"__self__\\\"):\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any (unannotated)\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield s.__self__, se\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any (unannotated), object | Any (unannotated))\\\")\",\n        \"offset\": 0,\n        \"src\": \"yield s.__self__, se\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"object | Any (unannotated)\\\")\",\n        \"offset\": 0,\n        \"src\": \"yield s.__self__, se\",\n        \"target\": \"mypy.server.objgraph.get_edges\"\n      }\n    ],\n    \"mypy/server/update.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 252,\n        \"src\": \"\\\"previous targets with errors: %s\\\" % sorted(self.previous_targets_with_errors)\",\n        \"target\": \"mypy.server.update.FineGrainedBuildManager.update\"\n      }\n    ],\n    \"mypy/solve.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 23,\n        \"message\": \"Name \\\"solvable_tv\\\" may be undefined\",\n        \"offset\": 216,\n        \"src\": \"s_batch.remove(solvable_tv)\",\n        \"target\": \"mypy.solve\"\n      },\n      {\n        \"code\": \"truthy-iterable\",\n        \"column\": 26,\n        \"message\": \"\\\"lowers\\\" has type \\\"Iterable[Type]\\\" which can always be true in boolean context. Consider using \\\"Collection[Type]\\\" instead.\",\n        \"offset\": 49,\n        \"src\": \"if not uppers and not lowers:\",\n        \"target\": \"mypy.solve.solve_one\"\n      },\n      {\n        \"code\": \"truthy-iterable\",\n        \"column\": 26,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-truthy-iterable for more info\",\n        \"offset\": 0,\n        \"src\": \"if not uppers and not lowers:\",\n        \"target\": null\n      }\n    ],\n    \"mypy/split_namespace.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 22,\n        \"src\": \"def _get(self) -> tuple[Any, Any]:\",\n        \"target\": \"mypy.split_namespace.SplitNamespace._get\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-explicit-any for more info\",\n        \"offset\": 0,\n        \"src\": \"def _get(self) -> tuple[Any, Any]:\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"return (self._standard_namespace, self._alt_namespace)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace._get\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return (self._standard_namespace, self._alt_namespace)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace._get\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-any for more info\",\n        \"offset\": 0,\n        \"src\": \"return (self._standard_namespace, self._alt_namespace)\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return (self._standard_namespace, self._alt_namespace)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace._get\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def __setattr__(self, name: str, value: Any) -> None:\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if name.startswith(self._alt_prefix):\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"setattr(self._alt_namespace, name[len(self._alt_prefix) :], value)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"setattr(self._alt_namespace, name[len(self._alt_prefix) :], value)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 72,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"setattr(self._alt_namespace, name[len(self._alt_prefix) :], value)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"setattr(self._standard_namespace, name, value)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"setattr(self._standard_namespace, name, value)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__setattr__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def __getattr__(self, name: str) -> Any:\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__getattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if name.startswith(self._alt_prefix):\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__getattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return getattr(self._alt_namespace, name[len(self._alt_prefix) :])\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__getattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return getattr(self._alt_namespace, name[len(self._alt_prefix) :])\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__getattr__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"return getattr(self._standard_namespace, name)\",\n        \"target\": \"mypy.split_namespace.SplitNamespace.__getattr__\"\n      }\n    ],\n    \"mypy/stats.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"expr\\\" has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 249,\n        \"src\": \"if o.expr:\",\n        \"target\": \"mypy.stats.StatisticsVisitor.visit_yield_from_expr\"\n      }\n    ],\n    \"mypy/strconv.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 22,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 53,\n        \"src\": \"return f\\\"<{self.get_id(o)}>\\\"\",\n        \"target\": \"mypy.strconv.StrConv.format_id\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 22,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 14,\n        \"src\": \"tag += f\\\"<{self.get_id(obj)}>\\\"\",\n        \"target\": \"mypy.strconv.StrConv.dump\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 22,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"a.append(self.type_param(p))\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a.append(self.type_param(p))\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Args\\\", args))\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(o.type)\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(\\\"Generator\\\")\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.extend(extra)\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append(o.body)\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return a\",\n        \"target\": \"mypy.strconv.StrConv.func_helper\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"a: list[Any] = [o.defs]\",\n        \"target\": \"mypy.strconv.StrConv.visit_mypy_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.insert(0, \\\"BOM\\\")\",\n        \"target\": \"mypy.strconv.StrConv.visit_mypy_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"a.insert(0, o.path.replace(os.getcwd() + os.sep, \\\"\\\").replace(os.sep, \\\"/\\\"))\",\n        \"target\": \"mypy.strconv.StrConv.visit_mypy_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(\\\"IgnoredLines(%s)\\\" % \\\", \\\".join(str(line) for line in sorted(o.ignored_lines)))\",\n        \"target\": \"mypy.strconv.StrConv.visit_mypy_file\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_mypy_file\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 42,\n        \"src\": \"a: Any = o.items.copy()\",\n        \"target\": \"mypy.strconv.StrConv.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"a.insert(0, o.type)\",\n        \"target\": \"mypy.strconv.StrConv.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"a.insert(0, o.impl)\",\n        \"target\": \"mypy.strconv.StrConv.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"a.insert(-1, \\\"Static\\\")\",\n        \"target\": \"mypy.strconv.StrConv.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"a.insert(-1, \\\"Class\\\")\",\n        \"target\": \"mypy.strconv.StrConv.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 26,\n        \"src\": \"a.insert(1, self.type_param(p))\",\n        \"target\": \"mypy.strconv.StrConv.visit_class_def\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 29,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"a.append(o.rvalue)\",\n        \"target\": \"mypy.strconv.StrConv.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(o.type)\",\n        \"target\": \"mypy.strconv.StrConv.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"a: list[Any] = [o.expr, o.body]\",\n        \"target\": \"mypy.strconv.StrConv.visit_while_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Else\\\", o.else_body.body))\",\n        \"target\": \"mypy.strconv.StrConv.visit_while_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_while_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Async\\\", \\\"\\\"))\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append(o.index)\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(o.index_type)\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.extend([o.expr, o.body])\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a.extend([o.expr, o.body])\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Else\\\", o.else_body.body))\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_for_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_if_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"If\\\", [o.expr[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_if_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append((\\\"Then\\\", o.body[i].body))\",\n        \"target\": \"mypy.strconv.StrConv.visit_if_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_if_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return self.dump([a, (\\\"Else\\\", o.else_body.body)], o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_if_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 27,\n        \"src\": \"a: list[Any] = [o.body]\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(\\\"*\\\")\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"a.append(o.types[i])\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(o.vars[i])\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append(o.handlers[i])\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"a.append((\\\"Else\\\", o.else_body.body))\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Finally\\\", o.finally_body.body))\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_try_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Async\\\", \\\"\\\"))\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Expr\\\", [o.expr[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Target\\\", [o.target[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(o.unanalyzed_type)\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a + [o.body], o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return self.dump(a + [o.body], o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_with_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"a: list[Any] = [o.subject]\",\n        \"target\": \"mypy.strconv.StrConv.visit_match_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Pattern\\\", [o.patterns[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_match_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Guard\\\", [o.guards[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_match_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append((\\\"Body\\\", o.bodies[i].body))\",\n        \"target\": \"mypy.strconv.StrConv.visit_match_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_match_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"a: list[Any] = [o.name]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_alias_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(self.type_param(p))\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_alias_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a.append(self.type_param(p))\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_alias_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append(o.value)\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_alias_stmt\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_alias_stmt\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def type_param(self, p: mypy.nodes.TypeParam) -> list[Any]:\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"a.append(prefix + p.name)\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append(p.upper_bound)\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Values\\\", p.values))\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Default\\\", [p.default]))\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return [(\\\"TypeParam\\\", a)]\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"return [(\\\"TypeParam\\\", a)]\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return [(\\\"TypeParam\\\", a)]\",\n        \"target\": \"mypy.strconv.StrConv.type_param\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 27,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 36,\n        \"src\": \"pretty += f\\\" = {o.node.final_value}\\\"\",\n        \"target\": \"mypy.strconv.StrConv.visit_name_expr\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 21,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 22,\n        \"src\": \"n += f\\\" [{fullname}{id}]\\\"\",\n        \"target\": \"mypy.strconv.StrConv.pretty_name\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"expr\\\" has type \\\"Expression\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 19,\n        \"src\": \"if o.expr:\",\n        \"target\": \"mypy.strconv.StrConv.visit_yield_from_expr\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-truthy-bool for more info\",\n        \"offset\": 0,\n        \"src\": \"if o.expr:\",\n        \"target\": null\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 9,\n        \"src\": \"extra: list[str | tuple[str, list[Any]]] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[str | (str, list[Any])]\\\")\",\n        \"offset\": 5,\n        \"src\": \"extra.append(\\\"VarArg\\\")\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[str | (str, list[Any])]\\\")\",\n        \"offset\": 2,\n        \"src\": \"extra.append((\\\"KwArgs\\\", [o.arg_names[i], o.args[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"extra.append((\\\"KwArgs\\\", [o.arg_names[i], o.args[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"extra.append((\\\"KwArgs\\\", [o.arg_names[i], o.args[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[str | (str, list[Any])]\\\")\",\n        \"offset\": 2,\n        \"src\": \"extra.append((\\\"DictVarArg\\\", [o.args[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"extra.append((\\\"DictVarArg\\\", [o.args[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"extra.append((\\\"DictVarArg\\\", [o.args[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"a: list[Any] = [o.callee, (\\\"Args\\\", args)]\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a + extra, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[str | (str, list[Any])]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return self.dump(a + extra, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_call_expr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 55,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [\\\"Variance(COVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [\\\"Variance(COVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [\\\"Variance(CONTRAVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [\\\"Variance(CONTRAVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [(\\\"Values\\\", o.values)]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [(\\\"Values\\\", o.values)]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [f\\\"UpperBound({self.stringify_type(o.upper_bound)})\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [f\\\"UpperBound({self.stringify_type(o.upper_bound)})\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [\\\"Variance(COVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [\\\"Variance(COVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [\\\"Variance(CONTRAVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [\\\"Variance(CONTRAVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [f\\\"UpperBound({self.stringify_type(o.upper_bound)})\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [f\\\"UpperBound({self.stringify_type(o.upper_bound)})\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [\\\"Variance(COVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [\\\"Variance(COVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [\\\"Variance(CONTRAVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [\\\"Variance(CONTRAVARIANT)\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a += [f\\\"UpperBound({self.stringify_type(o.upper_bound)})\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"a += [f\\\"UpperBound({self.stringify_type(o.upper_bound)})\\\"]\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 56,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 6,\n        \"src\": \"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        \"target\": \"mypy.strconv.StrConv.visit_namedtuple_expr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 36,\n        \"src\": \"a: list[Any] = [o.begin_index, o.end_index, o.stride]\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if not a[0]:\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not a[0]:\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a[0] = \\\"<empty>\\\"\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if not a[1]:\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not a[1]:\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a[1] = \\\"<empty>\\\"\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_slice_expr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 24,\n        \"src\": \"a: list[Any] = []\",\n        \"target\": \"mypy.strconv.StrConv.visit_mapping_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Key\\\", [o.keys[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_mapping_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"a.append((\\\"Value\\\", [o.values[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_mapping_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Rest\\\", [o.rest]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_mapping_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_mapping_pattern\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"a: list[Any] = [o.class_ref]\",\n        \"target\": \"mypy.strconv.StrConv.visit_class_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Positionals\\\", o.positionals))\",\n        \"target\": \"mypy.strconv.StrConv.visit_class_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"a.append((\\\"Keyword\\\", [o.keyword_keys[i], o.keyword_values[i]]))\",\n        \"target\": \"mypy.strconv.StrConv.visit_class_pattern\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return self.dump(a, o)\",\n        \"target\": \"mypy.strconv.StrConv.visit_class_pattern\"\n      }\n    ],\n    \"mypy/stubdoc.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 65,\n        \"src\": \"def __eq__(self, other: Any) -> bool:\",\n        \"target\": \"mypy.stubdoc.ArgSig.__eq__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(other, ArgSig):\",\n        \"target\": \"mypy.stubdoc.ArgSig.__eq__\"\n      }\n    ],\n    \"mypy/stubgen.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 30,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 297,\n        \"src\": \"args.append(f\\\"{name}={arg.accept(self)}\\\")\",\n        \"target\": \"mypy.stubgen.AliasPrinter.visit_call_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1639,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 9,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 18,\n        \"src\": \"if ns.modules + ns.packages and ns.files:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if ns.modules + ns.packages and ns.files:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if ns.modules + ns.packages and ns.files:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if ns.quiet and ns.verbose:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if ns.quiet and ns.verbose:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if ns.inspect and ns.parse_only:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if ns.inspect and ns.parse_only:\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"os.makedirs(ns.output_dir, exist_ok=True)\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"no_import=ns.no_import,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"inspect=ns.inspect,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"doc_dir=ns.doc_dir,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"search_path=ns.search_path.split(\\\":\\\"),\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"ignore_errors=ns.ignore_errors,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"parse_only=ns.parse_only,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"include_private=ns.include_private,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"output_dir=ns.output_dir,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"modules=ns.modules,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"packages=ns.packages,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"files=ns.files,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"verbose=ns.verbose,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"quiet=ns.quiet,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"export_less=ns.export_less,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"include_docstrings=ns.include_docstrings,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"legacy=ns.legacy,\",\n        \"target\": \"mypy.stubgen.parse_options\"\n      }\n    ],\n    \"mypy/stubgenc.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 272,\n        \"src\": \"argspec = inspect.getfullargspec(func)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec | None\\\")\",\n        \"offset\": 4,\n        \"src\": \"if argspec is None:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 17,\n        \"src\": \"args = argspec.args\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 1,\n        \"src\": \"defaults = argspec.defaults\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...] | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"defaults = argspec.defaults\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 1,\n        \"src\": \"varargs = argspec.varargs\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 1,\n        \"src\": \"kwargs = argspec.varkw\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 1,\n        \"src\": \"annotations = argspec.annotations\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"annotations = argspec.annotations\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 1,\n        \"src\": \"kwonlyargs = argspec.kwonlyargs\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"FullArgSpec\\\")\",\n        \"offset\": 1,\n        \"src\": \"kwonlydefaults = argspec.kwonlydefaults\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"kwonlydefaults = argspec.kwonlydefaults\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"if key not in annotations:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"argtype = annotations[key]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"argtype = annotations[key]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if argtype is None:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(argtype, str):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return self.get_type_fullname(argtype)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 13,\n        \"src\": \"if arg in annotations:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"argtype = annotations[arg]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"argtype = annotations[arg]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if argtype == \\\"None\\\":\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"arglist.append(ArgSig(arg, argtype, default=True))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 4,\n        \"src\": \"def get_pos_default(i: int, _arg: str) -> Any | None:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...] | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if defaults and i >= len(args) - len(defaults):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...] | None | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if defaults and i >= len(args) - len(defaults):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if defaults and i >= len(args) - len(defaults):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return defaults[i - (len(args) - len(defaults))]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return defaults[i - (len(args) - len(defaults))]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return defaults[i - (len(args) - len(defaults))]\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (i: int, _arg: str) -> Any | None\\\")\",\n        \"offset\": 4,\n        \"src\": \"add_args(args, get_pos_default)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 9,\n        \"src\": \"def get_kw_default(_i: int, arg: str) -> Any | None:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if kwonlydefaults:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return kwonlydefaults.get(arg)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"return kwonlydefaults.get(arg)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (_i: int, arg: str) -> Any | None\\\")\",\n        \"offset\": 4,\n        \"src\": \"add_args(kwonlyargs, get_kw_default)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_default_function_sig\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str | None\\\")\",\n        \"offset\": 45,\n        \"src\": \"return getattr(obj, \\\"__module__\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_obj_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 8,\n        \"src\": \"all_items = self.get_members(self.module)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 2,\n        \"src\": \"all_items = sorted(all_items, key=lambda x: x[0])\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (x: (str, Any)) -> str\\\")\",\n        \"offset\": 0,\n        \"src\": \"all_items = sorted(all_items, key=lambda x: x[0])\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"all_items = sorted(all_items, key=lambda x: x[0])\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 2,\n        \"src\": \"for name, obj in all_items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for name, obj in all_items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for name, obj in all_items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if inspect.ismodule(obj) and obj.__name__ in self.known_modules:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 12,\n        \"src\": \"elif self.is_defined_in_module(obj) and not inspect.ismodule(obj):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 73,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"elif self.is_defined_in_module(obj) and not inspect.ismodule(obj):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 2,\n        \"src\": \"items.append((name, obj))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"items.append((name, obj))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"items.append((name, obj))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"obj_module_name = self.get_obj_module(obj)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 6,\n        \"src\": \"self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)})\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)})\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)})\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 88,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)})\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 10,\n        \"src\": \"for name, obj in items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for name, obj in items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for name, obj in items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if self.is_function(obj):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.generate_function_stub(name, obj, output=functions)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif inspect.isclass(obj):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.generate_class_stub(name, obj, output=types)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.generate_variable_stub(name, obj, output=variables)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_module\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 37,\n        \"message\": \"Name \\\"output\\\" may be undefined\",\n        \"offset\": 16,\n        \"src\": \"for i, line in enumerate(output):\",\n        \"target\": \"mypy.stubgenc\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 39,\n        \"src\": \"def get_members(self, obj: object) -> list[tuple[str, Any]]:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"obj_dict: Mapping[str, Any] = getattr(obj, \\\"__dict__\\\")\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"for name in obj_dict:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"value = getattr(obj, name)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 4,\n        \"src\": \"results.append((name, value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"results.append((name, value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"results.append((name, value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return results\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_members\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 10,\n        \"src\": \"return f\\\"type[{self.get_type_fullname(obj)}]\\\"\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_type_annotation\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 38,\n        \"src\": \"raw_lookup: Mapping[str, Any] = getattr(class_info.cls, \\\"__dict__\\\")\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_staticmethod\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"raw_value = raw_lookup.get(name, obj)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_staticmethod\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"raw_value = raw_lookup.get(name, obj)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_staticmethod\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return isinstance(raw_value, staticmethod)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_staticmethod\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_staticmethod\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 4,\n        \"src\": \"return getattr(obj, \\\"__abstractmethod__\\\", False)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_abstract_method\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 7,\n        \"src\": \"def is_property_readonly(prop: Any) -> bool:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_property_readonly\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"(prop: Any) -> bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"def is_property_readonly(prop: Any) -> bool:\",\n        \"target\": \"mypy.stubgenc\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return hasattr(prop, \\\"fset\\\") and prop.fset is None\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_property_readonly\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return hasattr(prop, \\\"fset\\\") and prop.fset is None\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.is_property_readonly\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 28,\n        \"src\": \"docstring: Any = getattr(obj, \\\"__doc__\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"docstring: Any = getattr(obj, \\\"__doc__\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not isinstance(docstring, str):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"docstring=docstring,\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 30,\n        \"src\": \"if docstring:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"docstring = self._indent_docstring(docstring)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 86,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"output.extend(self.format_func_def(inferred, decorators=decorators, docstring=docstring))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_function_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 63,\n        \"src\": \"docstring = getattr(raw_obj, \\\"__doc__\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"fget = getattr(raw_obj, \\\"fget\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if fget:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"alt_docstr = getattr(fget, \\\"__doc__\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"alt_docstr = getattr(fget, \\\"__doc__\\\", None)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if alt_docstr and docstring:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if alt_docstr and docstring:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"docstring += \\\"\\\\n\\\" + alt_docstr\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"docstring += \\\"\\\\n\\\" + alt_docstr\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"docstring += \\\"\\\\n\\\" + alt_docstr\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"elif alt_docstr:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"docstring = alt_docstr\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 3,\n        \"src\": \"self.module_name, name, docstring=docstring, is_abstract=False, class_info=class_info\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_property_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 44,\n        \"src\": \"typename = getattr(typ, \\\"__qualname__\\\", typ.__name__)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_type_fullname\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 4,\n        \"src\": \"typename = f\\\"{module_name}.{typename}\\\"\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_type_fullname\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 1,\n        \"src\": \"return typename\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.get_type_fullname\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 28,\n        \"src\": \"raw_lookup: Mapping[str, Any] = getattr(cls, \\\"__dict__\\\")\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 1,\n        \"src\": \"items = self.get_members(cls)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 2,\n        \"src\": \"items = sorted(items, key=lambda x: method_name_sort_key(x[0]))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (x: (str, Any)) -> (int, str)\\\")\",\n        \"offset\": 0,\n        \"src\": \"items = sorted(items, key=lambda x: method_name_sort_key(x[0]))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 69,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"items = sorted(items, key=lambda x: method_name_sort_key(x[0]))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"names = {x[0] for x in items}\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"names = {x[0] for x in items}\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"names = {x[0] for x in items}\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"attrs: list[tuple[str, Any]] = []\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str | None\\\")\",\n        \"offset\": 6,\n        \"src\": \"class_name, \\\"\\\", getattr(cls, \\\"__doc__\\\", None), cls, parent=parent_class\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 3,\n        \"src\": \"for attr, value in items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for attr, value in items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for attr, value in items:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Mapping[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"raw_value = raw_lookup.get(attr, value)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"raw_value = raw_lookup.get(attr, value)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"raw_value = raw_lookup.get(attr, value)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if self.is_method(class_info, attr, value) or self.is_classmethod(\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"class_info, attr, value\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"if self.is_staticmethod(class_info, attr, value):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 59,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif self.is_classmethod(class_info, attr, value):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"self.generate_function_stub(attr, value, output=methods, class_info=class_info)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif self.is_property(class_info, attr, raw_value):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"raw_value,\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"value,\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"elif inspect.isclass(value) and self.is_defined_in_module(value):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 70,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"elif inspect.isclass(value) and self.is_defined_in_module(value):\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.generate_class_stub(attr, value, types, parent_class=class_info)\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 2,\n        \"src\": \"attrs.append((attr, value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"attrs.append((attr, value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"attrs.append((attr, value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 2,\n        \"src\": \"for attr, value in attrs:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for attr, value in attrs:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for attr, value in attrs:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if attr == \\\"__hash__\\\" and value is None:\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 75,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"prop_type_name = self.strip_or_import(self.get_type_annotation(value))\",\n        \"target\": \"mypy.stubgenc.InspectionStubGenerator.generate_class_stub\"\n      }\n    ],\n    \"mypy/stubtest.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 74,\n        \"src\": \"def _style(message: str, **kwargs: Any) -> str:\",\n        \"target\": \"mypy.stubtest._style\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"kwargs.setdefault(\\\"color\\\", \\\"none\\\")\",\n        \"target\": \"mypy.stubtest._style\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return _formatter.style(message, **kwargs)\",\n        \"target\": \"mypy.stubtest._style\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 14,\n        \"src\": \"def __init__(\",\n        \"target\": \"mypy.stubtest.Error.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 25,\n        \"src\": \"self.runtime_object = runtime_object\",\n        \"target\": \"mypy.stubtest.Error.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 4,\n        \"src\": \"runtime_sig = safe_inspect_signature(runtime_object)\",\n        \"target\": \"mypy.stubtest.Error.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 2,\n        \"src\": \"self.runtime_desc = _truncate(repr(runtime_object), 100)\",\n        \"target\": \"mypy.stubtest.Error.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 2,\n        \"src\": \"runtime_is_async = inspect.iscoroutinefunction(runtime_object)\",\n        \"target\": \"mypy.stubtest.Error.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 40,\n        \"src\": \"if not isinstance(self.runtime_object, Missing):\",\n        \"target\": \"mypy.stubtest.Error.get_description\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"runtime_line = inspect.getsourcelines(self.runtime_object)[1]\",\n        \"target\": \"mypy.stubtest.Error.get_description\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"runtime_file = inspect.getsourcefile(self.runtime_object)\",\n        \"target\": \"mypy.stubtest.Error.get_description\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 81,\n        \"src\": \"bottom_module = bottom_frame.f_globals.get(\\\"__name__\\\", \\\"\\\")\",\n        \"target\": \"mypy.stubtest.test_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"bottom_module = bottom_frame.f_globals.get(\\\"__name__\\\", \\\"\\\")\",\n        \"target\": \"mypy.stubtest.test_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if bottom_module == \\\"__main__\\\" or bottom_module.split(\\\".\\\")[0] == \\\"mypy\\\":\",\n        \"target\": \"mypy.stubtest.test_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if bottom_module == \\\"__main__\\\" or bottom_module.split(\\\".\\\")[0] == \\\"mypy\\\":\",\n        \"target\": \"mypy.stubtest.test_module\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 68,\n        \"message\": \"The type \\\"<Deleted 'e'>\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 4,\n        \"src\": \"f\\\"encountered unexpected error, {type(e).__name__}: {e}\\\",\",\n        \"target\": \"mypy.stubtest.test_module\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def [_T] (func: (...) -> _T) -> _SingleDispatchCallable[_T]\\\")\",\n        \"offset\": 13,\n        \"src\": \"@singledispatch\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@singledispatch\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify(\",\n        \"target\": \"mypy.stubtest.verify\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 11,\n        \"src\": \"yield Error(object_path, \\\"is an unknown mypy node\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 50,\n        \"src\": \"@verify.register(nodes.MypyFile)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[MypyFile, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.MypyFile)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 7,\n        \"message\": \"Condition is always false\",\n        \"offset\": 7,\n        \"src\": \"if not isinstance(runtime, types.ModuleType):\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is not a module\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"runtime_all_as_set = set(runtime.__all__)\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 19,\n        \"src\": \"obj = getattr(r, attr)\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(obj, types.ModuleType):\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 22,\n        \"src\": \"obj_mod = obj.__module__\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if isinstance(obj_mod, str):\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 28,\n        \"src\": \"runtime_entry = getattr(runtime, entry, MISSING)\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 5,\n        \"src\": \"yield from verify(stub_entry, runtime_entry, object_path + [entry])\",\n        \"target\": \"mypy.stubtest.verify_mypyfile\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def _verify_final(\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 10,\n        \"src\": \"if not stub.is_final and not issubclass(runtime, enum.Enum):\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 10,\n        \"src\": \"runtime_final = getattr(runtime, \\\"__final__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"runtime_final = getattr(runtime, \\\"__final__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 4,\n        \"src\": \"if runtime_final and not stub.is_final:\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest._verify_final\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"def _verify_metaclass(\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[type[Any]]\\\")\",\n        \"offset\": 7,\n        \"src\": \"runtime_metaclass = type(runtime)\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"runtime_metaclass = type(runtime)\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[type[Any]]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if runtime_metaclass is not type and stub.metaclass_type is None:\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 29,\n        \"message\": \"The type \\\"type[type[Any]]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 2,\n        \"src\": \"runtime_desc=f\\\"{runtime_metaclass}\\\",\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[type[Any]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"runtime_desc=f\\\"{runtime_metaclass}\\\",\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[type[Any]]\\\")\",\n        \"offset\": 3,\n        \"src\": \"runtime_metaclass is type\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 13,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest._verify_metaclass\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 6,\n        \"src\": \"@verify.register(nodes.TypeInfo)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[TypeInfo, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.TypeInfo)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: TypeInfo, runtime: type[Any] | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.TypeInfo)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_typeinfo(\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: TypeInfo, runtime: type[Any] | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_typeinfo(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any] | Missing\\\")\",\n        \"offset\": 6,\n        \"src\": \"if not isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any] | Missing\\\")\",\n        \"offset\": 5,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 7,\n        \"message\": \"Condition is always false\",\n        \"offset\": 3,\n        \"src\": \"if not isinstance(runtime, type):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if not isinstance(runtime, type):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 8,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is not a type\\\", stub, runtime, stub_desc=repr(stub))\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"yield from _verify_final(stub, runtime, object_path)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 76,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"to_check.update(\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 21,\n        \"src\": \"runtime_attr = getattr(runtime, mangled_entry)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"runtime_attr = getattr(runtime, mangled_entry)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"if runtime_attr is not MISSING and type(runtime) is not runtime:\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[type[Any]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if runtime_attr is not MISSING and type(runtime) is not runtime:\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if runtime_attr is not MISSING and type(runtime) is not runtime:\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if runtime_attr is not MISSING and type(runtime) is not runtime:\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if getattr(runtime_attr, \\\"__objclass__\\\", None) is type(runtime):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if getattr(runtime_attr, \\\"__objclass__\\\", None) is type(runtime):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[type[Any]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if getattr(runtime_attr, \\\"__objclass__\\\", None) is type(runtime):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if getattr(runtime_attr, \\\"__objclass__\\\", None) is type(runtime):\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"and isinstance(runtime_attr, types.WrapperDescriptorType)\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"yield from verify(stub_to_verify, runtime_attr, object_path + [entry])\",\n        \"target\": \"mypy.stubtest.verify_typeinfo\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]:\",\n        \"target\": \"mypy.stubtest._static_lookup_runtime\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 13,\n        \"src\": \"def _verify_static_class_methods(\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"if inspect.isbuiltin(runtime):\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"BuiltinFunctionType[[*Untyped, **Untyped], Untyped]\\\")\",\n        \"offset\": 3,\n        \"src\": \"probably_class_method = isinstance(getattr(runtime, \\\"__self__\\\", None), type)\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 7,\n        \"src\": \"if static_runtime is MISSING:\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(static_runtime, classmethod) and not stub.is_class:\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(static_runtime, classmethod) and stub.is_class:\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(static_runtime, staticmethod) and not stub.is_static:\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(static_runtime, staticmethod) and stub.is_static:\",\n        \"target\": \"mypy.stubtest._verify_static_class_methods\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 45,\n        \"src\": \"if runtime_arg.default is not inspect.Parameter.empty:\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"runtime_type = get_mypy_type_of_runtime_value(runtime_arg.default)\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 12,\n        \"src\": \"and type(runtime_arg.default) is not object\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"and type(runtime_arg.default) is not object\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"and runtime_arg.default is not ...\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 13,\n        \"src\": \"and runtime_arg.default is not UNREPRESENTABLE\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 5,\n        \"src\": \"if type(stub_default) is not type(runtime_arg.default):\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if type(stub_default) is not type(runtime_arg.default):\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"defaults_match = bool(stub_default == runtime_arg.default)\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"defaults_match = bool(stub_default == runtime_arg.default)\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"f\\\"has a default value of {runtime_arg.default!r}, \\\"\",\n        \"target\": \"mypy.stubtest._verify_arg_default_value\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 28,\n        \"src\": \"def get_name(arg: Any) -> str:\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(arg, inspect.Parameter):\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(arg, nodes.Argument):\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 4,\n        \"src\": \"def get_type(arg: Any) -> str | None:\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(arg, inspect.Parameter):\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(arg, nodes.Argument):\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 4,\n        \"src\": \"def has_default(arg: Any) -> bool:\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(arg, inspect.Parameter):\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return arg.default is not inspect.Parameter.empty\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(arg, nodes.Argument):\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 4,\n        \"src\": \"def get_desc(arg: Any) -> str:\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_type = get_type(arg)\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"get_name(arg)\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"+ (\\\" = ...\\\" if has_default(arg) else \\\"\\\")\",\n        \"target\": \"mypy.stubtest.Signature.__str__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 246,\n        \"src\": \"and arg.default is not inspect.Parameter.empty\",\n        \"target\": \"mypy.stubtest._is_private_parameter\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 4,\n        \"src\": \"@verify.register(nodes.FuncItem)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[FuncItem, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.FuncItem)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: FuncItem, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.FuncItem)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_funcitem(\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: FuncItem, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_funcitem(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if not is_probably_a_function(runtime):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is not a function\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not callable(runtime):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 4,\n        \"src\": \"static_runtime = _static_lookup_runtime(object_path)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"for error_text in _verify_abstract_status(stub, runtime):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, error_text, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"for error_text in _verify_final_method(stub, runtime, static_runtime):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 0,\n        \"src\": \"for error_text in _verify_final_method(stub, runtime, static_runtime):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, error_text, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 0,\n        \"src\": \"for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 70,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is inconsistent, \\\" + message, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"signature = safe_inspect_signature(runtime)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"runtime_is_coroutine = inspect.iscoroutinefunction(runtime)\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 18,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 37,\n        \"message\": \"Name \\\"stub_sig\\\" may be undefined\",\n        \"offset\": 8,\n        \"src\": \"for message in _verify_signature(stub_sig, runtime_sig, function_name=stub.name):\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 47,\n        \"message\": \"Name \\\"runtime_sig\\\" may be undefined\",\n        \"offset\": 0,\n        \"src\": \"for message in _verify_signature(stub_sig, runtime_sig, function_name=stub.name):\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.verify_funcitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 5,\n        \"src\": \"@verify.register(Missing)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[Missing, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(Missing)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(Missing)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_none(\",\n        \"target\": \"mypy.stubtest.verify_none\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_none(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"yield Error(object_path, \\\"is not present in stub\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_none\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 3,\n        \"src\": \"@verify.register(nodes.Var)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[Var, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.Var)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: Var, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.Var)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_var(\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: Var, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_var(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"and is_read_only_property(runtime)\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 86,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"yield Error(object_path, \\\"is read-only at runtime but not in the stub\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"runtime_type = get_mypy_type_of_runtime_value(runtime)\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"if isinstance(runtime, enum.Enum):\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"runtime_type = get_mypy_type_of_runtime_value(runtime.value)\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 66,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 13,\n        \"src\": \"object_path, f\\\"variable differs from runtime type {runtime_type}\\\", stub, runtime\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 89,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"object_path, f\\\"variable differs from runtime type {runtime_type}\\\", stub, runtime\",\n        \"target\": \"mypy.stubtest.verify_var\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 4,\n        \"src\": \"@verify.register(nodes.OverloadedFuncDef)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[OverloadedFuncDef, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.OverloadedFuncDef)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: OverloadedFuncDef, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.OverloadedFuncDef)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_overloadedfuncdef(\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: OverloadedFuncDef, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_overloadedfuncdef(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 4,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"if is_read_only_property(runtime):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 90,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is read-only at runtime but not in the stub\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if not is_probably_a_function(runtime):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is not a function\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if not callable(runtime):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"for msg in _verify_abstract_status(first_part.func, runtime):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, msg, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"static_runtime = _static_lookup_runtime(object_path)\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 0,\n        \"src\": \"for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 70,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is inconsistent, \\\" + message, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"signature = safe_inspect_signature(runtime)\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 18,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.verify_overloadedfuncdef\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 6,\n        \"src\": \"@verify.register(nodes.TypeVarExpr)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[TypeVarExpr, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.TypeVarExpr)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: TypeVarExpr, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.TypeVarExpr)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_typevarexpr(\",\n        \"target\": \"mypy.stubtest.verify_typevarexpr\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: TypeVarExpr, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_typevarexpr(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_typevarexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"if not isinstance(runtime, TypeVar):\",\n        \"target\": \"mypy.stubtest.verify_typevarexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 59,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is not a TypeVar\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_typevarexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 4,\n        \"src\": \"@verify.register(nodes.ParamSpecExpr)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[ParamSpecExpr, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.ParamSpecExpr)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: ParamSpecExpr, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.ParamSpecExpr)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_paramspecexpr(\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: ParamSpecExpr, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_paramspecexpr(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 3,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any | None, Any | None)\\\")\",\n        \"offset\": 3,\n        \"src\": \"maybe_paramspec_types = (\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"getattr(typing, \\\"ParamSpec\\\", None),\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"getattr(typing_extensions, \\\"ParamSpec\\\", None),\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 2,\n        \"src\": \"paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Generator[Any, None, None]\\\")\",\n        \"offset\": 0,\n        \"src\": \"paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any | None, Any | None)\\\")\",\n        \"offset\": 0,\n        \"src\": \"paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if not paramspec_types or not isinstance(runtime, paramspec_types):\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if not paramspec_types or not isinstance(runtime, paramspec_types):\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"if not paramspec_types or not isinstance(runtime, paramspec_types):\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, \\\"is not a ParamSpec\\\", stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_paramspecexpr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 4,\n        \"src\": \"def _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]:\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(runtime, property):\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any) -> Any | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"yield from _verify_final_method(stub.func, runtime.fget, MISSING)\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(runtime, functools.cached_property):\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any) -> Any\\\")\",\n        \"offset\": 1,\n        \"src\": \"yield from _verify_final_method(stub.func, runtime.func, MISSING)\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if inspect.isdatadescriptor(runtime):\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"runtime_type = get_mypy_type_of_runtime_value(runtime)\",\n        \"target\": \"mypy.stubtest._verify_readonly_property\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 13,\n        \"src\": \"def _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]:\",\n        \"target\": \"mypy.stubtest._verify_abstract_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 2,\n        \"src\": \"runtime_abstract = getattr(runtime, \\\"__isabstractmethod__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_abstract_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"runtime_abstract = getattr(runtime, \\\"__isabstractmethod__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_abstract_status\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 2,\n        \"src\": \"if runtime_abstract and not stub_abstract:\",\n        \"target\": \"mypy.stubtest._verify_abstract_status\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 5,\n        \"src\": \"def _verify_final_method(\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 5,\n        \"src\": \"if getattr(runtime, \\\"__final__\\\", False) or (\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if getattr(runtime, \\\"__final__\\\", False) or (\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 1,\n        \"src\": \"static_runtime is not MISSING and getattr(static_runtime, \\\"__final__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"static_runtime is not MISSING and getattr(static_runtime, \\\"__final__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"static_runtime is not MISSING and getattr(static_runtime, \\\"__final__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 0,\n        \"src\": \"static_runtime is not MISSING and getattr(static_runtime, \\\"__final__\\\", False)\",\n        \"target\": \"mypy.stubtest._verify_final_method\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 60,\n        \"src\": \"@verify.register(nodes.Decorator)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[Decorator, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.Decorator)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: Decorator, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.Decorator)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_decorator(\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: Decorator, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_decorator(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 6,\n        \"src\": \"if not isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 5,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"for message in _verify_readonly_property(stub, runtime):\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, message, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"for message in _verify_abstract_status(stub.func, runtime):\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"yield Error(object_path, message, stub, runtime)\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"yield from verify(func, runtime, object_path)\",\n        \"target\": \"mypy.stubtest.verify_decorator\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]\\\")\",\n        \"offset\": 3,\n        \"src\": \"@verify.register(nodes.TypeAlias)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"_SingleDispatchRegisterCallable[TypeAlias, _SingleDispatchCallable[Iterator[Error], def (stub: Node | Missing, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]]]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.TypeAlias)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (stub: TypeAlias, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"@verify.register(nodes.TypeAlias)\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def verify_typealias(\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (stub: TypeAlias, runtime: Any | Missing, object_path: list[str]) -> Iterator[Error]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def verify_typealias(\",\n        \"target\": \"mypy.stubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | Missing\\\")\",\n        \"offset\": 5,\n        \"src\": \"if isinstance(runtime, Missing):\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"runtime_origin = get_origin(runtime) or runtime\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"runtime_origin = get_origin(runtime) or runtime\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"runtime_origin = get_origin(runtime) or runtime\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if not isinstance(runtime_origin, type):\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 31,\n        \"src\": \"if runtime_origin is not Union and (\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"yield Error(object_path, \\\"is not a Union\\\", stub, runtime, stub_desc=str(stub_target))\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | ()\\\")\",\n        \"offset\": 4,\n        \"src\": \"if tuple not in getattr(runtime_origin, \\\"__mro__\\\", ()):\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if tuple not in getattr(runtime_origin, \\\"__mro__\\\", ()):\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"object_path, \\\"is not a subclass of tuple\\\", stub, runtime, stub_desc=stub_desc\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if runtime_origin is not collections.abc.Callable:\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 71,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"object_path, \\\"is not a type alias for Callable\\\", stub, runtime, stub_desc=stub_desc\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 69,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"yield Error(object_path, \\\"is not a recognised type alias\\\", stub, runtime, stub_desc=stub_desc)\",\n        \"target\": \"mypy.stubtest.verify_typealias\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 91,\n        \"src\": \"def is_probably_a_function(runtime: Any) -> bool:\",\n        \"target\": \"mypy.stubtest.is_probably_a_function\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"isinstance(runtime, (types.FunctionType, types.BuiltinFunctionType))\",\n        \"target\": \"mypy.stubtest.is_probably_a_function\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"or isinstance(runtime, (types.MethodType, types.BuiltinMethodType))\",\n        \"target\": \"mypy.stubtest.is_probably_a_function\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"or (inspect.ismethoddescriptor(runtime) and callable(runtime))\",\n        \"target\": \"mypy.stubtest.is_probably_a_function\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"or (isinstance(runtime, types.MethodWrapperType) and callable(runtime))\",\n        \"target\": \"mypy.stubtest.is_probably_a_function\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any) -> None | None\\\")\",\n        \"offset\": 5,\n        \"src\": \"return isinstance(runtime, property) and runtime.fset is None\",\n        \"target\": \"mypy.stubtest.is_read_only_property\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def safe_inspect_signature(runtime: Any) -> inspect.Signature | None:\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"return inspect.signature(runtime)\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"hasattr(runtime, \\\"__text_signature__\\\")\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"and \\\"<unrepresentable>\\\" in runtime.__text_signature__\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"sig = runtime.__text_signature__.replace(\\\"<unrepresentable>\\\", \\\"...\\\")\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 68,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"sig = inspect._signature_fromstr(inspect.Signature, runtime, sig)  # type: ignore[attr-defined]\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": null,\n        \"column\": 68,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"sig = inspect._signature_fromstr(inspect.Signature, runtime, sig)  # type: ignore[attr-defined]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 77,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"sig = inspect._signature_fromstr(inspect.Signature, runtime, sig)  # type: ignore[attr-defined]\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": null,\n        \"column\": 77,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"sig = inspect._signature_fromstr(inspect.Signature, runtime, sig)  # type: ignore[attr-defined]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(sig, inspect.Signature)\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if parameter.default is ...\",\n        \"target\": \"mypy.stubtest.safe_inspect_signature\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 43,\n        \"src\": \"def get_mypy_type_of_runtime_value(runtime: Any) -> mypy.types.Type | None:\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"if runtime is None:\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if isinstance(runtime, property):\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"runtime,\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 18,\n        \"src\": \"no_default = arg.default is inspect.Parameter.empty\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 21,\n        \"message\": \"Condition is always true\",\n        \"offset\": 9,\n        \"src\": \"elif arg.kind == inspect.Parameter.VAR_KEYWORD:\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 19,\n        \"src\": \"stub = get_stub(type(runtime).__module__)\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"stub = get_stub(type(runtime).__module__)\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 3,\n        \"src\": \"type_name = type(runtime).__name__\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"type_name = type(runtime).__name__\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"if isinstance(runtime, tuple):\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"if isinstance(runtime, enum.Enum) and isinstance(runtime.name, str):\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(runtime, bytes):\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif isinstance(runtime, (bool, int, str)):\",\n        \"target\": \"mypy.stubtest.get_mypy_type_of_runtime_value\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 386,\n        \"src\": \"default=[],\",\n        \"target\": \"mypy.stubtest.parse_options\"\n      }\n    ],\n    \"mypy/stubutil.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 45,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 163,\n        \"src\": \"print(f\\\"{mod}: Failed to import, skipping{message}\\\")\",\n        \"target\": \"mypy.stubutil.report_missing\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 15,\n        \"message\": \"Name \\\"arg_module\\\" may be undefined\",\n        \"offset\": 118,\n        \"src\": \"if arg_module not in self.local_modules:\",\n        \"target\": \"mypy.stubutil\"\n      }\n    ],\n    \"mypy/suggestions.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 24,\n        \"message\": \"Name \\\"arg\\\" may be undefined\",\n        \"offset\": 526,\n        \"src\": \"args.append(arg)\",\n        \"target\": \"mypy.suggestions\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"partial_fallback\\\" has type \\\"Instance\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 331,\n        \"src\": \"if t.partial_fallback and t.partial_fallback.type:\",\n        \"target\": \"mypy.suggestions.TypeFormatter.visit_tuple_type\"\n      }\n    ],\n    \"mypy/test/data.py\": [\n      {\n        \"code\": \"no-untyped-usage\",\n        \"column\": 8,\n        \"message\": \"Usage of untyped name \\\"suite\\\" in typed context\",\n        \"offset\": 324,\n        \"src\": \"suite = parent.obj()\",\n        \"target\": \"mypy.test.data.DataDrivenTestCase.runtest\"\n      },\n      {\n        \"code\": \"no-untyped-usage\",\n        \"column\": 8,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-no-untyped-usage for more info\",\n        \"offset\": 0,\n        \"src\": \"suite = parent.obj()\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 0,\n        \"src\": \"suite = parent.obj()\",\n        \"target\": \"mypy.test.data.DataDrivenTestCase.runtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 1,\n        \"src\": \"suite.setup()\",\n        \"target\": \"mypy.test.data.DataDrivenTestCase.runtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 2,\n        \"src\": \"suite.run_case(self)\",\n        \"target\": \"mypy.test.data.DataDrivenTestCase.runtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 61,\n        \"src\": \"def repr_failure(\",\n        \"target\": \"mypy.test.data.DataDrivenTestCase.repr_failure\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 52,\n        \"message\": \"Name \\\"severity\\\" may be undefined\",\n        \"offset\": 167,\n        \"src\": \"output.append(f\\\"{fnam}:{i + 1}: {severity}: {message}\\\")\",\n        \"target\": \"mypy.test.data\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 58,\n        \"message\": \"Name \\\"severity\\\" may be undefined\",\n        \"offset\": 2,\n        \"src\": \"output.append(f\\\"{fnam}:{i + 1}:{col}: {severity}: {message}\\\")\",\n        \"target\": \"mypy.test.data\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 37,\n        \"src\": \"def pytest_sessionstart(session: Any) -> None:\",\n        \"target\": \"mypy.test.data.pytest_sessionstart\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 9,\n        \"src\": \"def pytest_addoption(parser: Any) -> None:\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"group = parser.getgroup(\\\"mypy\\\")\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"group.addoption(\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"group.addoption(\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"group.addoption(\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"group.addoption(\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"group.addoption(\",\n        \"target\": \"mypy.test.data.pytest_addoption\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_F: (...) -> object] (_F) -> _F\\\")\",\n        \"offset\": 9,\n        \"src\": \"@pytest.hookimpl(tryfirst=True)\",\n        \"target\": \"mypy.test.data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 2,\n        \"src\": \"if config.getoption(\\\"--collectonly\\\"):\",\n        \"target\": \"mypy.test.data.pytest_cmdline_main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 3,\n        \"src\": \"if config.getoption(\\\"--update-data\\\"):\",\n        \"target\": \"mypy.test.data.pytest_cmdline_main\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"def pytest_pycollect_makeitem(collector: Any, name: str, obj: object) -> Any | None:\",\n        \"target\": \"mypy.test.data.pytest_pycollect_makeitem\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 11,\n        \"src\": \"return DataSuiteCollector.from_parent(parent=collector, name=name)  # type: ignore[no-untyped-call, unused-ignore]\",\n        \"target\": \"mypy.test.data.pytest_pycollect_makeitem\"\n      },\n      {\n        \"code\": null,\n        \"column\": 57,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"return DataSuiteCollector.from_parent(parent=collector, name=name)  # type: ignore[no-untyped-call, unused-ignore]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"no-untyped-usage\",\n        \"column\": 27,\n        \"message\": \"Usage of untyped name \\\"obj\\\" in typed context\",\n        \"offset\": 73,\n        \"src\": \"suite: DataSuite = self.obj\",\n        \"target\": \"mypy.test.data.DataSuiteCollector.collect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 37,\n        \"src\": \"suite=self.parent.obj,\",\n        \"target\": \"mypy.test.data.DataFileCollector.collect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 1,\n        \"src\": \"file=os.path.join(self.parent.obj.data_prefix, self.name),\",\n        \"target\": \"mypy.test.data.DataFileCollector.collect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 17,\n        \"src\": \"data_path = Path(self.parent.obj.data_prefix) / self.name\",\n        \"target\": \"mypy.test.data.DataFileCollector._apply_fixes\"\n      }\n    ],\n    \"mypy/test/helpers.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 278,\n        \"src\": \"def retry_on_error(func: Callable[[], Any], max_wait: float = 1.0) -> None:\",\n        \"target\": \"mypy.test.helpers.retry_on_error\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 123,\n        \"src\": \"if testcase.config.getoption(\\\"--mypy-verbose\\\"):\",\n        \"target\": \"mypy.test.helpers.parse_options\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 99,\n        \"src\": \"base_version = getattr(mypy.version, \\\"base_based_version\\\", version)\",\n        \"target\": \"mypy.test.helpers.normalize_file_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str\\\")\",\n        \"offset\": 1,\n        \"src\": \"result = [re.sub(r\\\"\\\\b\\\" + re.escape(base_version) + r\\\"\\\\b\\\", \\\"$VERSION\\\", x) for x in result]\",\n        \"target\": \"mypy.test.helpers.normalize_file_output\"\n      }\n    ],\n    \"mypy/test/meta/_pytest.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 19,\n        \"message\": \"Name \\\"proc\\\" may be undefined\",\n        \"offset\": 68,\n        \"src\": \"stdout=proc.stdout.decode(),\",\n        \"target\": \"mypy.test.meta._pytest\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 19,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-possibly-undefined for more info\",\n        \"offset\": 0,\n        \"src\": \"stdout=proc.stdout.decode(),\",\n        \"target\": null\n      }\n    ],\n    \"mypy/test/test_ref_info.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 42,\n        \"src\": \"data: Any = json.load(refs_file)\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"for item in data:\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for item in data:\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"a.append(f\\\"{item['line']}:{item['column']}:{item['target']}\\\")\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"a.append(f\\\"{item['line']}:{item['column']}:{item['target']}\\\")\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"a.append(f\\\"{item['line']}:{item['column']}:{item['target']}\\\")\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"a.append(f\\\"{item['line']}:{item['column']}:{item['target']}\\\")\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"a.append(f\\\"{item['line']}:{item['column']}:{item['target']}\\\")\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"a.append(f\\\"{item['line']}:{item['column']}:{item['target']}\\\")\",\n        \"target\": \"mypy.test.test_ref_info.RefInfoSuite.run_case\"\n      }\n    ],\n    \"mypy/test/testcheck.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 64,\n        \"src\": \"if lxml is None and os.path.basename(testcase.file) == \\\"check-reports.test\\\":\",\n        \"target\": \"mypy.test.testcheck.TypeCheckSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"False | Untyped\\\")\",\n        \"offset\": 144,\n        \"src\": \"if output != a and testcase.config.getoption(\\\"--update-data\\\", False):\",\n        \"target\": \"mypy.test.testcheck.TypeCheckSuite.run_case_once\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 0,\n        \"src\": \"if output != a and testcase.config.getoption(\\\"--update-data\\\", False):\",\n        \"target\": \"mypy.test.testcheck.TypeCheckSuite.run_case_once\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 82,\n        \"src\": \"meta = build.find_cache_meta(id, path, manager)\",\n        \"target\": \"mypy.test.testcheck.TypeCheckSuite.find_missing_cache_files\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 1,\n        \"src\": \"if not build.validate_meta(meta, id, path, ignore_errors, manager):\",\n        \"target\": \"mypy.test.testcheck.TypeCheckSuite.find_missing_cache_files\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"CacheMeta | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if not build.validate_meta(meta, id, path, ignore_errors, manager):\",\n        \"target\": \"mypy.test.testcheck.TypeCheckSuite.find_missing_cache_files\"\n      }\n    ],\n    \"mypy/test/testcmdline.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 49,\n        \"src\": \"if lxml is None and os.path.basename(testcase.file) == \\\"reports.test\\\":\",\n        \"target\": \"mypy.test.testcmdline.PythonCmdlineSuite.run_case\"\n      }\n    ],\n    \"mypy/test/testdaemon.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(int, Any)\\\")\",\n        \"offset\": 106,\n        \"src\": \"return err.returncode, err.output\",\n        \"target\": \"mypy.test.testdaemon.run_cmd\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return err.returncode, err.output\",\n        \"target\": \"mypy.test.testdaemon.run_cmd\"\n      }\n    ],\n    \"mypy/test/testfinegrained.py\": [\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 78,\n        \"src\": \"return\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 97,\n        \"src\": \"response = server.check(sources, export_types=False, is_tty=False, terminal_width=-1)\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"out = response[\\\"out\\\"] or response[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"out = response[\\\"out\\\"] or response[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"out = response[\\\"out\\\"] or response[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"out = response[\\\"out\\\"] or response[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_check\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert isinstance(out, str)\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.run_check\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 18,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 136,\n        \"src\": \"res = cast(\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"res = cast(\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 13,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"val = val.replace(\\\"\\\\\\\\\\\\\\\\\\\", \\\"\\\\\\\\\\\")\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"val = val.replace(tmp_dir + os.path.sep, \\\"\\\")\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"val = val.replace(os.path.realpath(tmp_dir) + os.path.sep, \\\"\\\")\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"val = val.replace(os.path.abspath(tmp_dir) + os.path.sep, \\\"\\\")\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"output.extend(val.strip().split(\\\"\\\\n\\\"))\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_suggest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 18,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 21,\n        \"src\": \"res = cast(\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"res = cast(\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 14,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"val = res[\\\"error\\\"] if \\\"error\\\" in res else res[\\\"out\\\"] + res[\\\"err\\\"]\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"output.extend(val.strip().split(\\\"\\\\n\\\"))\",\n        \"target\": \"mypy.test.testfinegrained.FineGrainedSuite.maybe_inspect\"\n      }\n    ],\n    \"mypy/test/testinfer.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 164,\n        \"src\": \"d.items(), [({0, 1}, {\\\"group1\\\"}), ({2, 3, 4}, {\\\"group2\\\"}), ({5, 6, 7}, {\\\"group3\\\"})]\",\n        \"target\": \"mypy.test.testinfer.OperandDisjointDictSuite.test_independent_maps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 14,\n        \"src\": \"[\",\n        \"target\": \"mypy.test.testinfer.OperandDisjointDictSuite.test_partial_merging\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 17,\n        \"src\": \"[({0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16}, {\\\"a\\\", \\\"b\\\", \\\"c\\\", \\\"d\\\", \\\"e\\\", \\\"f\\\"})],\",\n        \"target\": \"mypy.test.testinfer.OperandDisjointDictSuite.test_full_merging\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 11,\n        \"src\": \"self.assertEqual(d.items(), [({0, 1, 2, 3, 4, 5, 6}, {\\\"a\\\", \\\"b\\\", \\\"c\\\", \\\"d\\\", \\\"e\\\"})])\",\n        \"target\": \"mypy.test.testinfer.OperandDisjointDictSuite.test_merge_with_multiple_overlaps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 29,\n        \"src\": \"[(\\\"==\\\", [0, 1]), (\\\"==\\\", [1, 2]), (\\\"<\\\", [2, 3]), (\\\"==\\\", [3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_basic_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"[(\\\"==\\\", [0, 1, 2]), (\\\"<\\\", [2, 3]), (\\\"==\\\", [3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_basic_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"[(\\\"==\\\", [0, 1]), (\\\"==\\\", [1, 2]), (\\\"<\\\", [2, 3]), (\\\"==\\\", [3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_basic_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"[(\\\"==\\\", [0, 1, 2]), (\\\"<\\\", [2, 3]), (\\\"==\\\", [3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_basic_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 17,\n        \"src\": \"[(\\\"==\\\", [0, 1, 2]), (\\\"is\\\", [2, 3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_multiple_groups\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"[(\\\"==\\\", [0, 1, 2, 3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_multiple_groups\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"[(\\\"is\\\", [0, 1]), (\\\"==\\\", [1, 2, 3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_multiple_groups\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"[(\\\"is\\\", [0, 1, 2]), (\\\"<\\\", [2, 3]), (\\\"==\\\", [3, 4, 5])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_multiple_groups\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 58,\n        \"src\": \"[(\\\"==\\\", [0, 1, 2]), (\\\"is\\\", [2, 3, 4])],\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_multiple_groups_different_operators\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 26,\n        \"src\": \"self.assertEqual(group_comparison_operands([], {}, set()), [])\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_empty_pair_list\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 68,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.assertEqual(group_comparison_operands([], {}, {\\\"==\\\"}), [])\",\n        \"target\": \"mypy.test.testinfer.OperandComparisonGroupingSuite.test_empty_pair_list\"\n      }\n    ],\n    \"mypy/test/testmerge.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 175,\n        \"src\": \"if isinstance(node.node, Node):\",\n        \"target\": \"mypy.test.testmerge.ASTMergeSuite.format_symbol_table_node\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 3,\n        \"src\": \"s = f\\\"? ({type(node.node)})\\\"\",\n        \"target\": \"mypy.test.testmerge.ASTMergeSuite.format_symbol_table_node\"\n      }\n    ],\n    \"mypy/test/testpep561.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 22,\n        \"message\": \"Name \\\"program\\\" may be undefined\",\n        \"offset\": 169,\n        \"src\": \"os.remove(program)\",\n        \"target\": \"mypy.test.testpep561\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 4,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 20,\n        \"src\": \"packages = \\\"packages\\\"\",\n        \"target\": \"mypy.test.testpep561.test_mypy_path_is_respected\"\n      }\n    ],\n    \"mypy/test/testreports.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 19,\n        \"src\": \"@pytest.mark.skipif(lxml is None, reason=\\\"Cannot import lxml. Is it installed?\\\")\",\n        \"target\": \"mypy.test.testreports\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 5,\n        \"src\": \"@pytest.mark.skipif(lxml is None, reason=\\\"Cannot import lxml. Is it installed?\\\")\",\n        \"target\": \"mypy.test.testreports\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 11,\n        \"src\": \"child_package.classes[\\\"class\\\"] = etree.Element(\\\"class\\\")\",\n        \"target\": \"mypy.test.testreports.CoberturaReportSuite.test_as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 0,\n        \"src\": \"child_package.classes[\\\"class\\\"] = etree.Element(\\\"class\\\")\",\n        \"target\": \"mypy.test.testreports.CoberturaReportSuite.test_as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any (from unimported type)\\\"\",\n        \"offset\": 19,\n        \"src\": \"expected_output, etree.tostring(cobertura_package.as_xml(), pretty_print=True)\",\n        \"target\": \"mypy.test.testreports.CoberturaReportSuite.test_as_xml\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"expected_output, etree.tostring(cobertura_package.as_xml(), pretty_print=True)\",\n        \"target\": \"mypy.test.testreports.CoberturaReportSuite.test_as_xml\"\n      }\n    ],\n    \"mypy/test/teststubgen.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 55,\n        \"src\": \"@unittest.skipIf(sys.platform == \\\"win32\\\", \\\"clean up fails on Windows\\\")\",\n        \"target\": \"mypy.test.teststubgen\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 27,\n        \"src\": \"@unittest.skipIf(sys.platform == \\\"win32\\\", \\\"clean up fails on Windows\\\")\",\n        \"target\": \"mypy.test.teststubgen\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 26,\n        \"src\": \"@unittest.skipIf(sys.platform == \\\"win32\\\", \\\"clean up fails on Windows\\\")\",\n        \"target\": \"mypy.test.teststubgen\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 21,\n        \"src\": \"def run(self, result: Any | None = None) -> Any | None:\",\n        \"target\": \"mypy.test.teststubgen.StubgenCmdLineSuite.run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 2,\n        \"src\": \"return super().run(result)\",\n        \"target\": \"mypy.test.teststubgen.StubgenCmdLineSuite.run\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 452,\n        \"src\": \"@unittest.skipIf(sys.platform == \\\"win32\\\", \\\"Tests building the paths common ancestor on *nix\\\")\",\n        \"target\": \"mypy.test.teststubgen\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 16,\n        \"src\": \"@unittest.skipIf(\",\n        \"target\": \"mypy.test.teststubgen\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 95,\n        \"src\": \"@unittest.skipIf(sys.platform == \\\"win32\\\", \\\"clean up fails on Windows\\\")\",\n        \"target\": \"mypy.test.teststubgen\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str | None\\\")\",\n        \"offset\": 191,\n        \"src\": \"docstring=getattr(TestClass, \\\"__doc__\\\", None),\",\n        \"target\": \"mypy.test.teststubgen.StubgencSuite.test_non_c_generate_signature_with_kw_only_args\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (self: Any) -> str\\\")\",\n        \"offset\": 298,\n        \"src\": \"test.__doc__ = property(lambda self: \\\"test(arg0: str) -> None\\\")  # type: ignore[assignment]\",\n        \"target\": \"mypy.test.teststubgen.StubgencSuite.test_generate_c_function_no_crash_for_non_str_docstring\"\n      },\n      {\n        \"code\": null,\n        \"column\": 32,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"test.__doc__ = property(lambda self: \\\"test(arg0: str) -> None\\\")  # type: ignore[assignment]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 31,\n        \"src\": \"TestClass.attribute,\",\n        \"target\": \"mypy.test.teststubgen.StubgencSuite.test_generate_c_property_with_pybind11\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | str | None\\\")\",\n        \"offset\": 202,\n        \"src\": \"docstring=getattr(TestClass, \\\"__doc__\\\", None),\",\n        \"target\": \"mypy.test.teststubgen.StubgencSuite.test_generate_c_type_with_overload_shiboken\"\n      }\n    ],\n    \"mypy/test/teststubtest.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 206,\n        \"src\": \"def collect_cases(fn: Callable[..., Iterator[Case]]) -> FunctionType[..., None]:\",\n        \"target\": \"mypy.test.teststubtest.collect_cases\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 8,\n        \"src\": \"def test(*args: Any, **kwargs: Any) -> None:\",\n        \"target\": \"mypy.test.teststubtest.collect_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 1,\n        \"src\": \"cases = list(fn(*args, **kwargs))\",\n        \"target\": \"mypy.test.teststubtest.collect_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"cases = list(fn(*args, **kwargs))\",\n        \"target\": \"mypy.test.teststubtest.collect_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (*args: Any, **kwargs: Any) -> None\\\")\",\n        \"offset\": 30,\n        \"src\": \"return test\",\n        \"target\": \"mypy.test.teststubtest.collect_cases\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 4,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_basic_good(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 18,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_types(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 21,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_coroutines(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 9,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_arg_name(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 39,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_arg_kind(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 32,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_private_parameters(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 71,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_default_presence(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 34,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_default_value(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 74,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_static_class_method(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 64,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_arg_mismatch(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 17,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_varargs_varkwargs(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 66,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_overload(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 122,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_property(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 103,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_cached_property(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 99,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_var(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 63,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_type_alias(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 190,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_enum(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 117,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_decorator(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 16,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_all_at_runtime_not_stub(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 9,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_all_in_stub_not_at_runtime(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 3,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_all_in_stub_different_to_all_at_runtime(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 16,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_missing(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 43,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_missing_no_runtime_all(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 8,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_missing_no_runtime_all_terrible(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 17,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_non_public_1(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 6,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_non_public_2(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 5,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_dunders(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 27,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_not_subclassable(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 10,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_has_runtime_final_decorator(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 256,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_name_mangling(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 58,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_mro(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 31,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_good_literal(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 33,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_bad_literal(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 35,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_special_subtype(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 34,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_runtime_typing_objects(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 31,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_named_tuple(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 35,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_named_tuple_typing_and_collections(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 29,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_type_var(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 14,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_metaclass_match(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 48,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_metaclass_abcmeta(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 13,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_abstract_methods(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 97,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_abstract_properties(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 66,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_type_check_only(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (fn: (...) -> Iterator[Case]) -> def (...) -> None\\\")\",\n        \"offset\": 65,\n        \"src\": \"@collect_cases\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 4,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (...) -> None\\\")\",\n        \"offset\": 1,\n        \"src\": \"def test_no_param_defaults_bool_eval(self) -> Iterator[Case]:\",\n        \"target\": \"mypy.test.teststubtest\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 176,\n        \"src\": \"def f(a: int, b: int, *, c: int, d: int = 0, **kwargs: Any) -> None:\",\n        \"target\": \"mypy.test.teststubtest.StubtestMiscUnit.test_signature\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 81,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"def (a: int, b: int, *, c: int, d: int = ..., **kwargs: Any) -> None\\\")\",\n        \"offset\": 4,\n        \"src\": \"str(mypy.stubtest.Signature.from_inspect_signature(inspect.signature(f)))\",\n        \"target\": \"mypy.test.teststubtest.StubtestMiscUnit.test_signature\"\n      }\n    ],\n    \"mypy/test/testtypegen.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 65,\n        \"src\": \"if node.line != -1 and map[node]:\",\n        \"target\": \"mypy.test.testtypegen.TypeExportSuite.run_case\"\n      }\n    ],\n    \"mypy/test/testtypes.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 1629,\n        \"src\": \"@skipUnless(mypy.expandtype.__file__.endswith(\\\".py\\\"), \\\"Skip for compiled mypy\\\")\",\n        \"target\": \"mypy.test.testtypes\"\n      }\n    ],\n    \"mypy/test/update_data.py\": [\n      {\n        \"code\": \"unreachable\",\n        \"column\": 22,\n        \"message\": \"Intersection of \\\"DataSuiteCollector & DataFileCollector\\\" cannot exist: would have incompatible method signatures\",\n        \"offset\": 17,\n        \"src\": \"assert isinstance(collector, DataFileCollector)\",\n        \"target\": \"mypy.test.update_data.update_testcase_output\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 4,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 1,\n        \"src\": \"for fix in _iter_fixes(testcase, actual, incremental_step=incremental_step):\",\n        \"target\": \"mypy.test.update_data.update_testcase_output\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 30,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 43,\n        \"src\": \"file_path = f\\\"tmp/{test_item.arg}\\\"\",\n        \"target\": \"mypy.test.update_data._iter_fixes\"\n      }\n    ],\n    \"mypy/traverser.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 123,\n        \"src\": \"if o.arguments is not None:\",\n        \"target\": \"mypy.traverser.TraverserVisitor.visit_func\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 69,\n        \"src\": \"if o.expr is not None:\",\n        \"target\": \"mypy.traverser.TraverserVisitor.visit_assert_stmt\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 6,\n        \"src\": \"if o.expr is not None:\",\n        \"target\": \"mypy.traverser.TraverserVisitor.visit_del_stmt\"\n      }\n    ],\n    \"mypy/type_visitor.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 278,\n        \"src\": \"cast(Any, t.partial_fallback.accept(self)),\",\n        \"target\": \"mypy.type_visitor.TypeTranslator.visit_tuple_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"cast(Any, t.partial_fallback.accept(self)),\",\n        \"target\": \"mypy.type_visitor.TypeTranslator.visit_tuple_type\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 12,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 15,\n        \"src\": \"cast(Any, t.fallback.accept(self)),\",\n        \"target\": \"mypy.type_visitor.TypeTranslator.visit_typeddict_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"cast(Any, t.fallback.accept(self)),\",\n        \"target\": \"mypy.type_visitor.TypeTranslator.visit_typeddict_type\"\n      }\n    ],\n    \"mypy/typeanal.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 60,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 1242,\n        \"src\": \"f'ParamSpec must have \\\"*args\\\" typed as \\\"{name}.args\\\" and \\\"**kwargs\\\" typed as \\\"{name}.kwargs\\\"',\",\n        \"target\": \"mypy.typeanal.TypeAnalyser.visit_callable_type\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 98,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 0,\n        \"src\": \"f'ParamSpec must have \\\"*args\\\" typed as \\\"{name}.args\\\" and \\\"**kwargs\\\" typed as \\\"{name}.kwargs\\\"',\",\n        \"target\": \"mypy.typeanal.TypeAnalyser.visit_callable_type\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 62,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 558,\n        \"src\": \"self.fail(f'Invalid argument constructor \\\"{found.fullname}\\\"', arg)\",\n        \"target\": \"mypy.typeanal.TypeAnalyser.analyze_callable_args\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 57,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 759,\n        \"src\": \"assert t.alias is not None, f\\\"Unfixed type alias {t.type_ref}\\\"\",\n        \"target\": \"mypy.typeanal.DivergingAliasDetector.visit_type_alias_type\"\n      }\n    ],\n    \"mypy/typeops.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1084,\n        \"src\": \"sum_types: dict[str, tuple[set[Any], list[int]]] = {}\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, (set[Any], list[int])]\\\")\",\n        \"offset\": 6,\n        \"src\": \"if fullname not in sum_types:\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, (set[Any], list[int])]\\\")\",\n        \"offset\": 1,\n        \"src\": \"sum_types[fullname] = (\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(set[Any], list[int])\\\")\",\n        \"offset\": 0,\n        \"src\": \"sum_types[fullname] = (\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"set(typ.fallback.type.enum_members)\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"else {True, False}\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, (set[Any], list[int])]\\\")\",\n        \"offset\": 4,\n        \"src\": \"literals, indexes = sum_types[fullname]\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(set[Any], list[int])\\\")\",\n        \"offset\": 0,\n        \"src\": \"literals, indexes = sum_types[fullname]\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"literals, indexes = sum_types[fullname]\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"literals.discard(typ.value)\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"set[Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"if not literals:\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 6,\n        \"src\": \"proper_types, [(i not in marked_for_deletion) for i in range(len(proper_types))]\",\n        \"target\": \"mypy.typeops.try_contracting_literals_in_union\"\n      }\n    ],\n    \"mypy/types.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 44,\n        \"src\": \"JsonDict: _TypeAlias = dict[str, Any]\",\n        \"target\": \"mypy.types\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 136,\n        \"src\": \"_dummy: Final[Any] = object()\",\n        \"target\": \"mypy.types\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 245,\n        \"src\": \"\\\"args\\\": [arg.serialize() for arg in self.args],\",\n        \"target\": \"mypy.types.TypeAliasType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"args\\\": [arg.serialize() for arg in self.args],\",\n        \"target\": \"mypy.types.TypeAliasType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeAliasType\\\"\",\n        \"target\": \"mypy.types.TypeAliasType.deserialize\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 165,\n        \"src\": \"def copy_modified(self, *, id: TypeVarId, **kwargs: Any) -> Self:\",\n        \"target\": \"mypy.types.TypeVarLikeType.copy_modified\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 40,\n        \"src\": \"def copy_modified(\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"values: Bogus[list[Type]] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"upper_bound: Bogus[Type] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"default: Bogus[Type] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"id: Bogus[TypeVarId] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"scopename: Bogus[str | None] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"id=self.id if id is _dummy else id,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"values=self.values if values is _dummy else values,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 59,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"default=self.default if default is _dummy else default,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"scopename=self.scopename if scopename == _dummy else scopename,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"scopename=self.scopename if scopename == _dummy else scopename,\",\n        \"target\": \"mypy.types.TypeVarType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 20,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.TypeVarType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 6,\n        \"src\": \"\\\"values\\\": [v.serialize() for v in self.values],\",\n        \"target\": \"mypy.types.TypeVarType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"values\\\": [v.serialize() for v in self.values],\",\n        \"target\": \"mypy.types.TypeVarType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeVarType\\\"\",\n        \"target\": \"mypy.types.TypeVarType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"values=[deserialize_type(v) for v in data[\\\"values\\\"]],\",\n        \"target\": \"mypy.types.TypeVarType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"values=[deserialize_type(v) for v in data[\\\"values\\\"]],\",\n        \"target\": \"mypy.types.TypeVarType.deserialize\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 68,\n        \"src\": \"def copy_modified(\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"id: Bogus[TypeVarId] = _dummy,\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"prefix: Bogus[Parameters] = _dummy,\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"default: Bogus[Type] = _dummy,\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"id if id is not _dummy else self.id,\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"default=default if default is not _dummy else self.default,\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"prefix=prefix if prefix is not _dummy else self.prefix,\",\n        \"target\": \"mypy.types.ParamSpecType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 25,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.ParamSpecType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"ParamSpecType\\\"\",\n        \"target\": \"mypy.types.ParamSpecType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 41,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.TypeVarTupleType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeVarTupleType\\\"\",\n        \"target\": \"mypy.types.TypeVarTupleType.deserialize\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 22,\n        \"src\": \"def copy_modified(\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"id: Bogus[TypeVarId] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"upper_bound: Bogus[Type] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"default: Bogus[Type] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"min_len: Bogus[int] = _dummy,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"self.id if id is _dummy else id,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"self.upper_bound if upper_bound is _dummy else upper_bound,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"self.default if default is _dummy else default,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"min_len=self.min_len if min_len is _dummy else min_len,\",\n        \"target\": \"mypy.types.TypeVarTupleType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 57,\n        \"src\": \"def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType:\",\n        \"target\": \"mypy.types.UnboundType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if args is _dummy:\",\n        \"target\": \"mypy.types.UnboundType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any (unannotated)\\\"\",\n        \"offset\": 15,\n        \"src\": \"with visitor.string_type():\",\n        \"target\": \"mypy.types.UnboundType.accept\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 19,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.UnboundType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 3,\n        \"src\": \"\\\"args\\\": [a.serialize() for a in self.args],\",\n        \"target\": \"mypy.types.UnboundType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"args\\\": [a.serialize() for a in self.args],\",\n        \"target\": \"mypy.types.UnboundType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"UnboundType\\\"\",\n        \"target\": \"mypy.types.UnboundType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"[deserialize_type(a) for a in data[\\\"args\\\"]],\",\n        \"target\": \"mypy.types.UnboundType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[deserialize_type(a) for a in data[\\\"args\\\"]],\",\n        \"target\": \"mypy.types.UnboundType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 97,\n        \"src\": \"return {\\\".class\\\": \\\"UnpackType\\\", \\\"type\\\": self.type.serialize()}\",\n        \"target\": \"mypy.types.UnpackType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"UnpackType\\\"\",\n        \"target\": \"mypy.types.UnpackType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 58,\n        \"src\": \"original_any: Bogus[AnyType | None] = _dummy,\",\n        \"target\": \"mypy.types.AnyType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"missing_import_name: Bogus[str | None] = _dummy,\",\n        \"target\": \"mypy.types.AnyType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if original_any is _dummy:\",\n        \"target\": \"mypy.types.AnyType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"if missing_import_name is _dummy:\",\n        \"target\": \"mypy.types.AnyType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 17,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.AnyType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"assert data[\\\".class\\\"] == cls.__name__\",\n        \"target\": \"mypy.types.AnyType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 103,\n        \"src\": \"return {\\\".class\\\": \\\"UninhabitedType\\\"}\",\n        \"target\": \"mypy.types.UninhabitedType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"UninhabitedType\\\"\",\n        \"target\": \"mypy.types.UninhabitedType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 28,\n        \"src\": \"return {\\\".class\\\": \\\"NoneType\\\"}\",\n        \"target\": \"mypy.types.NoneType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"NoneType\\\"\",\n        \"target\": \"mypy.types.NoneType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 43,\n        \"src\": \"return {\\\".class\\\": \\\"DeletedType\\\", \\\"source\\\": self.source}\",\n        \"target\": \"mypy.types.DeletedType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"DeletedType\\\"\",\n        \"target\": \"mypy.types.DeletedType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 31,\n        \"src\": \"def copy_modified(self, type_guard: Bogus[Type] = _dummy) -> TypeGuardType:\",\n        \"target\": \"mypy.types.TypeGuardType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"type_guard if type_guard is not _dummy else self.type_guard,\",\n        \"target\": \"mypy.types.TypeGuardType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 52,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.TypeGuardType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeGuardType\\\"\",\n        \"target\": \"mypy.types.TypeGuardType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 44,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.ExtraAttrs.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, dict[Any, Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"attrs\\\": {k: v.serialize() for k, v in self.attrs.items()},\",\n        \"target\": \"mypy.types.ExtraAttrs.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[Any, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"attrs\\\": {k: v.serialize() for k, v in self.attrs.items()},\",\n        \"target\": \"mypy.types.ExtraAttrs.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"immutable\\\": list(self.immutable),\",\n        \"target\": \"mypy.types.ExtraAttrs.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"immutable\\\": list(self.immutable),\",\n        \"target\": \"mypy.types.ExtraAttrs.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"ExtraAttrs\\\"\",\n        \"target\": \"mypy.types.ExtraAttrs.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"{k: deserialize_type(v) for k, v in data[\\\"attrs\\\"].items()},\",\n        \"target\": \"mypy.types.ExtraAttrs.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{k: deserialize_type(v) for k, v in data[\\\"attrs\\\"].items()},\",\n        \"target\": \"mypy.types.ExtraAttrs.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{k: deserialize_type(v) for k, v in data[\\\"attrs\\\"].items()},\",\n        \"target\": \"mypy.types.ExtraAttrs.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{k: deserialize_type(v) for k, v in data[\\\"attrs\\\"].items()},\",\n        \"target\": \"mypy.types.ExtraAttrs.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 124,\n        \"src\": \"\\\"args\\\": [arg.serialize() for arg in self.args],\",\n        \"target\": \"mypy.types.Instance.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"args\\\": [arg.serialize() for arg in self.args],\",\n        \"target\": \"mypy.types.Instance.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 13,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"Instance\\\"\",\n        \"target\": \"mypy.types.Instance.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 17,\n        \"src\": \"args: Bogus[list[Type]] = _dummy,\",\n        \"target\": \"mypy.types.Instance.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"last_known_value: Bogus[LiteralType | None] = _dummy,\",\n        \"target\": \"mypy.types.Instance.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"args=args if args is not _dummy else self.args,\",\n        \"target\": \"mypy.types.Instance.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"last_known_value if last_known_value is not _dummy else self.last_known_value\",\n        \"target\": \"mypy.types.Instance.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 145,\n        \"src\": \"arg_types: Bogus[Sequence[Type]] = _dummy,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_kinds: Bogus[list[ArgKind]] = _dummy,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_names: Bogus[Sequence[str | None]] = _dummy,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"is_ellipsis_args: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"imprecise_arg_kinds: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"arg_types=arg_types if arg_types is not _dummy else self.arg_types,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_names=arg_names if arg_names is not _dummy else self.arg_names,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"variables=variables if variables is not _dummy else self.variables,\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if imprecise_arg_kinds is not _dummy\",\n        \"target\": \"mypy.types.Parameters.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 93,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"arg_types\\\": [t.serialize() for t in self.arg_types],\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"arg_types\\\": [t.serialize() for t in self.arg_types],\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"arg_kinds\\\": [int(x.value) for x in self.arg_kinds],\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"arg_kinds\\\": [int(x.value) for x in self.arg_kinds],\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"variables\\\": [tv.serialize() for tv in self.variables],\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"variables\\\": [tv.serialize() for tv in self.variables],\",\n        \"target\": \"mypy.types.Parameters.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"Parameters\\\"\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"arg_types\\\"]],\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"arg_types\\\"]],\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[ArgKind(x) for x in data[\\\"arg_kinds\\\"]],\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[ArgKind(x) for x in data[\\\"arg_kinds\\\"]],\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data[\\\"variables\\\"]],\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data[\\\"variables\\\"]],\",\n        \"target\": \"mypy.types.Parameters.deserialize\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 62,\n        \"src\": \"def __init__(\",\n        \"target\": \"mypy.types.CallableType.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any] | None\\\")\",\n        \"offset\": 53,\n        \"src\": \"if def_extras:\",\n        \"target\": \"mypy.types.CallableType.__init__\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"self.def_extras = def_extras\",\n        \"target\": \"mypy.types.CallableType.__init__\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 22,\n        \"src\": \"def copy_modified(\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"arg_types: Bogus[Sequence[Type]] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_kinds: Bogus[list[ArgKind]] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_names: Bogus[Sequence[str | None]] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ret_type: Bogus[Type] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"fallback: Bogus[Instance] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"name: Bogus[str | None] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"definition: Bogus[SymbolNode] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 54,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"is_ellipsis_args: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"implicit: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"special_sig: Bogus[str | None] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"from_type_type: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"bound_args: Bogus[list[Type | None]] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"def_extras: Bogus[dict[str, Any]] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_guard: Bogus[TypeGuardType | None] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_is: Bogus[Type | None] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"from_concatenate: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"imprecise_arg_kinds: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"unpack_kwargs: Bogus[bool] = _dummy,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"arg_types=arg_types if arg_types is not _dummy else self.arg_types,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"arg_names=arg_names if arg_names is not _dummy else self.arg_names,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ret_type=ret_type if ret_type is not _dummy else self.ret_type,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"fallback=fallback if fallback is not _dummy else self.fallback,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"name=name if name is not _dummy else self.name,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"definition=definition if definition is not _dummy else self.definition,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"variables=variables if variables is not _dummy else self.variables,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"implicit=implicit if implicit is not _dummy else self.implicit,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 58,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"special_sig=special_sig if special_sig is not _dummy else self.special_sig,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"bound_args=bound_args if bound_args is not _dummy else self.bound_args,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 72,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_guard=type_guard if type_guard is not _dummy else self.type_guard,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"type_is=type_is if type_is is not _dummy else self.type_is,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"from_concatenate if from_concatenate is not _dummy else self.from_concatenate\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"if imprecise_arg_kinds is not _dummy\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"unpack_kwargs=unpack_kwargs if unpack_kwargs is not _dummy else self.unpack_kwargs,\",\n        \"target\": \"mypy.types.CallableType.copy_modified\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 301,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"arg_types\\\": [t.serialize() for t in self.arg_types],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"arg_types\\\": [t.serialize() for t in self.arg_types],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"arg_kinds\\\": [int(x.value) for x in self.arg_kinds],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"arg_kinds\\\": [int(x.value) for x in self.arg_kinds],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 6,\n        \"src\": \"\\\"variables\\\": [v.serialize() for v in self.variables],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"variables\\\": [v.serialize() for v in self.variables],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 3,\n        \"src\": \"\\\"bound_args\\\": [(None if t is None else t.serialize()) for t in self.bound_args],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"bound_args\\\": [(None if t is None else t.serialize()) for t in self.bound_args],\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"def_extras\\\": dict(self.def_extras),\",\n        \"target\": \"mypy.types.CallableType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 10,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"CallableType\\\"\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"arg_types\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"arg_types\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[ArgKind(x) for x in data[\\\"arg_kinds\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[ArgKind(x) for x in data[\\\"arg_kinds\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data[\\\"variables\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 62,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data[\\\"variables\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"bound_args=[(None if t is None else deserialize_type(t)) for t in data[\\\"bound_args\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"bound_args=[(None if t is None else deserialize_type(t)) for t in data[\\\"bound_args\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 65,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"bound_args=[(None if t is None else deserialize_type(t)) for t in data[\\\"bound_args\\\"]],\",\n        \"target\": \"mypy.types.CallableType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 81,\n        \"src\": \"return {\\\".class\\\": \\\"Overloaded\\\", \\\"items\\\": [t.serialize() for t in self.items]}\",\n        \"target\": \"mypy.types.Overloaded.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {\\\".class\\\": \\\"Overloaded\\\", \\\"items\\\": [t.serialize() for t in self.items]}\",\n        \"target\": \"mypy.types.Overloaded.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {\\\".class\\\": \\\"Overloaded\\\", \\\"items\\\": [t.serialize() for t in self.items]}\",\n        \"target\": \"mypy.types.Overloaded.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"Overloaded\\\"\",\n        \"target\": \"mypy.types.Overloaded.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return Overloaded([CallableType.deserialize(t) for t in data[\\\"items\\\"]])\",\n        \"target\": \"mypy.types.Overloaded.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return Overloaded([CallableType.deserialize(t) for t in data[\\\"items\\\"]])\",\n        \"target\": \"mypy.types.Overloaded.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 14,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.NamedOverloaded.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"items\\\": [t.serialize() for t in self.items],\",\n        \"target\": \"mypy.types.NamedOverloaded.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"items\\\": [t.serialize() for t in self.items],\",\n        \"target\": \"mypy.types.NamedOverloaded.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"NamedOverloaded\\\"\",\n        \"target\": \"mypy.types.NamedOverloaded.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return NamedOverloaded([CallableType.deserialize(t) for t in data[\\\"items\\\"]], data[\\\"_name\\\"])\",\n        \"target\": \"mypy.types.NamedOverloaded.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return NamedOverloaded([CallableType.deserialize(t) for t in data[\\\"items\\\"]], data[\\\"_name\\\"])\",\n        \"target\": \"mypy.types.NamedOverloaded.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 82,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.TupleType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"items\\\": [t.serialize() for t in self.items],\",\n        \"target\": \"mypy.types.TupleType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"items\\\": [t.serialize() for t in self.items],\",\n        \"target\": \"mypy.types.TupleType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TupleType\\\"\",\n        \"target\": \"mypy.types.TupleType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"items\\\"]],\",\n        \"target\": \"mypy.types.TupleType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"items\\\"]],\",\n        \"target\": \"mypy.types.TupleType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 157,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"items\\\": [[n, t.serialize()] for (n, t) in self.items.items()],\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"items\\\": [[n, t.serialize()] for (n, t) in self.items.items()],\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"items\\\": [[n, t.serialize()] for (n, t) in self.items.items()],\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"required_keys\\\": sorted(self.required_keys),\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"required_keys\\\": sorted(self.required_keys),\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"readonly_keys\\\": sorted(self.readonly_keys),\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"readonly_keys\\\": sorted(self.readonly_keys),\",\n        \"target\": \"mypy.types.TypedDictType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypedDictType\\\"\",\n        \"target\": \"mypy.types.TypedDictType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"{n: deserialize_type(t) for (n, t) in data[\\\"items\\\"]},\",\n        \"target\": \"mypy.types.TypedDictType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{n: deserialize_type(t) for (n, t) in data[\\\"items\\\"]},\",\n        \"target\": \"mypy.types.TypedDictType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"{n: deserialize_type(t) for (n, t) in data[\\\"items\\\"]},\",\n        \"target\": \"mypy.types.TypedDictType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 252,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.LiteralType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"LiteralType\\\"\",\n        \"target\": \"mypy.types.LiteralType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 88,\n        \"src\": \"return {\",\n        \"target\": \"mypy.types.UnionType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 2,\n        \"src\": \"\\\"items\\\": [t.serialize() for t in self.items],\",\n        \"target\": \"mypy.types.UnionType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"items\\\": [t.serialize() for t in self.items],\",\n        \"target\": \"mypy.types.UnionType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"UnionType\\\"\",\n        \"target\": \"mypy.types.UnionType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"items\\\"]],\",\n        \"target\": \"mypy.types.UnionType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[deserialize_type(t) for t in data[\\\"items\\\"]],\",\n        \"target\": \"mypy.types.UnionType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 67,\n        \"src\": \"return {\\\".class\\\": \\\"IntersectionType\\\", \\\"items\\\": [t.serialize() for t in self.items]}\",\n        \"target\": \"mypy.types.IntersectionType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {\\\".class\\\": \\\"IntersectionType\\\", \\\"items\\\": [t.serialize() for t in self.items]}\",\n        \"target\": \"mypy.types.IntersectionType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {\\\".class\\\": \\\"IntersectionType\\\", \\\"items\\\": [t.serialize() for t in self.items]}\",\n        \"target\": \"mypy.types.IntersectionType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"IntersectionType\\\"\",\n        \"target\": \"mypy.types.IntersectionType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return IntersectionType([deserialize_type(t) for t in data[\\\"items\\\"]])\",\n        \"target\": \"mypy.types.IntersectionType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 50,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return IntersectionType([deserialize_type(t) for t in data[\\\"items\\\"]])\",\n        \"target\": \"mypy.types.IntersectionType.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 137,\n        \"src\": \"return {\\\".class\\\": \\\"TypeType\\\", \\\"item\\\": self.item.serialize()}\",\n        \"target\": \"mypy.types.TypeType.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert data[\\\".class\\\"] == \\\"TypeType\\\"\",\n        \"target\": \"mypy.types.TypeType.deserialize\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 68,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 43,\n        \"src\": \"assert False, f\\\"Internal error: unresolved placeholder type {self.fullname}\\\"\",\n        \"target\": \"mypy.types.PlaceholderType.serialize\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 21,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 101,\n        \"src\": \"return f\\\"{t.constructor}({typ})\\\"\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_callable_argument\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 21,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 2,\n        \"src\": \"return f\\\"{t.constructor}({typ}, {t.name})\\\"\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_callable_argument\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 66,\n        \"src\": \"if t.name is None:\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_type_var\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 2,\n        \"src\": \"s = f\\\"`{t.id}\\\"\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_type_var\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 30,\n        \"message\": \"Member \\\"upper_bound\\\" has type \\\"Type\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 13,\n        \"src\": \"if self.id_mapper and t.upper_bound:\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_type_var\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 11,\n        \"src\": \"if t.name is None:\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_param_spec\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 2,\n        \"src\": \"s += f\\\"`{t.id}\\\"\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_param_spec\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always false\",\n        \"offset\": 40,\n        \"src\": \"if t.name is None:\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_type_var_tuple\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 12,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 2,\n        \"src\": \"s = f\\\"`{t.id}\\\"\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_type_var_tuple\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"partial_fallback\\\" has type \\\"Instance\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 127,\n        \"src\": \"if t.partial_fallback and t.partial_fallback.type:\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_tuple_type\"\n      },\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 11,\n        \"message\": \"Member \\\"fallback\\\" has type \\\"Instance\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 23,\n        \"src\": \"if t.fallback and t.fallback.type:\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_typeddict_type\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 30,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 41,\n        \"src\": \"return f\\\"<placeholder {t.fullname}>\\\"\",\n        \"target\": \"mypy.types.TypeStrVisitor.visit_placeholder_type\"\n      }\n    ],\n    \"mypy/types_utils.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 50,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 66,\n        \"src\": \"assert target.alias, f\\\"Unfixed type alias {target.type_ref}\\\"\",\n        \"target\": \"mypy.types_utils.is_invalid_recursive_alias\"\n      }\n    ],\n    \"mypy/util.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 19,\n        \"src\": \"orjson: Any\",\n        \"target\": \"mypy.util\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 356,\n        \"src\": \"members = inspect.getmembers(\",\n        \"target\": \"mypy.util.get_class_descriptors\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, Any)\\\")\",\n        \"offset\": 3,\n        \"src\": \"fields_cache[cls] = [x for x, y in members if x != \\\"__weakref__\\\" and x != \\\"__dict__\\\"]\",\n        \"target\": \"mypy.util.get_class_descriptors\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"fields_cache[cls] = [x for x, y in members if x != \\\"__weakref__\\\" and x != \\\"__dict__\\\"]\",\n        \"target\": \"mypy.util.get_class_descriptors\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[(str, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"fields_cache[cls] = [x for x, y in members if x != \\\"__weakref__\\\" and x != \\\"__dict__\\\"]\",\n        \"target\": \"mypy.util.get_class_descriptors\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 25,\n        \"src\": \"setattr(new, attr, getattr(old, attr))\",\n        \"target\": \"mypy.util.replace_object_state\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 555,\n        \"src\": \"def getattr(value: object, name: str) -> Any: ...\",\n        \"target\": \"mypy.util.getattr\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def (value: object, name: str) -> Any\\\")\",\n        \"offset\": 0,\n        \"src\": \"def getattr(value: object, name: str) -> Any: ...\",\n        \"target\": \"mypy.util.getattr\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-decorated-any for more info\",\n        \"offset\": 0,\n        \"src\": \"def getattr(value: object, name: str) -> Any: ...\",\n        \"target\": null\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def getattr(value: object, name: str, default: T) -> Any | T: ...\",\n        \"target\": \"mypy.util.getattr\"\n      },\n      {\n        \"code\": \"decorated-any\",\n        \"column\": 0,\n        \"message\": \"Type of decorated function contains type \\\"Any\\\" (\\\"def [T] (value: object, name: str, default: T) -> Any | T\\\")\",\n        \"offset\": 0,\n        \"src\": \"def getattr(value: object, name: str, default: T) -> Any | T: ...\",\n        \"target\": \"mypy.util.getattr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"def getattr(value, name, default: object = _default):\",\n        \"target\": \"mypy.util.getattr\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 6,\n        \"src\": \"def attrgetter(name: str) -> operator.attrgetter[Any]:\",\n        \"target\": \"mypy.util.attrgetter\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if orjson is not None:\",\n        \"target\": \"mypy.util.json_dumps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"dumps_option = orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS\",\n        \"target\": \"mypy.util.json_dumps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"dumps_option = orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS\",\n        \"target\": \"mypy.util.json_dumps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"dumps_option = orjson.OPT_SORT_KEYS\",\n        \"target\": \"mypy.util.json_dumps\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"return orjson.dumps(obj, option=dumps_option)  # type: ignore[no-any-return]\",\n        \"target\": \"mypy.util.json_dumps\"\n      },\n      {\n        \"code\": null,\n        \"column\": 19,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"return orjson.dumps(obj, option=dumps_option)  # type: ignore[no-any-return]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return orjson.dumps(obj, option=dumps_option)  # type: ignore[no-any-return]\",\n        \"target\": \"mypy.util.json_dumps\"\n      },\n      {\n        \"code\": null,\n        \"column\": 44,\n        \"message\": \"Error code \\\"any\\\" not covered by \\\"type: ignore\\\" comment\",\n        \"offset\": 0,\n        \"src\": \"return orjson.dumps(obj, option=dumps_option)  # type: ignore[no-any-return]\",\n        \"target\": null\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 12,\n        \"src\": \"def json_loads(data: bytes) -> Any:\",\n        \"target\": \"mypy.util.json_loads\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if orjson is not None:\",\n        \"target\": \"mypy.util.json_loads\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return orjson.loads(data)\",\n        \"target\": \"mypy.util.json_loads\"\n      }\n    ],\n    \"mypy/visitor.py\": [\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 368,\n        \"src\": \"def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_mypy_file\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-empty-body for more info\",\n        \"offset\": 0,\n        \"src\": \"def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T:\",\n        \"target\": null\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 6,\n        \"src\": \"def visit_var(self, o: mypy.nodes.Var, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_var\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 5,\n        \"src\": \"def visit_import(self, o: mypy.nodes.Import, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_import\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_import_from\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_import_all\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 5,\n        \"src\": \"def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_func_def\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_overloaded_func_def\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_class_def\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_global_decl\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_nonlocal_decl\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_decorator\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_type_alias\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_placeholder_node\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 5,\n        \"src\": \"def visit_block(self, o: mypy.nodes.Block, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_block\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_expression_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_assignment_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_operator_assignment_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_while_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_for_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_return_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_assert_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_del_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_if_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_break_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_continue_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_pass_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_raise_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_try_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_with_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_match_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_type_alias_stmt\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 5,\n        \"src\": \"def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_int_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_str_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_bytes_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_float_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_complex_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_ellipsis\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_star_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_name_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_member_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_yield_from_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_yield_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_call_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_op_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_comparison_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_cast_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_assert_type_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_reveal_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_super_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_assignment_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_unary_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_list_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_dict_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_tuple_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_set_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_index_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_type_application\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_lambda_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_list_comprehension\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_set_comprehension\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_dictionary_comprehension\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_generator_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_slice_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_conditional_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_type_var_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_paramspec_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_type_var_tuple_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_type_alias_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_namedtuple_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_enum_call_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_typeddict_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_newtype_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit__promote_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_await_expr\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_temp_node\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 5,\n        \"src\": \"def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_as_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_or_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_value_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_singleton_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_sequence_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_starred_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_mapping_pattern\"\n      },\n      {\n        \"code\": \"empty-body\",\n        \"column\": 4,\n        \"message\": \"Missing return statement\",\n        \"offset\": 3,\n        \"src\": \"def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T:\",\n        \"target\": \"mypy.visitor.NodeVisitor.visit_class_pattern\"\n      }\n    ],\n    \"mypyc/analysis/ircheck.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 32,\n        \"message\": \"The type \\\"mypyc.ir.ops.Op\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 85,\n        \"src\": \"return f\\\"FnError(source={self.source}, desc={self.desc})\\\"\",\n        \"target\": \"mypyc.analysis.ircheck.FnError.__repr__\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 32,\n        \"message\": \"The type \\\"mypyc.ir.ops.BasicBlock\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 0,\n        \"src\": \"return f\\\"FnError(source={self.source}, desc={self.desc})\\\"\",\n        \"target\": \"mypyc.analysis.ircheck.FnError.__repr__\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 72,\n        \"message\": \"The type \\\"type[object]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 186,\n        \"src\": \"self.fail(op, f\\\"Invalid type for item of tuple literal: {type(x)})\\\")\",\n        \"target\": \"mypyc.analysis.ircheck.OpChecker.check_tuple_items_valid_literals\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 76,\n        \"message\": \"The type \\\"type[object]\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 11,\n        \"src\": \"self.fail(op, f\\\"Invalid type for item of frozenset literal: {type(x)})\\\")\",\n        \"target\": \"mypyc.analysis.ircheck.OpChecker.check_frozenset_items_valid_literals\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 21,\n        \"src\": \"elif isinstance(op.value, frozenset):\",\n        \"target\": \"mypyc.analysis.ircheck.OpChecker.visit_load_literal\"\n      }\n    ],\n    \"mypyc/build.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 115,\n        \"src\": \"options.platform,\",\n        \"target\": \"mypyc.build.emit_messages\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 292,\n        \"src\": \"def mypyc_build(\",\n        \"target\": \"mypyc.build.mypyc_build\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 28,\n        \"src\": \"if not skip_cgen_input:\",\n        \"target\": \"mypyc.build.mypyc_build\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"group_cfiles = skip_cgen_input\",\n        \"target\": \"mypyc.build.mypyc_build\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 19,\n        \"src\": \"def mypycify(\",\n        \"target\": \"mypyc.build.mypycify\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 75,\n        \"src\": \"skip_cgen_input=skip_cgen_input,\",\n        \"target\": \"mypyc.build.mypycify\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 9,\n        \"src\": \"compiler: Any = ccompiler.new_compiler()\",\n        \"target\": \"mypyc.build.mypycify\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"sysconfig.customize_compiler(compiler)\",\n        \"target\": \"mypyc.build.mypycify\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"if compiler.compiler_type == \\\"unix\\\":\",\n        \"target\": \"mypyc.build.mypycify\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 9,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 17,\n        \"src\": \"elif compiler.compiler_type == \\\"msvc\\\":\",\n        \"target\": \"mypyc.build.mypycify\"\n      }\n    ],\n    \"mypyc/codegen/emit.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 22,\n        \"message\": \"Name \\\"item_type\\\" may be undefined\",\n        \"offset\": 457,\n        \"src\": \"if isinstance(item_type, RTuple):\",\n        \"target\": \"mypyc.codegen.emit\"\n      }\n    ],\n    \"mypyc/codegen/emitclass.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 44,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 253,\n        \"src\": \"fields[f\\\"tp_{table_name}\\\"] = f\\\"&{table_struct_name}\\\"\",\n        \"target\": \"mypyc.codegen.emitclass.generate_class\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 54,\n        \"message\": \"Name \\\"shadow_vtable_name\\\" may be undefined\",\n        \"offset\": 110,\n        \"src\": \"cl, setup_name, defaults_fn, vtable_name, shadow_vtable_name, emitter\",\n        \"target\": \"mypyc.codegen.emitclass\"\n      }\n    ],\n    \"mypyc/codegen/emitfunc.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 20,\n        \"message\": \"Name \\\"dest\\\" may be undefined\",\n        \"offset\": 453,\n        \"src\": \"dest,\",\n        \"target\": \"mypyc.codegen.emitfunc\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 41,\n        \"message\": \"Name \\\"dest\\\" may be undefined\",\n        \"offset\": 33,\n        \"src\": \"self.emitter.emit_line(f\\\"{dest} = 1;\\\")\",\n        \"target\": \"mypyc.codegen.emitfunc\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 142,\n        \"src\": \"elif isinstance(op.value, Value):\",\n        \"target\": \"mypyc.codegen.emitfunc.FunctionEmitterVisitor.visit_raise_standard_error\"\n      }\n    ],\n    \"mypyc/codegen/emitmodule.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 8,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 154,\n        \"src\": \"ir_data: Any = json.loads(ir_json)\",\n        \"target\": \"mypyc.codegen.emitmodule.MypycPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"if hash_digest(meta_json) != ir_data[\\\"meta_hash\\\"]:\",\n        \"target\": \"mypyc.codegen.emitmodule.MypycPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if hash_digest(meta_json) != ir_data[\\\"meta_hash\\\"]:\",\n        \"target\": \"mypyc.codegen.emitmodule.MypycPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"for path, hash in ir_data[\\\"src_hashes\\\"].items():\",\n        \"target\": \"mypyc.codegen.emitmodule.MypycPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for path, hash in ir_data[\\\"src_hashes\\\"].items():\",\n        \"target\": \"mypyc.codegen.emitmodule.MypycPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"if hash != real_hash:\",\n        \"target\": \"mypyc.codegen.emitmodule.MypycPlugin.report_config_data\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 217,\n        \"src\": \"cache_data = {\",\n        \"target\": \"mypyc.codegen.emitmodule.load_scc_from_cache\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 20,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"k.fullname: cast(\",\n        \"target\": \"mypyc.codegen.emitmodule.load_scc_from_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"k.fullname: cast(\",\n        \"target\": \"mypyc.codegen.emitmodule.load_scc_from_cache\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"modules = deserialize_modules(cache_data, ctx)\",\n        \"target\": \"mypyc.codegen.emitmodule.load_scc_from_cache\"\n      }\n    ],\n    \"mypyc/codegen/literals.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 66,\n        \"src\": \"elif isinstance(value, frozenset):\",\n        \"target\": \"mypyc.codegen.literals.Literals.record_literal\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"See https://kotlinisland.github.io/basedmypy/_refs.html#code-redundant-expr for more info\",\n        \"offset\": 0,\n        \"src\": \"elif isinstance(value, frozenset):\",\n        \"target\": null\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 11,\n        \"message\": \"Condition is always true\",\n        \"offset\": 39,\n        \"src\": \"if isinstance(value, frozenset):\",\n        \"target\": \"mypyc.codegen.literals.Literals.literal_index\"\n      }\n    ],\n    \"mypyc/common.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 35,\n        \"src\": \"SIZEOF_SIZE_T_SYSCONFIG: Final = sysconfig.get_config_var(\\\"SIZEOF_SIZE_T\\\")\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"int(SIZEOF_SIZE_T_SYSCONFIG)\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if SIZEOF_SIZE_T_SYSCONFIG is not None\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"MAX_SHORT_INT: Final = 2 ** (8 * int(SIZEOF_SIZE_T) - 2) - 1\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"MIN_SHORT_INT: Final = -(MAX_SHORT_INT) - 1\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"MIN_SHORT_INT: Final = -(MAX_SHORT_INT) - 1\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"MAX_LITERAL_SHORT_INT: Final = MAX_SHORT_INT\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"MIN_LITERAL_SHORT_INT: Final = -MAX_LITERAL_SHORT_INT - 1\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"MIN_LITERAL_SHORT_INT: Final = -MAX_LITERAL_SHORT_INT - 1\",\n        \"target\": \"mypyc.common\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 29,\n        \"src\": \"JsonDict = dict[str, Any]\",\n        \"target\": \"mypyc.common\"\n      }\n    ],\n    \"mypyc/crash.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 56,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 31,\n        \"src\": \"print(f\\\"{module_path}:{line}: {type(err).__name__}: {err}\\\")\",\n        \"target\": \"mypyc.crash.crash_report\"\n      }\n    ],\n    \"mypyc/ir/class_ir.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 346,\n        \"src\": \"return {\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 17,\n        \"src\": \"\\\"attributes\\\": [(k, t.serialize()) for k, t in self.attributes.items()],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"attributes\\\": [(k, t.serialize()) for k, t in self.attributes.items()],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 3,\n        \"src\": \"\\\"method_decls\\\": [\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"method_decls\\\": [\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 5,\n        \"src\": \"\\\"methods\\\": [(k, m.id) for k, m in self.methods.items()],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"methods\\\": [(k, m.id) for k, m in self.methods.items()],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"glue_methods\\\": [\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"glue_methods\\\": [\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 5,\n        \"src\": \"\\\"property_types\\\": [(k, t.serialize()) for k, t in self.property_types.items()],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"property_types\\\": [(k, t.serialize()) for k, t in self.property_types.items()],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"properties\\\": list(self.properties),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"properties\\\": list(self.properties),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 3,\n        \"src\": \"\\\"trait_vtables\\\": [\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"trait_vtables\\\": [\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 5,\n        \"src\": \"\\\"traits\\\": [cir.fullname for cir in self.traits],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"traits\\\": [cir.fullname for cir in self.traits],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"mro\\\": [cir.fullname for cir in self.mro],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"mro\\\": [cir.fullname for cir in self.mro],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"base_mro\\\": [cir.fullname for cir in self.base_mro],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"base_mro\\\": [cir.fullname for cir in self.base_mro],\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any] | None)\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"children\\\": (\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"[cir.fullname for cir in self.children] if self.children is not None else None\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any] | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"[cir.fullname for cir in self.children] if self.children is not None else None\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 3,\n        \"src\": \"\\\"attrs_with_defaults\\\": sorted(self.attrs_with_defaults),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"attrs_with_defaults\\\": sorted(self.attrs_with_defaults),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"_always_initialized_attrs\\\": sorted(self._always_initialized_attrs),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"_always_initialized_attrs\\\": sorted(self._always_initialized_attrs),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"_sometimes_initialized_attrs\\\": sorted(self._sometimes_initialized_attrs),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"_sometimes_initialized_attrs\\\": sorted(self._sometimes_initialized_attrs),\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"fullname = data[\\\"module_name\\\"] + \\\".\\\" + data[\\\"name\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert fullname in ctx.classes, \\\"Class %s not in deser class map\\\" % fullname\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 76,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert fullname in ctx.classes, \\\"Class %s not in deser class map\\\" % fullname\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir = ctx.classes[fullname]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 15,\n        \"src\": \"ir.attributes = {k: deserialize_type(t, ctx) for k, t in data[\\\"attributes\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.attributes = {k: deserialize_type(t, ctx) for k, t in data[\\\"attributes\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.attributes = {k: deserialize_type(t, ctx) for k, t in data[\\\"attributes\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir.method_decls = {\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 85,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"ir.methods = {k: ctx.functions[v] for k, v in data[\\\"methods\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.methods = {k: ctx.functions[v] for k, v in data[\\\"methods\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 39,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.methods = {k: ctx.functions[v] for k, v in data[\\\"methods\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir.glue_methods = {\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(ClassIR, Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"(ctx.classes[c], k): ctx.functions[v] for (c, k), v in data[\\\"glue_methods\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"(ctx.classes[c], k): ctx.functions[v] for (c, k), v in data[\\\"glue_methods\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"(ctx.classes[c], k): ctx.functions[v] for (c, k), v in data[\\\"glue_methods\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"(ctx.classes[c], k): ctx.functions[v] for (c, k), v in data[\\\"glue_methods\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 28,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"ir.property_types = {k: deserialize_type(t, ctx) for k, t in data[\\\"property_types\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.property_types = {k: deserialize_type(t, ctx) for k, t in data[\\\"property_types\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.property_types = {k: deserialize_type(t, ctx) for k, t in data[\\\"property_types\\\"]}\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir.properties = {\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data[\\\"properties\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data[\\\"properties\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data[\\\"properties\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data[\\\"properties\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"ir.trait_vtables = {\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data[\\\"trait_vtables\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data[\\\"trait_vtables\\\"]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"ir.traits = [ctx.classes[s] for s in data[\\\"traits\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.traits = [ctx.classes[s] for s in data[\\\"traits\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir.mro = [ctx.classes[s] for s in data[\\\"mro\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.mro = [ctx.classes[s] for s in data[\\\"mro\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir.base_mro = [ctx.classes[s] for s in data[\\\"base_mro\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.base_mro = [ctx.classes[s] for s in data[\\\"base_mro\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir.children = data[\\\"children\\\"] and [ctx.classes[s] for s in data[\\\"children\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"ir.children = data[\\\"children\\\"] and [ctx.classes[s] for s in data[\\\"children\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir.children = data[\\\"children\\\"] and [ctx.classes[s] for s in data[\\\"children\\\"]]\",\n        \"target\": \"mypyc.ir.class_ir.ClassIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 25,\n        \"src\": \"return {\",\n        \"target\": \"mypyc.ir.class_ir.serialize_vtable_entry\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 14,\n        \"src\": \"if data[\\\".class\\\"] == \\\"VTableMethod\\\":\",\n        \"target\": \"mypyc.ir.class_ir.deserialize_vtable_entry\"\n      }\n    ],\n    \"mypyc/ir/func_ir.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 48,\n        \"src\": \"return {\",\n        \"target\": \"mypyc.ir.func_ir.RuntimeArg.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 55,\n        \"src\": \"return {\\\"args\\\": [t.serialize() for t in args], \\\"ret_type\\\": self.ret_type.serialize()}\",\n        \"target\": \"mypyc.ir.func_ir.FuncSignature.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {\\\"args\\\": [t.serialize() for t in args], \\\"ret_type\\\": self.ret_type.serialize()}\",\n        \"target\": \"mypyc.ir.func_ir.FuncSignature.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {\\\"args\\\": [t.serialize() for t in args], \\\"ret_type\\\": self.ret_type.serialize()}\",\n        \"target\": \"mypyc.ir.func_ir.FuncSignature.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 5,\n        \"src\": \"[RuntimeArg.deserialize(arg, ctx) for arg in data[\\\"args\\\"]],\",\n        \"target\": \"mypyc.ir.func_ir.FuncSignature.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[RuntimeArg.deserialize(arg, ctx) for arg in data[\\\"args\\\"]],\",\n        \"target\": \"mypyc.ir.func_ir.FuncSignature.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 90,\n        \"src\": \"return {\",\n        \"target\": \"mypyc.ir.func_ir.FuncDecl.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 47,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 16,\n        \"src\": \"shortname = FuncDecl.compute_shortname(decl[\\\"class_name\\\"], decl[\\\"name\\\"])\",\n        \"target\": \"mypyc.ir.func_ir.FuncDecl.get_id_from_json\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 67,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"shortname = FuncDecl.compute_shortname(decl[\\\"class_name\\\"], decl[\\\"name\\\"])\",\n        \"target\": \"mypyc.ir.func_ir.FuncDecl.get_id_from_json\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"fullname = decl[\\\"module_name\\\"] + \\\".\\\" + shortname\",\n        \"target\": \"mypyc.ir.func_ir.FuncDecl.get_id_from_json\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 32,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return get_id_from_name(decl[\\\"name\\\"], fullname, func_ir[\\\"line\\\"])\",\n        \"target\": \"mypyc.ir.func_ir.FuncDecl.get_id_from_json\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return get_id_from_name(decl[\\\"name\\\"], fullname, func_ir[\\\"line\\\"])\",\n        \"target\": \"mypyc.ir.func_ir.FuncDecl.get_id_from_json\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 85,\n        \"src\": \"return {\",\n        \"target\": \"mypyc.ir.func_ir.FuncIR.serialize\"\n      }\n    ],\n    \"mypyc/ir/module_ir.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 35,\n        \"src\": \"return {\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 3,\n        \"src\": \"\\\"functions\\\": [f.serialize() for f in self.functions],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"functions\\\": [f.serialize() for f in self.functions],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"classes\\\": [c.serialize() for c in self.classes],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"classes\\\": [c.serialize() for c in self.classes],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, list[Any])\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"final_names\\\": [(k, t.serialize()) for k, t in self.final_names],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"\\\"final_names\\\": [(k, t.serialize()) for k, t in self.final_names],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"[ctx.functions[FuncDecl.get_id_from_json(f)] for f in data[\\\"functions\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 53,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[ctx.functions[FuncDecl.get_id_from_json(f)] for f in data[\\\"functions\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[ClassIR.deserialize(c, ctx) for c in data[\\\"classes\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 33,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[ClassIR.deserialize(c, ctx) for c in data[\\\"classes\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"[(k, deserialize_type(t, ctx)) for k, t in data[\\\"final_names\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, RType)\\\")\",\n        \"offset\": 0,\n        \"src\": \"[(k, deserialize_type(t, ctx)) for k, t in data[\\\"final_names\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 14,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[(k, deserialize_type(t, ctx)) for k, t in data[\\\"final_names\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"[(k, deserialize_type(t, ctx)) for k, t in data[\\\"final_names\\\"]],\",\n        \"target\": \"mypyc.ir.module_ir.ModuleIR.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 22,\n        \"src\": \"for cls in mod[\\\"classes\\\"]:\",\n        \"target\": \"mypyc.ir.module_ir.deserialize_modules\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 25,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"ir = ClassIR(cls[\\\"name\\\"], cls[\\\"module_name\\\"])\",\n        \"target\": \"mypyc.ir.module_ir.deserialize_modules\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"ir = ClassIR(cls[\\\"name\\\"], cls[\\\"module_name\\\"])\",\n        \"target\": \"mypyc.ir.module_ir.deserialize_modules\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 7,\n        \"src\": \"for method in mod[\\\"functions\\\"]:\",\n        \"target\": \"mypyc.ir.module_ir.deserialize_modules\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"func = FuncIR.deserialize(method, ctx)\",\n        \"target\": \"mypyc.ir.module_ir.deserialize_modules\"\n      }\n    ],\n    \"mypyc/ir/ops.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 50,\n        \"message\": \"The type \\\"mypyc.ir.ops.ControlOp\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 321,\n        \"src\": \"raise AssertionError(f\\\"Invalid set_target({self}, {i})\\\")\",\n        \"target\": \"mypyc.ir.ops.ControlOp.set_target\"\n      }\n    ],\n    \"mypyc/ir/pprint.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 208,\n        \"src\": \"elif isinstance(op.value, Value):\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.visit_raise_standard_error\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always true\",\n        \"offset\": 19,\n        \"src\": \"if arg_type:\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.visit_primitive_op\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 16,\n        \"message\": \"Statement is unreachable\",\n        \"offset\": 4,\n        \"src\": \"assert op.type_args\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.visit_primitive_op\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 81,\n        \"src\": \"def format(self, fmt: str, *args: Any) -> str:\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 14,\n        \"src\": \"arglist = list(args)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"arglist = list(args)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 8,\n        \"src\": \"arg = arglist.pop(0)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"arg = arglist.pop(0)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"assert isinstance(arg, Value)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 9,\n        \"src\": \"result.append(\\\"%d\\\" % arg)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 41,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"result.append(\\\"%f\\\" % arg)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 3,\n        \"src\": \"assert isinstance(arg, BasicBlock)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"assert isinstance(arg, RType)\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"result.append(str(arg))\",\n        \"target\": \"mypyc.ir.pprint.IRPrettyPrintVisitor.format\"\n      }\n    ],\n    \"mypyc/ir/rtypes.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 9,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 101,\n        \"src\": \"elif data[\\\".class\\\"] == \\\"RTuple\\\":\",\n        \"target\": \"mypyc.ir.rtypes.deserialize_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 9,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif data[\\\".class\\\"] == \\\"RUnion\\\":\",\n        \"target\": \"mypyc.ir.rtypes.deserialize_type\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 556,\n        \"src\": \"return {\\\".class\\\": \\\"RTuple\\\", \\\"types\\\": types}\",\n        \"target\": \"mypyc.ir.rtypes.RTuple.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"types = [deserialize_type(t, ctx) for t in data[\\\"types\\\"]]\",\n        \"target\": \"mypyc.ir.rtypes.RTuple.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"types = [deserialize_type(t, ctx) for t in data[\\\"types\\\"]]\",\n        \"target\": \"mypyc.ir.rtypes.RTuple.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 23,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[RType, Any | None]\\\")\",\n        \"offset\": 214,\n        \"src\": \"unique_items = dict.fromkeys(items)\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.make_simplified_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[RType, Any | None]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if len(unique_items) > 1:\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.make_simplified_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[RType, Any | None]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return RUnion(list(unique_items))\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.make_simplified_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[RType, Any | None]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return next(iter(unique_items))\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.make_simplified_union\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 20,\n        \"src\": \"return {\\\".class\\\": \\\"RUnion\\\", \\\"types\\\": types}\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.serialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"types = [deserialize_type(t, ctx) for t in data[\\\"types\\\"]]\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.deserialize\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"types = [deserialize_type(t, ctx) for t in data[\\\"types\\\"]]\",\n        \"target\": \"mypyc.ir.rtypes.RUnion.deserialize\"\n      }\n    ],\n    \"mypyc/irbuild/builder.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 13,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 271,\n        \"src\": \"with self.catch_errors(node.line):\",\n        \"target\": \"mypyc.irbuild.builder.IRBuilder.accept\"\n      },\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 46,\n        \"message\": \"The string for \\\"None\\\" isn't helpful in a user-facing or semantic string\",\n        \"offset\": 303,\n        \"src\": \"error_msg=f'value for final name \\\"{error_name}\\\" was not set',\",\n        \"target\": \"mypyc.irbuild.builder.IRBuilder.load_final_static\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 33,\n        \"src\": \"elif isinstance(val, complex):\",\n        \"target\": \"mypyc.irbuild.builder.IRBuilder.load_literal_value\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 15,\n        \"message\": \"Condition is always true\",\n        \"offset\": 89,\n        \"src\": \"if reg is not None:\",\n        \"target\": \"mypyc.irbuild.builder.IRBuilder.read\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 19,\n        \"message\": \"Name \\\"fullname\\\" may be undefined\",\n        \"offset\": 364,\n        \"src\": \"return fullname, final_var, native\",\n        \"target\": \"mypyc.irbuild.builder\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 40,\n        \"message\": \"Name \\\"native\\\" may be undefined\",\n        \"offset\": 0,\n        \"src\": \"return fullname, final_var, native\",\n        \"target\": \"mypyc.irbuild.builder\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 308,\n        \"src\": \"def catch_errors(self, line: int) -> Any:\",\n        \"target\": \"mypyc.irbuild.builder.IRBuilder.catch_errors\"\n      }\n    ],\n    \"mypyc/irbuild/classdef.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 145,\n        \"src\": \"with builder.catch_errors(stmt.line):\",\n        \"target\": \"mypyc.irbuild.classdef.transform_class_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 8,\n        \"src\": \"with builder.catch_errors(stmt.line):\",\n        \"target\": \"mypyc.irbuild.classdef.transform_class_def\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 23,\n        \"message\": \"Condition is always false\",\n        \"offset\": 399,\n        \"src\": \"if isinstance(typing_extensions.TypedDict, type):\",\n        \"target\": \"mypyc.irbuild.classdef.populate_non_ext_bases\"\n      },\n      {\n        \"code\": \"unreachable\",\n        \"column\": 34,\n        \"message\": \"Intersection of \\\"<typing special form> & type\\\" cannot exist: \\\"_SpecialForm\\\" is final\",\n        \"offset\": 0,\n        \"src\": \"if isinstance(typing_extensions.TypedDict, type):\",\n        \"target\": \"mypyc.irbuild.classdef.populate_non_ext_bases\"\n      }\n    ],\n    \"mypyc/irbuild/env_class.py\": [\n      {\n        \"code\": \"helpful-string\",\n        \"column\": 46,\n        \"message\": \"The type \\\"mypyc.ir.ops.Value\\\" doesn't define a __format__, __str__ or __repr__ method\",\n        \"offset\": 129,\n        \"src\": \"assert isinstance(env.type, RInstance), f\\\"{env} must be of type RInstance\\\"\",\n        \"target\": \"mypyc.irbuild.env_class.load_outer_env\"\n      }\n    ],\n    \"mypyc/irbuild/expression.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 45,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 228,\n        \"src\": \"index = builder.builder.load_int(fields.index(expr.name))\",\n        \"target\": \"mypyc.irbuild.expression.transform_member_expr\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 35,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 399,\n        \"src\": \"end = builder.load_int(MAX_SHORT_INT)\",\n        \"target\": \"mypyc.irbuild.expression.try_gen_slice_op\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 249,\n        \"src\": \"elif isinstance(rhs, Expression):\",\n        \"target\": \"mypyc.irbuild.expression.translate_printf_style_formatting\"\n      }\n    ],\n    \"mypyc/irbuild/for_helpers.py\": [\n      {\n        \"code\": \"truthy-bool\",\n        \"column\": 15,\n        \"message\": \"\\\"value_box\\\" has type \\\"Value\\\" which does not implement __bool__ or __len__ so it could always be true in boolean context\",\n        \"offset\": 754,\n        \"src\": \"assert value_box\",\n        \"target\": \"mypyc.irbuild.for_helpers.ForSequence.begin_body\"\n      }\n    ],\n    \"mypyc/irbuild/function.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 33,\n        \"message\": \"Name \\\"func_ir\\\" may be undefined\",\n        \"offset\": 349,\n        \"src\": \"builder.functions.append(func_ir)\",\n        \"target\": \"mypyc.irbuild.function\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 11,\n        \"message\": \"Name \\\"func_ir\\\" may be undefined\",\n        \"offset\": 5,\n        \"src\": \"return func_ir, func_reg\",\n        \"target\": \"mypyc.irbuild.function\"\n      }\n    ],\n    \"mypyc/irbuild/ll_builder.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 502,\n        \"src\": \"elif is_uint8_rprimitive(target_type):\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.coerce_int_to_fixed_width\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 42,\n        \"src\": \"c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE))\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.coerce_fixed_width_to_int\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 48,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 4,\n        \"src\": \"c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE))\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.coerce_fixed_width_to_int\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 27,\n        \"message\": \"Name \\\"skip\\\" may be undefined\",\n        \"offset\": 311,\n        \"src\": \"assert skip is not out\",\n        \"target\": \"mypyc.irbuild.ll_builder\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 35,\n        \"message\": \"Name \\\"coerced_args\\\" may be undefined\",\n        \"offset\": 90,\n        \"src\": \"self.add(KeepAlive(coerced_args))\",\n        \"target\": \"mypyc.irbuild.ll_builder\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 302,\n        \"src\": \"if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.load_int\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.load_int\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.load_int\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 52,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.load_int\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 870,\n        \"src\": \"elif is_uint8_rprimitive(type):\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.fixed_width_int_op\"\n      },\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 17,\n        \"message\": \"Condition is always true\",\n        \"offset\": 20,\n        \"src\": \"elif is_uint8_rprimitive(type):\",\n        \"target\": \"mypyc.irbuild.ll_builder.LowLevelIRBuilder.fixed_width_int_op\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 36,\n        \"message\": \"Name \\\"false_block\\\" may be undefined\",\n        \"offset\": 194,\n        \"src\": \"self.activate_block(false_block)\",\n        \"target\": \"mypyc.irbuild.ll_builder\"\n      }\n    ],\n    \"mypyc/irbuild/main.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 47,\n        \"src\": \"F = TypeVar(\\\"F\\\", bound=Callable[..., Any])\",\n        \"target\": \"mypyc.irbuild.main\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 22,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 1,\n        \"src\": \"strict_optional_dec = cast(Callable[[F], F], state.strict_optional_set(True))\",\n        \"target\": \"mypyc.irbuild.main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[F: (...) -> Any] (F) -> F\\\")\",\n        \"offset\": 0,\n        \"src\": \"strict_optional_dec = cast(Callable[[F], F], state.strict_optional_set(True))\",\n        \"target\": \"mypyc.irbuild.main\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 1,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[F: (...) -> Any] (F) -> F\\\")\",\n        \"offset\": 3,\n        \"src\": \"@strict_optional_dec  # Turn on strict optional for any type manipulations we do\",\n        \"target\": \"mypyc.irbuild.main\"\n      }\n    ],\n    \"mypyc/irbuild/prepare.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 9,\n        \"message\": \"Condition is always true\",\n        \"offset\": 205,\n        \"src\": \"elif isinstance(node, Decorator):\",\n        \"target\": \"mypyc.irbuild.prepare.prepare_method_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 72,\n        \"src\": \"attrs = get_mypyc_attrs(cdef)\",\n        \"target\": \"mypyc.irbuild.prepare.prepare_class_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"if attrs.get(\\\"allow_interpreted_subclasses\\\") is True:\",\n        \"target\": \"mypyc.irbuild.prepare.prepare_class_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if attrs.get(\\\"allow_interpreted_subclasses\\\") is True:\",\n        \"target\": \"mypyc.irbuild.prepare.prepare_class_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"if attrs.get(\\\"serializable\\\") is True:\",\n        \"target\": \"mypyc.irbuild.prepare.prepare_class_def\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | None\\\")\",\n        \"offset\": 0,\n        \"src\": \"if attrs.get(\\\"serializable\\\") is True:\",\n        \"target\": \"mypyc.irbuild.prepare.prepare_class_def\"\n      }\n    ],\n    \"mypyc/irbuild/statement.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 7,\n        \"message\": \"Name \\\"next_block\\\" may be undefined\",\n        \"offset\": 516,\n        \"src\": \"if next_block:\",\n        \"target\": \"mypyc.irbuild.statement\"\n      }\n    ],\n    \"mypyc/irbuild/util.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 86,\n        \"src\": \"def get_mypyc_attr_literal(e: Expression) -> Any:\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attr_literal\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 26,\n        \"src\": \"def get_mypyc_attrs(stmt: ClassDef | Decorator) -> dict[str, Any]:\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attrs\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"attrs: dict[str, Any] = {}\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attrs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 24,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 7,\n        \"src\": \"attrs[arg.value] = True\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attrs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"attrs[name] = get_mypyc_attr_literal(arg)\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attrs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"attrs[name] = get_mypyc_attr_literal(arg)\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attrs\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"return attrs\",\n        \"target\": \"mypyc.irbuild.util.get_mypyc_attrs\"\n      }\n    ],\n    \"mypyc/subtype.py\": [\n      {\n        \"code\": \"redundant-expr\",\n        \"column\": 13,\n        \"message\": \"Condition is always true\",\n        \"offset\": 67,\n        \"src\": \"elif is_fixed_width_rtype(left):\",\n        \"target\": \"mypyc.subtype.SubtypeVisitor.visit_rprimitive\"\n      }\n    ],\n    \"mypyc/test/test_exceptions.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 57,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"list[Any]\\\")\",\n        \"offset\": 54,\n        \"src\": \"actual.append(\\\"hot blocks: %s\\\" % sorted(b.label for b in common))\",\n        \"target\": \"mypyc.test.test_exceptions.TestExceptionTransform.run_case\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 63,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Generator[Any, None, None]\\\")\",\n        \"offset\": 0,\n        \"src\": \"actual.append(\\\"hot blocks: %s\\\" % sorted(b.label for b in common))\",\n        \"target\": \"mypyc.test.test_exceptions.TestExceptionTransform.run_case\"\n      }\n    ],\n    \"mypyc/test/test_external.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 5,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"[_FT: (...) -> Any] (_FT) -> _FT\\\")\",\n        \"offset\": 17,\n        \"src\": \"@unittest.skipIf(sys.platform.startswith(\\\"win\\\"), \\\"rt tests don't work on windows\\\")\",\n        \"target\": \"mypyc.test.test_external\"\n      }\n    ],\n    \"mypyc/test/test_run.py\": [\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 194,\n        \"src\": \"bench = testcase.config.getoption(\\\"--bench\\\", False) and \\\"Benchmark\\\" in testcase.name\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any (unannotated) | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"bench = testcase.config.getoption(\\\"--bench\\\", False) and \\\"Benchmark\\\" in testcase.name\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 45,\n        \"src\": \"self.get_separate(\\\"\\\\n\\\".join(testcase.input), incremental_step)\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"self.get_separate(\\\"\\\\n\\\".join(testcase.input), incremental_step)\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 5,\n        \"src\": \"groups = construct_groups(sources, separate, len(module_names) > 1)\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 40,\n        \"src\": \"module_paths, separate, cfiles, self.multi_file, opt_level, debug_level\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 5,\n        \"src\": \"if testcase.config.getoption(\\\"--mypyc-showc\\\"):\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 40,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any (unannotated) | bool\\\")\",\n        \"offset\": 17,\n        \"src\": \"env[\\\"MYPYC_RUN_BENCH\\\"] = \\\"1\\\" if bench else \\\"0\\\"\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"no-untyped-usage\",\n        \"column\": 8,\n        \"message\": \"Usage of untyped name \\\"debugger\\\" in typed context\",\n        \"offset\": 2,\n        \"src\": \"debugger = testcase.config.getoption(\\\"debugger\\\")\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 0,\n        \"src\": \"debugger = testcase.config.getoption(\\\"debugger\\\")\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 1,\n        \"src\": \"if debugger:\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 1,\n        \"src\": \"if debugger == \\\"lldb\\\":\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any (unannotated)\\\"\",\n        \"offset\": 0,\n        \"src\": \"if debugger == \\\"lldb\\\":\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 2,\n        \"src\": \"elif debugger == \\\"gdb\\\":\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 17,\n        \"message\": \"Expression has type \\\"Any (unannotated)\\\"\",\n        \"offset\": 0,\n        \"src\": \"elif debugger == \\\"gdb\\\":\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 23,\n        \"src\": \"if testcase.config.getoption(\\\"--mypyc-showc\\\"):\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 2,\n        \"src\": \"if proc.returncode != 0:\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 21,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 2,\n        \"src\": \"signal = proc.returncode == -11\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 2,\n        \"src\": \"if signal:\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 3,\n        \"src\": \"if signal and not sys.platform.startswith(\\\"win\\\"):\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any | bool\\\")\",\n        \"offset\": 0,\n        \"src\": \"if signal and not sys.platform.startswith(\\\"win\\\"):\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"no-untyped-usage\",\n        \"column\": 20,\n        \"message\": \"Usage of untyped name \\\"debugger\\\" in typed context\",\n        \"offset\": 5,\n        \"src\": \"debugger = \\\"gdb\\\"\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 2,\n        \"src\": \"f'hint: Use \\\"pytest -n0 -s --mypyc-debug={debugger} -k <name-substring>\\\" to run test in debugger'\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"Any (unannotated) | bool\\\")\",\n        \"offset\": 7,\n        \"src\": \"if bench:\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"bool | Any\\\")\",\n        \"offset\": 32,\n        \"src\": \"assert proc.returncode == 0\",\n        \"target\": \"mypyc.test.test_run.TestRun.run_case_step\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 4,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 2,\n        \"src\": \"def get_separate(self, program_text: str, incremental_step: int) -> Any:\",\n        \"target\": \"mypyc.test.test_run.TestRun.get_separate\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 19,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 6,\n        \"src\": \"return ast.literal_eval(safe(m.group(1)))\",\n        \"target\": \"mypyc.test.test_run.TestRun.get_separate\"\n      }\n    ],\n    \"mypyc/test/test_serialization.py\": [\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 19,\n        \"src\": \"def get_dict(x: Any) -> dict[str, Any]:\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if hasattr(x, \\\"__mypyc_attrs__\\\"):\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 30,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 71,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 74,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"return dict(x.__dict__)\",\n        \"target\": \"mypyc.test.test_serialization.get_dict\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def get_function_dict(x: FuncIR) -> dict[str, Any]:\",\n        \"target\": \"mypyc.test.test_serialization.get_function_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"d = get_dict(x)\",\n        \"target\": \"mypyc.test.test_serialization.get_function_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"d.pop(\\\"blocks\\\", None)\",\n        \"target\": \"mypyc.test.test_serialization.get_function_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 4,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"d.pop(\\\"env\\\", None)\",\n        \"target\": \"mypyc.test.test_serialization.get_function_dict\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 1,\n        \"src\": \"return d\",\n        \"target\": \"mypyc.test.test_serialization.get_function_dict\"\n      },\n      {\n        \"code\": \"explicit-any\",\n        \"column\": 0,\n        \"message\": \"Explicit \\\"Any\\\" is not allowed\",\n        \"offset\": 3,\n        \"src\": \"def assert_blobs_same(x: Any, y: Any, trail: tuple[Any, ...]) -> None:\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 11,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 16,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 16,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 22,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(str, type[Any], type[Any])\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 51,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 61,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 70,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"type[Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 75,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert type(x) is type(y), (f\\\"Type mismatch at {trail}\\\", type(x), type(y))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 18,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"if isinstance(x, (FuncDecl, FuncIR, ClassIR)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert x.fullname == y.fullname, f\\\"Name mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 29,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert x.fullname == y.fullname, f\\\"Name mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 60,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert x.fullname == y.fullname, f\\\"Name mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(x, dict):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert len(x.keys()) == len(y.keys()), f\\\"Keys mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 66,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert len(x.keys()) == len(y.keys()), f\\\"Keys mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"((Any, Any), Any)\\\")\",\n        \"offset\": 1,\n        \"src\": \"for (xk, xv), (yk, yv) in zip(x.items(), y.items()):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for (xk, xv), (yk, yv) in zip(x.items(), y.items()):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[((Any, Any), Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for (xk, xv), (yk, yv) in zip(x.items(), y.items()):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 49,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for (xk, xv), (yk, yv) in zip(x.items(), y.items()):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert_blobs_same(xk, yk, trail + (\\\"keys\\\",))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert_blobs_same(xk, yk, trail + (\\\"keys\\\",))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert_blobs_same(xv, yv, trail + (xk,))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert_blobs_same(xv, yv, trail + (xk,))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(x, dict):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert x.keys() == y.keys(), f\\\"Keys mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert x.keys() == y.keys(), f\\\"Keys mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 56,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert x.keys() == y.keys(), f\\\"Keys mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"assert_blobs_same(x[k], y[k], trail + (k,))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert_blobs_same(x[k], y[k], trail + (k,))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(x, Iterable) and not isinstance(x, (str, set)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(int, (Any, Any))\\\")\",\n        \"offset\": 4,\n        \"src\": \"for i, (xv, yv) in enumerate(zip(x, y)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"(Any, Any)\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (xv, yv) in enumerate(zip(x, y)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 8,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for i, (xv, yv) in enumerate(zip(x, y)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 27,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"enumerate[(Any, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (xv, yv) in enumerate(zip(x, y)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"zip[(Any, Any)]\\\")\",\n        \"offset\": 0,\n        \"src\": \"for i, (xv, yv) in enumerate(zip(x, y)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 44,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"for i, (xv, yv) in enumerate(zip(x, y)):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 34,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert_blobs_same(xv, yv, trail + (i,))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 38,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert_blobs_same(xv, yv, trail + (i,))\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(x, RType):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 31,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert is_same_type(x, y), f\\\"RType mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 55,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert is_same_type(x, y), f\\\"RType mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"elif isinstance(x, FuncSignature):\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 1,\n        \"src\": \"assert is_same_signature(x, y), f\\\"Signature mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 64,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert is_same_signature(x, y), f\\\"Signature mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 15,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 2,\n        \"src\": \"assert x == y, f\\\"Value mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 20,\n        \"message\": \"Expression has type \\\"Any\\\"\",\n        \"offset\": 0,\n        \"src\": \"assert x == y, f\\\"Value mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 43,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"tuple[Any, ...]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert x == y, f\\\"Value mismatch at {trail}\\\"\",\n        \"target\": \"mypyc.test.test_serialization.assert_blobs_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 15,\n        \"src\": \"assert_blobs_same(get_dict(cls1), get_dict(cls2), (ir1.fullname, cls1.fullname))\",\n        \"target\": \"mypyc.test.test_serialization.assert_modules_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 42,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert_blobs_same(get_dict(cls1), get_dict(cls2), (ir1.fullname, cls1.fullname))\",\n        \"target\": \"mypyc.test.test_serialization.assert_modules_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 12,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 4,\n        \"src\": \"get_function_dict(fn1), get_function_dict(fn2), (ir1.fullname, fn1.fullname)\",\n        \"target\": \"mypyc.test.test_serialization.assert_modules_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 36,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"get_function_dict(fn1), get_function_dict(fn2), (ir1.fullname, fn1.fullname)\",\n        \"target\": \"mypyc.test.test_serialization.assert_modules_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 26,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 2,\n        \"src\": \"assert_blobs_same(get_dict(fn1.decl), get_dict(fn2.decl), (ir1.fullname, fn1.fullname))\",\n        \"target\": \"mypyc.test.test_serialization.assert_modules_same\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 46,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"dict[str, Any]\\\")\",\n        \"offset\": 0,\n        \"src\": \"assert_blobs_same(get_dict(fn1.decl), get_dict(fn2.decl), (ir1.fullname, fn1.fullname))\",\n        \"target\": \"mypyc.test.test_serialization.assert_modules_same\"\n      }\n    ],\n    \"mypyc/test/testutil.py\": [\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 11,\n        \"message\": \"Name \\\"default_builtins\\\" may be undefined\",\n        \"offset\": 67,\n        \"src\": \"if default_builtins:\",\n        \"target\": \"mypyc.test.testutil\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 22,\n        \"message\": \"Name \\\"builtins\\\" may be undefined\",\n        \"offset\": 2,\n        \"src\": \"os.remove(builtins)\",\n        \"target\": \"mypyc.test.testutil\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 7,\n        \"message\": \"Name \\\"default_builtins\\\" may be undefined\",\n        \"offset\": 19,\n        \"src\": \"if default_builtins:\",\n        \"target\": \"mypyc.test.testutil\"\n      },\n      {\n        \"code\": \"possibly-undefined\",\n        \"column\": 18,\n        \"message\": \"Name \\\"builtins\\\" may be undefined\",\n        \"offset\": 2,\n        \"src\": \"os.remove(builtins)\",\n        \"target\": \"mypyc.test.testutil\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 7,\n        \"message\": \"Expression type contains \\\"Any\\\" (has type \\\"False | Untyped\\\")\",\n        \"offset\": 96,\n        \"src\": \"if expected_output != actual and testcase.config.getoption(\\\"--update-data\\\", False):\",\n        \"target\": \"mypyc.test.testutil.assert_test_output\"\n      },\n      {\n        \"code\": \"any\",\n        \"column\": 37,\n        \"message\": \"Expression has type \\\"Untyped\\\"\",\n        \"offset\": 0,\n        \"src\": \"if expected_output != actual and testcase.config.getoption(\\\"--update-data\\\", False):\",\n        \"target\": \"mypyc.test.testutil.assert_test_output\"\n      }\n    ]\n  },\n  \"format\": \"1.7\",\n  \"targets\": [\n    \"package:mypy\",\n    \"package:mypyc\"\n  ]\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        exclude: \"^.mypy/baseline.json$|^.idea/\"\n  - repo: https://github.com/psf/black-pre-commit-mirror\n    rev: 24.10.0\n    hooks:\n      - id: black\n        exclude: '^(test-data/)'\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.8.6\n    hooks:\n      - id: ruff\n        args: [--exit-non-zero-on-fix]\n  - repo: https://github.com/python-jsonschema/check-jsonschema\n    rev: 0.31.0\n    hooks:\n      - id: check-github-workflows\n      - id: check-github-actions\n      - id: check-readthedocs\n  - repo: https://github.com/rhysd/actionlint\n    rev: v1.7.6\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.10.0\"\n  - repo: https://github.com/woodruffw/zizmor-pre-commit\n    rev: v1.0.1\n    hooks:\n      - id: zizmor\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": "# Basedmypy Changelog\n\n## [Unreleased]\n### Changes\n- don't error on missing arguments on `types.FunctionType` and `types.BuiltinFunctionType`\n### Fixed\n- allow `@final` decorator on `Protocol` classes with abstract attributes (#867)\n\n## [2.10.0]\n### Changes\n- codes for `Any` related errors haves been adjusted\n\n## [2.9.1]\n### Fixed\n- definition of `functools.cache` and `operator.attrgetter`\n\n## [2.9.0]\n### Added\n- `collections.User*` should have `__repr__`\n### Fixed\n- cache modules that only have baseline errors\n\n## [2.8.1]\n### Fixes\n- `stubtest`: the `__bool__` method of function parameter defaults will no longer be unnecessarily evaluated\n\n## [2.8.0]\n### Added\n- ban variance on  `TypeVar` definitions (#817)\n- enforce `TypeVar` constraints on type applications (#817)\n### Fixes\n- check type args on type aliases (#817)\n- cache modules that only have baseline errors\n- fix dmypy in vscode\n- fix `typing.Callable`\n### Docs\n- correct error code documentation regarding defaults\n\n## [2.7.0]\n### Added\n- typed `functools.wraps` correctly\n- typed `builtins.ellipsis`/`types.EllipsisType` correctly\n- disable `bytearray` and `memoryview` promotions by default\n- support `typing.type_check_only`\n- support default values on type parameters\n- support based type notation in type alias statements\n- support `basedtyping.FunctionType`\n### Fixes\n- fixed crash with `re` plugin\n- fixed crash with `Intersection` cache\n- fixed definition of `types.NoneType`\n### Enhancements\n- fixed default configuration in the docs\n\n## [2.6.0]\n### Added\n- Any parameter `_` will be inferred as `object` (#687)\n- `work_not_properly_function_names` made available to per module configuration (#699)\n- Support `BASEDMYPY_TYPE_CHECKING` (#702)\n- Enable stub mode within `TYPE_CHECKING` branches (#702)\n- Infer from overloads - add default value in impl (#697)\n- Warn for missing returns with explicit `Any` return types (#715)\n### Fixes\n- positional arguments on overloads break super (#697)\n- positional arguments on overloads duplicate unions (#697)\n- fix intersection type aliases (#716)\n\n## [2.5.0]\n### Added\n- `Callable` syntax (`(int) -> str`) (#619)\n- `FunctionType` syntax (`def (int) -> str`) (#619)\n### Fixes\n- `Callable` is no longer `types.FunctionType` (#619)\n\n## [2.4.0]\n\n## [2.3.0]\n### Added\n- f-string format specs are checked (#543)\n- Narrow type on initial assignment (#547)\n- Annotations in function bodies are not analyzed as evaluated (#564)\n- Invalid `cast`s show an error (#573)\n- Argument names are validated for subtypes (#562)\n- Type-guards narrow in the negative (#553)\n- Conditional types for asymmetric type-guards (#553)\n- Static conditions report an error (#553)\n- Regex groups are special-cased (#531)\n- f-strings will show an error if the value doesn't define a stringification (#565)\n### Enhancements\n- Show 'narrowed from' in `reveal_type` (#550)\n- `--color-output` is enabled by default (#531)\n- `--ide` will disable color-output (#531)\n- Output lines won't wrap if not connected to a terminal (#531)\n### Fixes\n- Render star args in error messages properly (#551)\n- The first argument to `cast` is analyzed as evaluated (#564)\n- Decorated functions that return `None` correctly warn when used (#572)\n- Some impossible type-guards were not reporting an error (#553)\n\n## [2.2.1]\n### Fixes\n- explicit-override is re-enabled by default\n\n## [2.2.0]\n### Added\n- type-guards have been reworked from the ground up (#516)\n- `TypeGuard` is retained in inferred types (#504)\n- Type narrowing is applied from lambda execution (#504)\n- `--ide` flag (#501)\n### Enhancements\n- `show-error-context`/`pretty` are now on by default (#501)\n- Show fake column number when `--show-error-end` (#501)\n- Error messages point to basedmypy docs (#516)\n- `Callable` types in error messages don't contain `mypy_extensions` (#516)\n### Fixes\n- Don't show \"X defined here\" when error context is hidden (#498)\n- Fix issue with reveal code in ignore message (#490)\n- Fixed union at join for same `type` literals. (#488)\n- Don't report false `Any` expressions when inferring lambda type (#515)\n- Correctly match overload when it contains an `Any` expression (#515)\n- Fixed the variance of `Mapping`s key type (#527)\n\n## [2.1.0]\n\n## [2.0.0]\n### Added\n- Deprecate python 3.7 support (#457)\n- Allow denotation of tuple types with tuple literals (#458)\n- Removed `--legacy` flag in favour of `--no-strict` (#445)\n- `default-return` is now enabled by default (#445)\n### Enhancements\n- Removed `Any` from the typings for `re.Match` group functions. (#459)\n- Ignore `Any` from unused `__init__`. (#321)\n### Fixes\n- Fix unsafe variance note (#452)\n- Fix crash with baseline filtering (#471)\n\n## [1.8.0]\n### Added\n- `Intersection` type (#357)\n\n## [1.7.0]\n### Added\n- `ignore-missing-py-typed` to use types even if there is no `py.typed` (#337)\n### Fixes\n- Errors regarding inferred functions didn't have a note (#394)\n- Type ignored calls to incomplete functions left a phantom note (#395)\n- Fix incorrect plural in summary message (#386)\n### Enhancements\n- Baseline now stores the source code for better matching (#415)\n- Duplicates are no longer stored in the baseline (#231)\n\n## [1.6.0]\n### Added\n- Support using `TypeVar`s in the bounds of other `TypeVar`s\n### Enhancements\n- Similar errors on the same line will now not be removed\n- Render generic upper bound with `: ` instead of ` <: `\n- Render uninhabited type as `Never` instead of `<nothing>`\n- Render Callables with `-> None`\n### Fixes\n- Handle positional only `/` parameters in overload implementation inference\n- Render inferred literal without `?`\n- Fix infer from defaults for inner functions\n\n## [1.5.0]\n### Added\n- Allow literal `int`, `bool` and `Enum`s without `Literal`\n### Enhancements\n- Unionize at type joins instead of common ancestor\n- Render Literal types better in output messages\n\n## [1.4.0]\n### Added\n- `ignore_any_from_errors` option to suppress `no-any-expr` messages from other errors\n- Function types are inferred from Overloads, overrides and default values. (no overrides for now sorry)\n- Infer Property types\n- Calls to incomplete functions are an error (configurable with `incomplete_is_typed`)\n- Added a new type `Untyped`, it's like `Any`, but more specific\n- Added a dependency on `basedtyping`\n### Enhancements\n- Render types a lot better in output messages\n### Fixes\n- `types.NoneType` now works as a value of `type[None]`\n\n## [1.3.0]\n### Added\n- `default_return` option to imply unannotated return type as `None`.\n- Specific error codes for `Any` errors\n- Automatic baseline mode, if there are no new errors then write.\n- Ignore baseline with `mypy --baseline-file= src`\n### Enhancements\n- Baseline will ignore reveals (`reveal_type` and `reveal_locals`).\n- `--write-baseline` will report total and new errors.\n- Much better baseline matching.\n\n## [1.2.0]\n### Added\n- Unions in output messages show with new syntax\n- `--legacy` flag\n- new baseline format\n\n## [1.0.0]\n### Added\n- Strict by default(`--strict` and disable dynamic typing)\n- add baseline support(`--write-baseline`, `--baseline-file`)\n- Type ignore must specify error code\n- Unused type ignore can be ignored\n- Add error code for unsafe variance(`unsafe-variance`)\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Mypy\n\nwelcome! basedmypy is a community project that aims to work for a wide\nrange of Python users and Python codebases. If you're trying basedmypy on\nyour Python code, your experience and what you can contribute are\nimportant to the project's success\n\n## Getting started with development\n\n### Setup\n\n#### (1) Fork the mypy repository\n\nWithin GitHub, navigate to <https://github.com/KotlinIsland/basedmypy> and fork the repository.\n\n#### (2) Clone the mypy repository and enter into it\n\nclone the project using your IDE\n\nif you don't use an IDE, you can also use the terminal (not recommended, the terminal is better left in the 80's):\n```shell\ngit clone https://github.com/<your_username>/basedmypy.git\ncd basedmypy\n```\n\n#### (3) Setup the project\n\n```shell\n./pw install\n```\n\n> [!Note]\n> You'll need Python 3.9 or higher to install all requirements\n> you can specify the version:\n>\n> ```shell\n> ./pw install --python 3.13\n> ```\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```shell\n# Use mypy to check mypy's own code\n.\\pw typecheck\n\n# Run a single test from the test suite\n.\\pw test test_name\n\n# Run all test cases in the \"test-data/unit/check-dataclasses.test\" file\npytest mypy/test/testcheck.py::TypeCheckSuite::check-dataclasses.test\n\n# Run the formatters and linters\n.\\pw format\n.\\pw 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## First time contributors\n\nIf you're looking for things to help with, browse our [issue tracker](https://github.com/KotlinIsland/basedmypy/issues)!\n\nIn particular, look for [good first issues](https://github.com/KotlinIsland/basedmypy/labels/good-first-issue)\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\nWe would like to thank the core basedmypy team:\n\n  KotlinIsland\n  DetachHead\n  PixieRa\n  Jorenham\n\nMypy 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  Ethan Smith\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"
  },
  {
    "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 pytest.ini\ninclude tox.ini\n\ninclude LICENSE mypyc/README.md CHANGELOG.md\nexclude .gitmodules CONTRIBUTING.md CREDITS ROADMAP.md action.yml .editorconfig\nexclude mypy_self_check_strict.ini .mypy/baseline.json\nexclude .git-blame-ignore-revs .pre-commit-config.yaml\n\nglobal-exclude *.py[cod]\nglobal-exclude .DS_Store\n\n# some random stuff\ninclude pw.bat\ninclude pw.lock\ninclude pw\nexclude .idea/watcherTasks.xml\nexclude .vscode/extensions.json\nexclude .vscode/launch.json\nexclude .vscode/settings.json\nexclude .vscode/tasks.json\n"
  },
  {
    "path": "README.md",
    "content": "> [!IMPORTANT]\n> **deprecated**: basedmypy is no longer maintained\n>\n> as of July 2025, this project is deprecated. basedmypy was intended to push the ecosystem forward from mypy, and there are now great alternatives that exist\n>\n> - basedpyright: https://github.com/DetachHead/basedpyright\n> - ty: https://github.com/astral-sh/ty\n>\n> we recommend migrating to one of the above projects for ongoing improvements and support. thank you to everyone who used, contributed to, and supported basedmypy ❤️\n\n[![Discord](https://img.shields.io/discord/948915247073349673?logo=discord)](https://discord.gg/7y9upqPrk2)\n[![Playground](https://img.shields.io/badge/🛝%20playground-blue)](https://mypy-play.net/?mypy=basedmypy-latest)\n[![Stable Version](https://img.shields.io/pypi/v/basedmypy?color=blue)](https://pypi.org/project/basedmypy/)\n[![Downloads](https://img.shields.io/pypi/dm/basedmypy)](https://pypistats.org/packages/basedmypy)\n[![Documentation](https://img.shields.io/badge/📚%20docs-blue)](https://KotlinIsland.github.io/basedmypy)\n[![Checked with basedmypy](https://img.shields.io/badge/basedmypy-checked-brightgreen?labelColor=orange)](https://github.com/KotlinIsland/basedmypy)\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\n<!-- can't use a <picture> because it doesn't work in the app -->\n\n![Amon Gus.](/docs/static/logo-dark.png#gh-dark-mode-only)\n![Amon Gus.](/docs/static/logo-light.png#gh-light-mode-only)\n\n# Based Static Typing for Python\n\nBasedmypy is a Python type checker that is built on top of the work done by the\n[mypy project](https://github.com/python/mypy). It resolves fundamental issues, limitations and compromises\nthat exist within Mypy and Python's type system.\n\nBased features include:\n\n- Typesafe by default (optional and dynamic typing still supported)\n- Baseline functionality\n- Support for `Intersection` types\n- Default return type of `None` instead of `Any`\n- Generic `TypeVar` bounds\n- Based type-guards\n- Infer parameter type from default value\n- Infer overload types\n- Bare literals\n- Tuple literal types\n\nSee the [the docs](https://kotlinisland.github.io/basedmypy/based_features.html) for a comprehensive list.\n\n\n### BasedPyright\n\nAlso, take a look at [BasedPyright](https://github.com/DetachHead/basedpyright), a based type checker and language server based on Pyright!\n\n## Usage\n\nBasedmypy is installed as an alternative to, and in place of, the `mypy` installation:\n\n    mypy test.py\n\n    python -m mypy test.py\n\n\n## Why?\n\nbasedmypy was created to attempt to resolve two issues within Python and Mypy's typing ecosystem\nand to demonstrate new typing concepts:\n\n1. Mypy is lacking numerous pieces of functionality\n2. Pythons type system is full of deeply concerning compromises\n\nYou can find a comprehensive list of features in [the docs](https://kotlinisland.github.io/basedmypy/based_features.html).\n\n\n## Integrations\n\nIf you are using vscode, we recommend the [mypy extension](https://marketplace.visualstudio.com/items?itemName=ms-python.mypy-type-checker)\n\nIf you are using IntelliJ IDEA/PyCharm, we recommend the [basedtyping plugin](https://plugins.jetbrains.com/plugin/23374-basedtyping)\n\nIf you are using [Pydantic](https://github.com/pydantic/pydantic), we recommend [pydantic-basedtyping](https://github.com/KotlinIsland/pydantic-basedtyping)\n\n\n### Baseline\n\nBasedmypy supports a feature called baseline. It allows you to adopt new strictness or features\nwithout the burden of refactoring and fixing every new error, just save all current errors to the baseline\nfile and resolve them at what ever pace you want. Only new code will report new errors.\n\nRead more and see examples in [the docs](https://KotlinIsland.github.io/basedmypy/baseline)\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://kotlinisland.github.io/basedmypy.\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": "sphinx>=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 attr\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/based_features.rst",
    "content": ".. _based_features:\n\nBased Features\n==============\n\n\nIntersection Types\n------------------\n\nUsing the ``&`` operator or ``basedtyping.Intersection`` you can denote intersection types:\n\n.. code-block:: python\n\n    class Growable(ABC, Generic[T]):\n        @abstractmethod\n        def add(self, item: T): ...\n\n\n    class Resettable(ABC):\n        @abstractmethod\n        def reset(self): ...\n\n\n    def f(x: Resettable & Growable[str]):\n        x.reset()\n        x.add(\"first\")\n\nType Joins\n----------\n\nMypy joins types to their common base type:\n\n.. code-block:: python\n\n    a: int\n    b: str\n    reveal_type(a if bool() else b)  # Revealed type is \"builtins.object\"\n\nBasedmypy joins types into unions instead:\n\n.. code-block:: python\n\n    a: int\n    b: str\n    reveal_type(a if bool() else b)  # Revealed type is \"int | str\"\n\n\nBased Callable\n--------------\n\nBasedmypy supports callable and function syntax types:\n\n.. code-block:: python\n\n    a: \"(int) -> str\" = lambda x: str(x)  # Callable\n    b: \"def (int) -> str\" = lambda x: str(x)  # FunctionType\n\nIn mypy, all ``Callable``\\s are assumed to be functions (``FunctionType``/``builtins.function``), but this is not the case for instances that have a `__call__` method.\n\nBasedmypy corrects this by separating `Callable` and `FunctionType`:\n\n.. code-block:: python\n\n    class A:\n        def __call__(self, i: int) -> str: ...\n    a: \"(int) -> str\" = A()\n    a.__name__  # error: \"() -> int\" has no attribute \"__name__\"  [attr-defined]\n    b: \"def (int) -> str\" = lambda i: \"\"\n    b.__name__  # okay: `FunctionType` has a `__name__` attribute\n\nBasedmypy warns against unsafe and ambiguous assignments of callables on classes:\n\n.. code-block:: python\n\n    class A:\n        a: \"() -> int\" = lambda: 10  # error: Don't assign a \"FunctionType\" via the class, it will become a \"MethodType\"\n\n\nAdditionally, a ``Protocol`` ``_NamedCallable`` is introduced to represent the union of all 'named' callable implementations:\n\n.. code-block:: python\n\n    class A:\n        def f(self): ...\n\n    reveal_type(A.f)  # \"def (self: A) -> None\"\n    reveal_type(A().f)  # \"_NamedCallable & () -> None\"\n\nBare Literals\n-------------\n\n``Literal`` is so cumbersome! Just use a bare literal instead:\n\n.. code-block:: python\n\n    class Color(Enum):\n        RED = auto()\n\n    a: 1 | 2\n    b: True | Color.RED\n\n\nDefault Return Type\n-------------------\n\nThe default return type of functions is ``None`` instead of ``Any``:\n(configurable with the :confval:`default_return` option.)\n\n.. code-block:: python\n\n    def f(name: str):\n        print(f\"Hello, {name}!\")\n\n    reveal_type(f)  # (str) -> None\n\nGeneric ``TypeVar`` Bounds\n--------------------------\n\nBasedmpy allows the bounds of ``TypeVar``\\s to be generic.\n\nSo you are able to have functions with polymorphic generic parameters:\n\n.. code-block:: python\n\n    E = TypeVar(\"E\")\n    I = TypeVar(\"I\", bound=Iterable[E])\n\n\n    def foo(i: I, e: E) -> I:\n        assert e not in i\n        return i\n\n\n    reveal_type(foo([\"based\"], \"mypy\"))  # N: Revealed type is \"list[str]\"\n    reveal_type(foo({1, 2}, 3))  # N: Revealed type is \"set[int]\"\n\n\n``TypeVar`` usages work properly\n--------------------------------\n\nmypy allows various invalid usages of ``TypeVar``, which are corrected in basedmypy.\n\nit's invalid to provide variance to a constrained ``TypeVar`` because they aren't generic, they\nrepresent a set of choices that the ``TypeVar`` can be replaced with:\n\n.. code-block:: python\n\n    E = TypeVar(\"E\", int, str, covariant=True)  # mypy doesn't report the error here\n\n    G = TypeVar(\"G\", int, str)\n    class P(Protocol[G]):  # mypy reports an invalid error here\n        def f() -> E: ...\n\n    class A[T: (object, str)]: ...\n    a = A[int]()  # mypy doesn't report the error here\n\n    class B[T: int]: ...\n    type C = B[object]  # mypy doesn't report the error here\n\n\nReinvented type guards\n----------------------\n\n``TypeGuard`` acts similar to ``cast``, which is often sub-optimal and dangerous:\n\n.. code-block:: python\n\n    def is_str_list(val: list[object]) -> TypeGuard[list[str]]:\n        return all(isinstance(x, str) for x in val)\n\n    l1: list[object] = []\n    l2 = l1\n\n    if is_str_list(l1):\n        l2.append(100)\n        reveal_type(l1[0])  # Revealed type is \"str\", at runtime it is 100\n\n\n    class A: ...\n    class B(A): ...\n    def is_a(val: object) -> TypeGuard[A]: ...\n\n    b = B()\n    if is_a(b):\n        reveal_type(b)  # A, not B\n\n\nBasedmypy introduces a simpler and more powerful denotation for type-guards, and changes their behavior\nto be safer.\n\n.. code-block:: python\n\n    def is_int(value: object) -> value is int: ...\n\nType-guards don't widen:\n\n.. code-block:: python\n\n    a: bool\n    if is_int(a):\n        reveal_type(a)  # Revealed type is \"bool\"\n\nType-guards narrow in the negative case:\n\n.. code-block:: python\n\n    a: int | str\n    if is_int(a):\n        reveal_type(a)  # Revealed type is \"int\"\n    else:\n        reveal_type(a)  # Revealed type is \"str\"\n\nType-guards work on the implicit ``self`` and ``cls`` parameters:\n\n.. code-block:: python\n\n    class A:\n        def guard(self) -> self is B: ...\n    class B(A): ...\n\n    a = A()\n    if a.guard():\n        reveal_type(a)  # Revealed type is \"B\"\n\nInvalid type-guards show an error:\n\n.. code-block:: python\n\n    def guard(x: str) -> x is int: # error: A type-guard's type must be assignable to its parameter's type.\n\nType-guards that only narrow when returning true are denoted as:\n\n.. code-block:: python\n\n    def is_positive_int(x: object) -> x is int if True else False:\n        return isinstance(x, int) and x > 0\n\n    i: int | None\n    if is_positive_int(i):\n        reveal_type(i)  # Revealed type is \"int\"\n    else:\n        reveal_type(i)  # Revealed type is \"int | None\"\n\nIf you want to achieve something similar to the old ``TypeGuard``:\n\n.. code-block:: python\n\n    def as_str_list(val: list[object]) -> list[str] | None:\n        return (\n            cast(list[str], val)\n            if all(isinstance(x, str) for x in val)\n            else None\n        )\n\n    a: list[object]\n    if (str_a := as_str_list(a)) is not None:\n        ...\n\n    # or\n\n    def is_str_list(val: list[object]) -> bool:\n        return all(isinstance(x, str) for x in val)\n\n    a: list[object]\n    if is_str_list(a):\n        str_a = cast(list[str], a)\n        ...\n\n\nCovariant Mapping key type\n--------------------------\n\nThe key type of ``Mapping`` is fixed to be covariant:\n\n.. code-block:: python\n\n    a: Mapping[str, str]\n    b: Mapping[object, object] = a  # no error\n\n\nTuple Literal Types\n-------------------\n\nBasedmypy allows denotation of tuple types with tuple literals:\n\n.. code-block:: python\n\n    a: (int, str) = (1, \"a\")\n\n\nTypes in Messages\n-----------------\n\nBasedmypy makes significant changes to error and info messages, consider:\n\n.. code-block:: python\n\n    T = TypeVar(\"T\", bound=int)\n\n    def f(a: T, b: list[str | 1 | 2]):\n        reveal_type((a, b))\n\n    reveal_type(f)\n\nMypy shows::\n\n    Revealed type is \"tuple[T`-1, builtins.list[Union[builtins.str, Literal[1], Literal[2]]]]\"\n    Revealed type is \"def [T <: builtins.int] (a: T`-1, b: builtins.list[Union[builtins.str, Literal[1], Literal[2]]]) -> Any\"\n\nBasedmypy shows::\n\n    Revealed type is \"(T@f, list[str | 1 | 2])\"\n    Revealed type is \"def [T: int] (a: T, b: list[str | 1 | 2]) -> None\"\n\n\nReveal Type Narrowed\n--------------------\n\nThe defined type of a variable will be shown in the message for `reveal_type`:\n\n.. code-block:: python\n\n    a: object\n    a = 1\n    reveal_type(a)  # Revealed type is \"int\" (narrowed from \"object\")\n\n\nTyped ``functools.Cache``\n-------------------------\n\nIn mypy, ``functools.cache`` is unsafe:\n\n.. code-block:: python\n\n    @cache\n    def f(): ...\n    f(1, 2, 3)  # no error\n\nThis is resolved:\n\n.. code-block:: python\n\n    @cache\n    def f(): ...\n    f(1, 2, 3)  # error: expected no args\n\n\nChecked f-strings\n-----------------\n\n.. code-block:: python\n\n    f\"{None:0>2}\"  # error: The type \"None\" doesn't support format-specifiers\n    f\"{date(1,1,1):%}\"  # error: Invalid trailing '%', escape with '%%'\n    f\"{'s':.2f}\"  # error: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | complex\")\n\n\nSupport for `typing.type_check_only`\n------------------------------------\n\n`typing.type_check_only` is a decorator that specifies that a value is not available at runtime:\n\n.. code-block:: python\n\n    ellipsis  # error: Symbol \"ellipsis\" is not accessible at runtime  [type-check-only]\n    function  # error: Symbol \"function\" is not accessible at runtime  [type-check-only]\n\n\nAnnotations in Functions\n------------------------\n\nBasedmypy handles type annotations in function bodies as unevaluated:\n\n`PEP 526 <https://peps.python.org/pep-0526/#runtime-effects-of-type-annotations>`_\n\n.. code-block:: python\n\n    def f():\n        a: int | str  # no error in python 3.9, this annotation isn't evaluated\n\n\nChecked Argument Names\n----------------------\n\nBasedmypy will warn when subtypes have different keyword arguments:\n\n.. code-block:: python\n\n    class A:\n        def f(self, a: int): ...\n\n    class B(A):\n        @override\n        def f(self, b: int): ...  # error: Signature of \"f\" incompatible with supertype \"A\"\n\n\nRegex Checks\n------------\n\nBasedmypy will report invalid regex patterns, and also analyze regex values\nto infer the group composition of a resulting ``Match`` object:\n\n.. code-block:: python\n\n    re.compile(\"as(df\")  #  error: missing ), unterminated subpattern at position 0  [regex]\n\n    if m := re.search(\"(a)?(b)\", s):\n        reveal_type(m.groups())  # Revealed type is \"(str | None, str)\"\n\n    if m := re.search(\"(?P<foo>a)\", s):\n        reveal_type(m.group(\"foo\"))\n        reveal_type(m.group(\"bar\"))  # error: no such group: 'bar'  [regex]\n\nHelpful String Check\n--------------------\n\n`<object object at 0x0123456789ABCDEF>` and `None` accidentally appearing in user facing messages\nis not ideal, so basedmypy will warn against it:\n\n.. code-block:: python\n\n    class A: ...\n    f\"{A()}\"  # error: The type \"A\" doesn't define a __str__ or __format__ method  [unhelpful-string]\n    f\"{print(\"hi\")}\"  # error: The string for \"None\" isn't helpful for a user-facing message  [unhelpful-string]\n"
  },
  {
    "path": "docs/source/based_inference.rst",
    "content": ".. _based_inference:\n\nBased Inference\n===============\n\n\nOverload Implementation Inference\n---------------------------------\n\nThe types in overload implementations (including properties) can be inferred:\n\n.. code-block:: python\n\n    @overload\n    def f(a: int) -> str: ...\n\n    @overload\n    def f(a: str) -> int: ...\n\n    def f(a):\n        reveal_type(a)  # int | str\n        return None  # error: expected str | int\n\n    class A:\n        @property\n        def foo(self) -> int: ...\n        @foo.setter\n        def foo(self, value): ...  # no need for annotations\n\n\nInfer Function Parameters\n-------------------------\n\nInfer the type of a function parameter from its default value:\n\n.. code-block:: python\n\n    def f(a=1, b=True):\n        reveal_type((a, b))  # (int, bool)\n\nNarrow On Initial Assignment\n----------------------------\n\nWhen a variable definition has an explicit annotation, the initialization value will be used to narrow its type:\n\n.. code-block:: python\n\n    a: object = 1\n    reveal_type(a)  # Revealed type is \"int\"\n\n\nUnused Parameter Inferred\n-------------------------\n\nWhen a parameter is named `_`, its type will be inferred as `object`:\n\n.. code-block:: python\n\n    def f(a: int, _):\n        reveal_type(_)  # Revealed type is \"object\"\n\nThis is to help with writing functions for callbacks where you don't care about certain parameters.\n"
  },
  {
    "path": "docs/source/baseline.rst",
    "content": ".. _baseline:\n\nBaseline\n========\n\nBasedmypy supports a feature know as 'baselining' where a snapshot of a codebase is\ntaken and compared against on subsequent runs. This can be used to ease the gradual\nadoption of new checks and strictness options. It is not intended as a utility to\nreplace ``type: ignore`` comments or to hide errors.\n\nThe baseline file should be committed with your project so that other people can utilize and update it.\n\n\nWorkflow\n--------\n\nConsider the following:\n\n\n.. code-block:: python\n\n    # demo.py\n    def foo(a: list) -> None:\n        if \"bar\" in a:\n            a.append(\"baz\")\n\n\nAll three lines here contain errors:\n\n.. code-block:: text\n\n    > mypy demo.py\n    demo.py:1: error: Missing type parameters for generic type \"list\"  [type-arg]\n    demo.py:2: error: Expression type contains \"Any\" (has type \"List[Any]\")  any\n    demo.py:3: error: Expression type contains \"Any\" (has type \"List[Any]\")  any\n    Found 3 errors in 1 file (checked 1 source file)\n\nWe can write these errors to a baseline file:\n\n.. code-block:: text\n\n    > mypy --write-baseline demo.py\n    demo.py:1: error: Missing type parameters for generic type \"list\"  [type-arg]\n    demo.py:2: error: Expression type contains \"Any\" (has type \"List[Any]\")  any\n    demo.py:3: error: Expression type contains \"Any\" (has type \"List[Any]\")  any\n    Found 3 errors (3 new errors) in 1 file (checked 1 source file)\n    Baseline successfully written to .mypy/baseline.json\n\nNow when we run mypy again we will not receive any errors:\n\n.. code-block:: text\n\n    > mypy demo.py\n    Success: no issues found in 1 source file\n\nIf we modify the source code to have the correct full-form type annotation:\n\n.. code-block:: python\n\n    def foo(a: list[str]) -> None:\n        if \"bar\" in a:\n            a.append(\"baz\")\n\nAnd run mypy again:\n\n.. code-block:: text\n\n    > mypy demo.py\n    No errors, baseline file removed\n    Success: no issues found in 1 source file\n\nIt has detected that all the errors have now been resolved and the baseline file is no longer required.\n\nAlternatively, if instead we introduce new code that contains errors:\n\n.. code-block:: python\n\n    def foo(a: list) -> None:\n        if \"bar\" in a:\n            a.append(\"baz\")\n        1 + \"\"\n\nAnd run mypy again:\n\n.. code-block:: text\n\n    > mypy demo.py\n    demo.py:4:9: error: Unsupported operand types for + (\"int\" and \"str\")  [operator]\n    Found 1 error in 1 file (checked 1 source file)\n\nOnly errors within the new code are reported.\n\nAdditionally\n************\n\nIf your project uses multiple mypy runs or configurations you can specify alternative baseline file locations for each:\n\n.. code-block:: shell\n\n    > mypy --baseline-file .mypy/strict.json\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\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.. _baseline_features:\n\n\nBaseline interaction\n********************\n\nThe following flags are used to interact with the baseline functionality.\n\nYou can read more :ref:`here <baseline>`.\n\n.. option:: --write-baseline\n\n    Run mypy and create/update the baseline file with the errors found.\n\n.. option:: --baseline-file\n\n    The path of the baseline file to use. Default is ``./.mypy/baseline.json``.\n\n    You can specify :option:`--baseline-file= <--baseline-file>` (with no filename) to indicate that no baseline should be used:\n\n    .. code-block:: shell\n\n        > mypy demo.py --baseline-file=\n\n.. option:: --auto-baseline\n\n    Inverse: ``--no-auto-baseline``\n\n    Enabled by default, this feature will update the baseline file automatically if there are no new errors encountered.\n\n.. _cli_based_features:\n\nBased features\n**************\n\n.. option:: --ide\n\n    Preset options for best compatibility with an integrated developer environment.\n\n.. option:: --default-return\n\n    See :confval:`default_return`.\n\n.. option:: --bare-literals\n\n    See :confval:`bare_literals`.\n\n.. option:: --incomplete-is-typed\n\n    See :confval:`incomplete_is_typed`.\n\n.. option:: --no-untyped-usage\n\n    See :confval:`no_untyped_usage`.\n\n.. option:: --ignore-any-from-error\n\n    See :confval:`ignore_any_from_error`.\n\n.. option:: --ignore-missing-py-typed\n\n    See :confval:`ignore_missing_py_typed`\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 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 two 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 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.. _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\n\n    By default, mypy won't allow a variable to be redefined with an\n    unrelated type. 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    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 for mypy in a future 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 as a special case.\n\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 real code. In particular, it prohibits partial overlap in\n    ``TypedDict`` updates, and makes arguments prepended via ``Concatenate``\n    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.. option:: --strict\n\n    This flag mode enables all optional error checking flags.  You can see the\n    list of flags enabled by strict mode in the full :option:`mypy --help` output.\n\n    Note: the exact list of flags enabled by running :option:`--strict` may change\n    over time.\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.. _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.. option:: --force-uppercase-builtins\n\n    Always use ``List`` instead of ``list`` in error messages,\n    even on Python 3.9+.\n\n.. option:: --force-union-syntax\n\n    Always use ``Union[]`` and ``Optional[]`` for union types\n    in error messages (instead of the ``|`` operator),\n    even on Python 3.10+.\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:: --sqlite-cache\n\n    Use an `SQLite`_ database to store the cache.\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}\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() -> {\"int\": int, \"str\": str}:\n         return {\"int\": 42, \"str\": \"test\"}\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\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:: --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\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\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 only understood by mypy and\n   don't exist in Python. If you try to run your program, you'll have to\n   remove any ``reveal_type`` and ``reveal_locals`` calls before you can\n   run your code. Both are always available and you don't need to import\n   them.\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 __based_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 = \"basedmypy\"\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_theme_options = {\"light_logo\": \"logo-light.png\", \"dark_logo\": \"logo-dark.png\"}\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.\nhtml_favicon = \"../static/favicon.ico\"\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\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.\nhtml_show_copyright = False\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://docs.cython.org/en/latest\", None),\n    \"monkeytype\": (\"https://monkeytype.readthedocs.io/en/latest\", None),\n    \"setuptools\": (\"https://setuptools.readthedocs.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 with the following precedence order:\n\n    1. ``./mypy.ini``\n    2. ``./.mypy.ini``\n    3. ``./pyproject.toml``\n    4. ``./setup.cfg``\n    5. ``$XDG_CONFIG_HOME/mypy/config``\n    6. ``~/.config/mypy/config``\n    7. ``~/.mypy.ini``\n\nIt is important to understand that there is no merging of configuration\nfiles, as it would lead to ambiguity. The :option:`--config-file <mypy --config-file>`\ncommand-line flag has the highest precedence and\nmust be correct; otherwise mypy will report an error and exit. Without the\ncommand line option, mypy will look for configuration files in the\nprecedence order above.\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 `toml` (like `pyproject.toml`) or the legacy\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.. _config-file-based:\n\nBased features\n**************\n\n.. confval:: default_return\n\n    :type: boolean\n    :default: True\n\n    Causes an unannotated return type to be inferred as ``None``.\n\n    .. code-block:: python\n\n        def foo(i: int):\n            print(i)\n\n        reveal_type(foo)  # revealed type is \"def(int) -> None\"\n\n    It is required to disable this option for any dependencies that are not utilizing it, as they likely have untyped returns.\n\n    .. code-block:: toml\n\n        [[tool.mypy-overrides]]\n        module = [\"pytest.*\"]\n        default_return = false\n\n    This plays conservatively with :confval:`allow_untyped_defs <disallow_untyped_defs>` and :confval:`allow_incomplete_defs <disallow_untyped_defs>`.\n\n    .. code-block:: python\n\n        # mypy: allow-incomplete-defs, allow-untyped-defs\n        def foo(): ... # def() -> Any\n        def bar(a, b): ... # def(Any, Any) -> Any\n        def foo(a: int, b): ... # def(int, Any) -> None\n\n.. confval:: bare_literals\n\n    :type: boolean\n    :default: True\n\n    With this feature it is legal to use a literal ``int``, ``bool`` or ``Enum``\n    in a type position when it is safe to do so. This safety is determined by\n    whether ``__future__.annotations`` is active, if the file is a stub,\n    if the literal is used in a type operation, and if the literal is used\n    in an expression position (``TypeVar`` etc).\n\n.. confval:: incomplete_is_typed\n\n    :type: boolean\n    :default: False\n\n    A flag that assists with :confval:`disallow_untyped_calls` to partial functions, it indicates\n    that a partially typed function should be regarded as fully typed. This flag\n    is different to most other options in that it applies to where the function\n    is defined, not where it is called from.\n\n.. confval:: no_untyped_usage\n\n    :type: boolean\n    :default: True\n\n    ``Untyped`` is a specialized form of ``Any`` that can he helpful when gradually adopting type annotations:\n\n    .. code-block:: python\n\n        a: Untyped\n\n        a = 1  # error: usage of untyped name\n        b = a  # error: usage of untyped name\n\n    Basedmypy can now detect usage of partially typed functions:\n\n    .. code-block:: python\n\n        def foo(a, b=1): ...  # inferred as def (a: Untyped, b: int = ...)\n        def bar(a: int, b): ...  # inferred as def (a: int, b: Untyped)\n\n        foo(1, 2)  # error: call to incomplete function\n        foo(1, 2)  # error: call to incomplete function\n\n\n.. confval:: ignore_any_from_error\n\n    :type: boolean\n    :default: True\n\n    Often times, a small error can cause hundreds of errors, this feature helps to\n    surface only Any expressions that aren't from errors.\n\n\n.. confval:: ignore_missing_py_typed\n\n    :type: boolean\n    :default: False\n\n    Use the types from a package, even if it doesn't have a ``py.typed`` file.\n\n    You probably want to set this on a module override.\n\n    .. code-block:: toml\n\n        [[tool.mypy.overrides]]\n        module = [\"someuntypedmodule.*\"]\n        ignore_missing_py_typed = true\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:: 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 ``2.7``.  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: True\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: True\n\n    Disallows all expressions in the module that have type ``Any``.\n\n.. confval:: disallow_any_decorated\n\n    :type: boolean\n    :default: True\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: True\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: True\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: True\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: True\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: True\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: True\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: True\n\n    Type-checks the interior of functions without type annotations.\n\n.. confval:: disallow_untyped_decorators\n\n    :type: boolean\n    :default: True\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: True\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: True\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: True\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: True\n\n    Shows a warning when encountering any code inferred to be unreachable or\n    redundant after performing type analysis.\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: True\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\n\n    :type: boolean\n    :default: True\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:: local_partial_types\n\n    :type: boolean\n    :default: True\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\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 in real code.\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_concatenate\n\n   :type: boolean\n   :default: False\n\n   Make arguments prepended via ``Concatenate`` be truly positional-only.\n\n.. confval:: strict_equality\n\n   :type: boolean\n   :default: True\n\n   Prohibit equality checks, identity checks, and container checks between\n   non-overlapping types.\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: True\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: True\n\n    Prefixes each error with the relevant context.\n\n.. confval:: show_column_numbers\n\n    :type: boolean\n    :default: True\n\n    Shows column numbers in error messages.\n\n.. confval:: show_error_code_links\n\n    :type: boolean\n    :default: True\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: True\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\n.. confval:: force_uppercase_builtins\n\n    :type: boolean\n    :default: False\n\n    Always use ``List`` instead of ``list`` in error messages,\n    even on Python 3.9+.\n\n.. confval:: force_union_syntax\n\n    :type: boolean\n    :default: False\n\n    Always use ``Union[]`` and ``Optional[]`` for union types\n    in error messages (instead of the ``|`` operator),\n    even on Python 3.10+.\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: False\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:: 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 = \"2.7\"\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\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\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\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 part 1\n==================\n\nThis section documents various errors codes that basedmypy will\ngenerate with default options or when :confval:`strict` if off (`no_strict`).\nSee :ref:`error-codes` for general documentation\nabout error codes. :ref:`error-codes-strict` documents additional\nerror codes that are enabled with :confval:`strict` (the default).\n:ref:`error-codes-based` documents error codes that are unique\nto basedmypy.\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-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``,\nthat allows to still have errors for other improper uses of ``await``, for\nexample:\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-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-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-strict:\n\nError codes for strict checks\n=============================\n\nThis section documents various errors codes that basedmypy generates\nby default, but will be disabled when :confval:`strict` is false (`no_strict`).\nSee :ref:`error-codes` for general documentation about error codes\nand their configuration. :ref:`error-code-list` documents error codes\nthat are enabled regardless of :confval:`strict`.\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 parameters 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.. _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.\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"
  },
  {
    "path": "docs/source/error_code_list3.rst",
    "content": ".. _error-codes-based:\n\nError codes unique to basedmypy\n===============================\n\n.. _code-decorated-any:\n\nCheck that a decorated function isn't dynamic [decorated-any]\n-------------------------------------------------------------\n\nFrom :confval:`disallow_any_decorated`\n\n.. _code-any:\n\nBan any expression that contains ``Any`` [any]\n----------------------------------------------\n\nFrom :confval:`disallow_any_expr`\n\n.. _code-subclass-any:\n\nDon't subclass ``Any`` [subclass-any]\n----------------------------------------\n\nFrom :confval:`disallow_subclassing_any`\n\n.. _code-no-untyped-usage:\n\nDon't use anything that contains ``Any`` [no-untyped-usage]\n-----------------------------------------------------------\n\nFrom :confval:`no_untyped_usage`\n\n.. _code-unsafe-variance:\n\nCheck that type variables are used in accordance with their variance [unsafe-variance]\n--------------------------------------------------------------------------------------\n\n.. code-block:: python\n\n    inT = TypeVar(\"inT\", contravariant=True)\n    outT = TypeVar(\"outT\", covariant=True)\n\n    class X(Generic[inT, outT]):\n        def foo(self,\n            t: outT  # This usage of this covariant type variable is unsafe as a return type.  [unsafe-variance]\n        ) -> inT:  # This usage of this contravariant type variable is unsafe as a return type.  [unsafe-variance]\n            pass\n\n.. _code-typeguard-limitation:\n\nUnsupported usages of typeguards [typeguard-limitation]\n-------------------------------------------------------\n\nMypy does not yet support typeguarding a star argument:\n\n.. code-block:: python\n\n    def guard(x: object) -> x is int: ...\n\n    x: object\n    xs = x,\n    assert guard(*xs)  # Type guard on star argument is not yet supported  [typeguard-limitation]\n    reveal_type(x)  # object\n\n.. _code-typeguard-subtype:\n\nCheck that typeguard definitions are valid [typeguard-subtype]\n--------------------------------------------------------------\n\n.. code-block:: python\n\n    def guard(x: str) -> x is int:  # A type-guard's type must be assignable to its parameter's type. (guard has type \"int\", parameter has type \"str\")  [typeguard-subtype]\n        ...\n\n.. _code-regex:\n\nCheck for regex issues [regex]\n------------------------------\n\n.. code-block:: python\n\n    re.compile(\"(foo).*)\")  # error: unbalanced parenthesis at position 7  [regex]\n    m = re.match(\"(?P<name>\\w+)\", s)\n    assert m\n    m.group(\"nane\")  # error: no such group: 'nane'  [regex]\n\n.. _code-helpful-string:\n\nCheck that strings are useful [helpful-string]\n----------------------------------------------\n\nCatching unintentional values in f-strings:\n\n.. code-block:: python\n\n    def make_id(i: int | None) -> str:\n        return f\"id-{i}\"  # The string for \"None\" isn't helpful for a user-facing message  [helpful-string]\n\n.. _code-bad-cast:\n\nCheck that casts are valid [bad-cast]\n-------------------------------------\n\nCasting between two non-overlapping types is often a mistake:\n\n.. code-block:: python\n\n    a: int\n    cast(str, a)  # Conversion of type \"int\" to type \"str\" may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to \"object\" first.  [bad-cast]\n\n.. _code-callable-functiontype:\n\nCheck for bad usages of callabes and function types [callable-functiontype]\n---------------------------------------------------------------------------\n\nBecause functions can create methods when accessed in certain ways,\nbasedmypy has checks regarding their usages:\n\n.. code-block:: python\n\n    class A:\n        a: \"(int) -> object\" = lambda i: i + 1  # Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype]\n\n    A().a(1)  # runtime TypeError: <lambda>() takes 1 positional argument but 2 were given\n\n.. _code-possible-function:\n\nCheck that callables are valid [possible-function]\n--------------------------------------------------\n\nBecause a function can create methods when accessed in certain ways,\nbasedmypy has lint rules regarding their validity as ``Callable``\\s:\n\n.. code-block:: python\n\n    c: \"(int) -> object\" = lambda i: i + 1\n    class A:\n        a: \"(int) -> object\" = c  # This \"CallableType\" could be a \"FunctionType\", which when assigned via the class, would produce a \"MethodType\"  [possible-function]\n\n    A().a(1)  # runtime TypeError: <lambda>() takes 1 positional argument but 2 were given\n\n\n.. _code-unhandled-scenario:\n\nA scenario isn't being handled correctly by basedmypy itself\n------------------------------------------------------------\n\nSometimes, the implementation of a the type system is not completely sound\nand basedmypy needs to be updated.\n\n\n.. _code-type-check-only:\n\nSupport typing.type_check_only [type-check-only]\n------------------------------------------------\n\nSomething is being used in a runtime position that is not actually\naccessible or available at runtime.\n\n.. _code-reveal:\n\n# deprecated\n\n.. _code-no-any-decorated:\n\n.. _code-no-any-explicit:\n\n.. _code-no-any-expr:\n\n.. _code-no-subclass-any:\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 three topics (:ref:`error-code-list`,\n   :ref:`error-codes-strict` and :ref:`error-codes-based`) document the\n   various error codes basedmypy 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\nBaseline\n--------\n\nThe baseline functionality can store and ignore all currently existing type\nerrors such that you will only see errors coming from new code.\n\nSee :ref:`baseline`\n\nBasedmypy recommends this strategy, but alternatives are listed below.\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 these passing should be easy\n   strict_equality = True\n   strict_concatenate = 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\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-strict`.\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.\nThis does not apply to abstract classes that inherit from the ``Protocol`` class.\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.append('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[-1].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 colletions.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 synta):\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\nAnyone familiar with mypy should feel comfortable working with basedmypy.\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 basedmypy\n********************************\n\nBasedmypy cannot be installed alongside mypy, which must be uninstalled first:\n\n.. code-block:: shell\n\n    > pip uninstall mypy -y\n\nBasedmypy requires Python 3.8 or later to run.  You can install basedmypy using pip:\n\n.. code-block:: shell\n\n    $ python3 -m pip install basedmypy\n\nOnce basedmypy 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\nIf you try directly running mypy on your existing Python code, it\nwill most likely report lots and lots of errors. This is a feature! It makes it\neasy to notice all the possible errors with your code. (You can also\nlook into the baseline feature to help you adopt mypy incrementally.)\n\nIn order to get useful inferences 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\nBasedmypy has all strictness options enabled by default. This can often be a\nlittle overwhelming, and the baseline functionality can help alleviate this.\nFor a good compromise of safety and ease of use, we can recommend enabling ``allow_any_expr``.\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, basedmypy will type check dynamically typed functions. This means\nthat with a few exceptions, mypy will report all errors within 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, and basedmypy does report an error\n   # even though \"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\n\nclass MypyHTMLBuilder(StandaloneHTMLBuilder):\n    def __init__(self, app: Sphinx, env: BuildEnvironment) -> None:\n        super().__init__(app, env)\n        self._ref_to_doc = {}\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 _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\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 the basedmypy docs!\n==============================\n\nBasedmypy is a static type checker for Python that is built on top of the work done\nby the `mypy project <https://github.com/python/mypy>`_.\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.. toctree::\n   :maxdepth: 2\n   :caption: Basedmypy\n\n   baseline\n   based_features\n   based_inference\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   error_code_list3\n   additional_features\n   faq\n   changelog\n\n.. toctree::\n   :hidden:\n   :caption: Project Links\n\n   GitHub <https://github.com/KotlinIsland/basedmypy>\n   Discord <https://discord.gg/7y9upqPrk2>\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\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\n**************\n\nA callable type is a type that conforms to the ``collections.abc.Callable`` protocol, i.e. it has a ``__call__`` attribute (invoked with the call operator: ``X()``).\nThere are three main kinds of these:\n\n- functions and lambdas (``types.FunctionType``/``builtins.function``)\n- ``type`` objects. (i.e. the ``int`` class)\n- instances that define a ``__call__`` method\n\nA callable type can be denoted as ``\"(int, str) -> None\"``. A function type (``types.FunctionType``) can be denoted as ``\"def (int, str) -> None\"``.\n\n``FunctionType`` does have some problematic behavior due to it's implementation of ``__get__``:\n\n.. code-block:: python\n\n    def f(a, b): ...\n    class A:\n        f = f\n\n    A.f(1, 2)\n    A().f(1, 2)  # TypeError: f() takes 2 positional arguments but 3 were given\n\nThis is because when the class attribute is accessed through an instance, ``FunctionType`` will instead return a ``MethodType``, with the ``self`` argument pre-filled.\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.. _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).\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, Self\n\n    class M(type):\n        count: ClassVar[int] = 0\n\n        def make(cls) -> Self:\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.. note::\n    In Python 3.10 and earlier, ``Self`` is available in ``typing_extensions``.\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"
  },
  {
    "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 implementor 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 to get declared or inferred type of an expression (or other\ninformation about an expression, such as known attributes or definition location)\nusing ``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\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 ``from __future__ import annotations`` (:pep:`563`)\n  (this behaviour may eventually be made the default in a future Python version)\n* Use of string literal types or type comments\n* Use of ``typing.TYPE_CHECKING``\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 re-use 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 argument \"foo\" (default has\n        # type \"ellipsis\", argument 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\nIf you wish to ignore some of stubtest's complaints, stubtest supports a\npretty handy allowlist system.\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 --generate-allowlist. Allowlists\n    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 --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(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\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\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\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"
  },
  {
    "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() -> {\"int\": int, \"str\": str}:\n        return {\"int\": 42, \"str\": \"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\nfrom typing_extensions import 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):\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: Any = json.load(ds)\n\n    with open(meta_path) as ms:\n        meta_json: Any = 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\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\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/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\"\"\"\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 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            cache.write(file, data)\n            if file.endswith(\".meta.json\") and \"@deps\" not in file:\n                meta = json_loads(data)\n                old_deps[\"snapshot\"][meta[\"id\"]] = meta[\"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\"):\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 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 load(cache: MetadataStore, s: str) -> Any:\n    data = cache.read(s)\n    obj: Any = json_loads(data)\n    if s.endswith(\".meta.json\"):\n        # For meta files, zero out the mtimes and sort the\n        # dependencies to avoid spurious conflicts\n        obj[\"mtime\"] = 0\n        obj[\"data_mtime\"] = 0\n        if \"dependencies\" in obj:\n            all_deps = obj[\"dependencies\"] + obj[\"suppressed\"]\n            num_deps = len(obj[\"dependencies\"])\n            thing = list(zip(all_deps, obj[\"dep_prios\"], obj[\"dep_lines\"]))\n\n            def unzip(x: Any) -> Any:\n                return zip(*x) if x else ((), (), ())\n\n            obj[\"dependencies\"], prios1, lines1 = unzip(sorted(thing[:num_deps]))\n            obj[\"suppressed\"], prios2, lines2 = unzip(sorted(thing[num_deps:]))\n            obj[\"dep_prios\"] = prios1 + prios2\n            obj[\"dep_lines\"] = lines1 + lines2\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 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 cache\")\n    parser.add_argument(\"input_dir2\", help=\"Input directory for the cache\")\n    parser.add_argument(\"output\", help=\"Output file\")\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, bytes | 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] = json_dumps(obj2)\n                else:\n                    updates[s] = None\n            elif obj2:\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            updates[s] = cache2.read(s)\n\n    # Compute what deps have been added and merge them all into the\n    # @root deps file.\n    new_deps = {k: deps1.get(k, set()) - deps2.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)\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([A-Z])\", r\"\\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\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    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.*\\+dev\", 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    s = f\" * {c.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    parser.add_argument(\"version\", help=\"target mypy version (form X.Y)\")\n    parser.add_argument(\"--local\", action=\"store_true\")\n    args = parser.parse_args()\n    version: str = args.version\n    local: bool = args.local\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    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\nfrom typing_extensions import 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/install.py",
    "content": "import argparse\nfrom subprocess import check_call\n\n\ndef main(args: argparse.Namespace):\n    venv_args = [\"uv\", \"venv\", \"--python\", args.python, f\".venv{args.python}\"]\n    check_call(venv_args)\n    install_args = [\n        \"uv\",\n        \"pip\",\n        \"install\",\n        \"-r\",\n        \"test-requirements.txt\",\n        \"-e\",\n        \".\",\n        \"--python\",\n        f\".venv{args.python}\",\n    ]\n    check_call(install_args)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--python\", required=True)\n    main(parser.parse_args())\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 typing 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": "\"\"\"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 mypy 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(target_dir: str) -> None:\n    env = os.environ.copy()\n    env[\"CC\"] = \"clang\"\n    env[\"MYPYC_OPT_LEVEL\"] = \"2\"\n    env[\"PYTHONHASHSEED\"] = \"1\"\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) -> None:\n    heading(f\"Cloning mypy to {target_dir}\")\n    repo_dir = 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_dir, 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\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    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    subprocess.run(cmd, cwd=compiled_dir, env=env)\n    return time.time() - t0\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\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        \"--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=8,\n        type=int,\n        help=\"set maximum number of parallel builds (default=8)\",\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(\"commit\", nargs=\"+\", help=\"git revision to measure (e.g. branch name)\")\n    args = parser.parse_args()\n    incremental: bool = args.incremental\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\n    if not (os.path.isdir(\".git\") and os.path.isdir(\"mypyc\")):\n        sys.exit(\"error: Run this 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        clone(target_dir, commit)\n\n    self_check_dir = \"mypy.self.tmpdir\"\n    clone(self_check_dir, commits[0])\n\n    heading(\"Compiling mypy\")\n    print(\"(This will take a while...)\")\n\n    with ThreadPoolExecutor(max_workers=max_workers) as executor:\n        futures = [executor.submit(build_mypy, target_dir) for target_dir in target_dirs]\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(target_dirs[i], self_check_dir, incremental=incremental, code=code)\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        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})\")\n\n    shutil.rmtree(self_check_dir)\n    for target_dir in target_dirs:\n        shutil.rmtree(target_dir)\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    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        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(\n            f\"\"\"\\\n            Sync typeshed\n\n            Source commit:\n            https://github.com/python/typeshed/commit/{commit}\n            \"\"\"\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\" | head -n 1 | cut -d\" \" -f2)\n\ngit clone --depth 1 https://${WHEELS_PUSH_TOKEN}@github.com/KotlinIsland/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-Remove-use-of-LiteralString-in-builtins-13743.patch",
    "content": "From b4259edd94188f9e4cc77a22e768eea183a32053 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 | 100 +-----------------------------\n 1 file changed, 1 insertion(+), 99 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi\nindex 63c53a5f6..d55042b56 100644\n--- a/mypy/typeshed/stdlib/builtins.pyi\n+++ b/mypy/typeshed/stdlib/builtins.pyi\n@@ -63,7 +63,6 @@ from typing import (  # noqa: Y022\n from typing_extensions import (  # noqa: Y023\n     Concatenate,\n     Literal,\n-    LiteralString,\n     ParamSpec,\n     Self,\n     TypeAlias,\n@@ -438,31 +437,16 @@ class str(Sequence[str]):\n     def __new__(cls, object: object = ...) -> Self: ...\n     @overload\n     def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> 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 = ..., end: SupportsIndex | 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 = ..., end: SupportsIndex | 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 = ..., end: SupportsIndex | 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 = ..., end: SupportsIndex | None = ..., /) -> int: ...\n@@ -478,99 +462,35 @@ 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     if sys.version_info >= (3, 9):\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 \n     def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ...\n     def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ..., end: SupportsIndex | 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@@ -581,39 +501,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, /) -> LiteralString: ...\n-    @overload\n-    def __getitem__(self, key: SupportsIndex | slice, /) -> str: ...  # type: ignore[misc]\n+    def __getitem__(self, key: SupportsIndex | slice, /) -> str: ...\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 \n-- \n2.47.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch",
    "content": "From abc5225e3c69d7ae8f3388c87260fe496efaecac 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 89cdff6cc..1397e579d 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\n from typing import Any, Literal, TextIO, TypeVar\n@@ -13,7 +13,7 @@ _T = TypeVar(\"_T\")\n _T_co = TypeVar(\"_T_co\", covariant=True)\n _TaskYieldType: TypeAlias = Future[object] | None\n\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 b75e34fc5..526406acc 100644\n--- a/mypy/typeshed/stdlib/builtins.pyi\n+++ b/mypy/typeshed/stdlib/builtins.pyi\n@@ -1130,7 +1130,7 @@ class frozenset(AbstractSet[_T_co]):\n     if sys.version_info >= (3, 9):\n         def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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@@ -1324,7 +1324,7 @@ else:\n\n exit: _sitebuiltins.Quitter\n\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@@ -1389,7 +1389,7 @@ license: _sitebuiltins._Printer\n\n def locals() -> dict[str, Any]: ...\n\n-class map(Generic[_S]):\n+class map(Iterator[_S]):\n     @overload\n     def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /) -> Self: ...\n     @overload\n@@ -1632,7 +1632,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex\n\n quit: _sitebuiltins.Quitter\n\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@@ -1693,7 +1693,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ...\n @overload\n def vars(object: Any = ..., /) -> dict[str, Any]: ...\n\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 = ...) -> zip[Any]: ...\ndiff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi\nindex 4a82de638..ef93129d6 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 typing import Any, Generic, Literal, TypeVar, overload\n from typing_extensions import Self\n\n@@ -75,7 +75,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 bf6daad0a..1e6aa78e2 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 TracebackType\n-from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload\n+from typing import IO, Any, AnyStr, Literal, Protocol, overload\n from typing_extensions import Self, TypeAlias\n\n if sys.version_info >= (3, 9):\n@@ -107,7 +107,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 55b0814ac..675533d44 100644\n--- a/mypy/typeshed/stdlib/itertools.pyi\n+++ b/mypy/typeshed/stdlib/itertools.pyi\n@@ -29,7 +29,7 @@ _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-class count(Generic[_N]):\n+class count(Iterator[_N]):\n     @overload\n     def __new__(cls) -> count[int]: ...\n     @overload\n@@ -39,12 +39,12 @@ class count(Generic[_N]):\n     def __next__(self) -> _N: ...\n     def __iter__(self) -> Self: ...\n\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-class repeat(Generic[_T]):\n+class repeat(Iterator[_T]):\n     @overload\n     def __new__(cls, object: _T) -> Self: ...\n     @overload\n@@ -53,7 +53,7 @@ class repeat(Generic[_T]):\n     def __iter__(self) -> Self: ...\n     def __length_hint__(self) -> int: ...\n\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 = ...) -> Self: ...\n     @overload\n@@ -61,7 +61,7 @@ class accumulate(Generic[_T]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T: ...\n\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@@ -71,22 +71,22 @@ class chain(Generic[_T]):\n     if sys.version_info >= (3, 9):\n         def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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-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-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-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@@ -94,7 +94,7 @@ class groupby(Generic[_T_co, _S_co]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ...\n\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@@ -102,19 +102,19 @@ class islice(Generic[_T]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T: ...\n\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-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\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 = ...) -> zip_longest[tuple[_T1]]: ...\n@@ -192,7 +192,7 @@ class zip_longest(Generic[_T_co]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T_co: ...\n\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@@ -277,7 +277,7 @@ class product(Generic[_T_co]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T_co: ...\n\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@@ -291,7 +291,7 @@ class permutations(Generic[_T_co]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T_co: ...\n\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@@ -305,7 +305,7 @@ class combinations(Generic[_T_co]):\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T_co: ...\n\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@@ -320,13 +320,13 @@ class combinations_with_replacement(Generic[_T_co]):\n     def __next__(self) -> _T_co: ...\n\n if sys.version_info >= (3, 10):\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-    class batched(Generic[_T_co]):\n+    class batched(Iterator[tuple[_T_co, ...]], Generic[_T_co]):\n         if sys.version_info >= (3, 13):\n             def __new__(cls, iterable: Iterable[_T_co], n: int, *, strict: bool = False) -> Self: ...\n         else:\ndiff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi\nindex 2937d45e3..93197e5d4 100644\n--- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi\n+++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi\n@@ -1,5 +1,5 @@\n import sys\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 TracebackType\n from typing import Any, Final, Generic, TypeVar\n@@ -37,7 +37,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 b83516b4d..724bc3166 100644\n--- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi\n+++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi\n@@ -397,7 +397,7 @@ class Connection:\n         self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, /\n     ) -> Literal[False]: ...\n\n-class Cursor:\n+class Cursor(Iterator[Any]):\n     arraysize: int\n     @property\n     def connection(self) -> Connection: ...\n--\n2.47.1\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-sum-literal-integer-change-13961.patch",
    "content": "From 58c6a6ab863c1c38e95ccafaf13792ed9c00e499 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 ea9f8c894..a6065cc67 100644\n--- a/mypy/typeshed/stdlib/builtins.pyi\n+++ b/mypy/typeshed/stdlib/builtins.pyi\n@@ -1653,7 +1653,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.46.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch",
    "content": "From 61a490091d7c941780919660dc4fdfa88ae6474a 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 Since the plugin provides\n superior type checking:\n https://github.com/python/mypy/pull/13987#issuecomment-1310863427 A manual\n cherry-pick of e437cdf.\n\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 60bbc51d9..cf9cb81a4 100644\n--- a/mypy/typeshed/stdlib/_ctypes.pyi\n+++ b/mypy/typeshed/stdlib/_ctypes.pyi\n@@ -169,11 +169,7 @@ class Array(_CData, Generic[_CT]):\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.39.3 (Apple Git-146)\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\"}:  # 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 sys\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 = \"KotlinIsland/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    if name.endswith(\".tar.gz\"):\n        name = name[:-7]\n    if name.endswith(\".whl\"):\n        name = name[:-4]\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        versionutil_py = f.extractfile(f\"{sdist.name[:-len('.tar.gz')]}/mypy/versionutil.py\")\n        assert version_py is not None\n        assert versionutil_py is not None\n        version_py_contents = version_py.read().decode(\"utf-8\")\n        versionutil_py_contents = versionutil_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        from types import ModuleType\n\n        version_module = ModuleType(\"version\")\n        versionutil = ModuleType(\"versionutil\")\n        exec(versionutil_py_contents, versionutil.__dict__)\n        sys.modules[\"mypy.versionutil\"] = versionutil\n        version_py_contents = re.sub(\"from mypy import git\\n\", \"\", version_py_contents).split(\n            \"mypy_dir \"\n        )[0]\n        exec(version_py_contents, version_module.__dict__)\n\n        assert (\n            hashless_version == version_module.__based_version__\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\"]\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, save_dist=False) -> None:\n    # Verify `version` is a valid version, eg: 1.3.1rc2\n    assert re.match(r\"v?\\d+\\.\\d+\\.\\d+(\\+dev\\.\\S+|(a|b|rc)\\d+)?$\", version)\n    if \"dev\" in version:\n        assert dry_run, \"Must use --dry-run with dev versions of mypy\"\n    if version.startswith(\"v\"):\n        version = version[1:]\n\n    if save_dist:\n        dist = Path() / \"dist\"\n        dist.mkdir()\n        print(\"Saving wheels in project\")\n    else:\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(\n        \"--save-dist\", action=\"store_true\", default=False, help=\"location to store wheels\"\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, args.save_dist)\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\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 io import StringIO\nfrom typing import Callable, 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 Iterable, Sequence\nfrom typing import Protocol, cast\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    TypeGuardType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnpackType,\n    get_proper_type,\n    remove_dups,\n)\n\n\nclass ReportIncompatibleTypevarValue(Protocol):\n    def __call__(\n        self, a: CallableType, b: Type, c: str, d: Context, /, *, constrained: bool = False\n    ): ...\n\n\ndef get_target_type(\n    tvar: TypeVarLikeType,\n    type: Type,\n    callable: CallableType,\n    report_incompatible_typevar_value: ReportIncompatibleTypevarValue,\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        # TODO: can we use `type` as the context here?\n        report_incompatible_typevar_value(callable, type, tvar.name, context, constrained=True)\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: ReportIncompatibleTypevarValue,\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        # apply concrete bounds\n        tvar.upper_bound = expand_type(tvar.upper_bound, id_to_type)\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 = cast(TypeGuardType, 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 = list(result.variables) + 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 Sequence\nfrom typing import TYPE_CHECKING, Callable\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 caller_arg_type argument should evaluate to the type of the actual\n    argument type 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:\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] = set()\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 upack 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 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 (\n                isinstance(actual_type, Instance)\n                and len(actual_type.args) > 1\n                and is_subtype(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 Generator, Iterator\nfrom contextlib import contextmanager\nfrom typing import NamedTuple, Optional, Union\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nfrom mypy.erasetype import remove_instance_last_known_values\nfrom mypy.join import join_simple\nfrom mypy.literals import Key, literal, literal_hash, subkeys\nfrom mypy.nodes import Expression, IndexExpr, MemberExpr, NameExpr, RefExpr, TypeInfo, Var\nfrom mypy.subtypes import is_same_type, is_subtype\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    NoneType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    get_proper_type,\n)\nfrom mypy.typevars import fill_typevars_with_any\n\nBindableExpression: _TypeAlias = Union[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    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. It also records whether it is\n    possible to reach that point at all.\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\n    def __init__(self, id: int, conditional_frame: bool = False) -> None:\n        self.id = id\n        self.types: dict[Key, CurrentType] = {}\n        self.unreachable: bool | 2 = False\n        \"\"\"\n        We need to know if the reachability is based on an \"always-true\" scenario\n        as the implementation of this feature doesn't actually change the type of the variable.\n        (it's set in semanal)\n\n        False = reachable\n        True = unreachable\n        2 = unreachable due to artificial always-true scenarios\n        \"\"\"\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, Optional[Type]]]]\n\n\nclass ConditionalTypeBinder:\n    \"\"\"Keep track of conditional types of variables.\n\n    NB: Variables are tracked by literal expression, so it is possible\n    to confuse the binder; for example,\n\n    ```\n    class A:\n        a: Union[int, str] = None\n    x = A()\n    lst = [x]\n    reveal_type(x.a)      # Union[int, str]\n    x.a = 1\n    reveal_type(x.a)      # int\n    reveal_type(lst[0].a) # Union[int, str]\n    lst[0].a = 'a'\n    reveal_type(x.a)      # int\n    reveal_type(lst[0].a) # str\n    ```\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) -> None:\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        self.try_frames: set[int] = set()\n        self.break_frames: list[int] = []\n        self.continue_frames: list[int] = []\n        self.artificial_values: set[Key]\n        self._collect_artificial_keys = False\n\n    @contextmanager\n    def collect_artificial_keys(self) -> Generator[None, None, None]:\n        collect_artificial_keys = self._collect_artificial_keys\n        self._collect_artificial_keys = True\n        self.artificial_values = set()\n        try:\n            yield\n        finally:\n            self._collect_artificial_keys = collect_artificial_keys\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        if self._collect_artificial_keys:\n            self.artificial_values.add(key)\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    def put(self, expr: Expression, typ: Type, *, from_assignment: bool = True) -> None:\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, artificial=False) -> None:\n        self.frames[-1].unreachable = 2 if artificial else 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        artificial = any(f.unreachable == 2 for f in frames)\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\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            if 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            if all_reachable and all(\n                x is not None and not x.from_assignment for x in resulting_values\n            ):\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            current_type = resulting_values[0]\n            assert current_type is not None\n            type = current_type.type\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(\n                    t is not None and is_same_type(type, t.type) for t in resulting_values[1:]\n                ):\n                    type = AnyType(TypeOfAny.from_another_any, source_any=declaration_type)\n            else:\n                for other in resulting_values[1:]:\n                    assert other is not None\n                    type = join_simple(self.declarations[key], type, other.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 isinstance(type, ProperType) and isinstance(type, UnionType):\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 current_value is None or not is_same_type(type, current_value[0]):\n                if not (artificial and key in self.artificial_values):\n                    # if any frames were artificially unreachable,\n                    #  we don't want to narrow any types\n                    self._put(key, type, from_assignment=True)\n                changed = True\n\n        self.frames[-1].unreachable = not frames\n\n        return changed\n\n    def pop_frame(self, can_skip: bool, fall_through: int) -> Frame:\n        \"\"\"Pop a frame and return it.\n\n        See frame_context() for documentation of fall_through.\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 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(\n        self, expr: Expression, type: Type, declared_type: Type | None, restrict_any: bool = False\n    ) -> None:\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        enclosing_type = get_proper_type(self.most_recent_enclosing_type(expr, type))\n        if isinstance(enclosing_type, AnyType) and not restrict_any:\n            # If x is Any and y is int, after x = y we do not infer that x is int.\n            # This could be changed.\n            # Instead, since we narrowed type from Any in a recent frame (probably an\n            # isinstance check), but now it is reassigned, we broaden back\n            # to Any (which is the most recent enclosing type)\n            self.put(expr, enclosing_type)\n        # As a special case, when assigning Any to a variable with a\n        # declared Optional type that has been narrowed to None,\n        # replace all the Nones in the declared Union type with Any.\n        # This overrides the normal behavior of ignoring Any assignments to variables\n        # in order to prevent false positives.\n        # (See discussion in #3526)\n        elif (\n            isinstance(p_type, AnyType)\n            and isinstance(p_declared, UnionType)\n            and any(isinstance(get_proper_type(item), NoneType) for item in p_declared.items)\n            and isinstance(\n                get_proper_type(self.most_recent_enclosing_type(expr, NoneType())), NoneType\n            )\n        ):\n            # Replace any Nones in the union type with Any\n            new_items = [\n                type if isinstance(get_proper_type(item), NoneType) else item\n                for item in p_declared.items\n            ]\n            self.put(expr, UnionType(new_items))\n        elif isinstance(p_type, AnyType) and not (\n            isinstance(p_declared, UnionType)\n            and any(isinstance(get_proper_type(item), AnyType) for item in p_declared.items)\n        ):\n            # Assigning an Any value doesn't affect the type to avoid false negatives, unless\n            # there is an Any item in a declared union type.\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 most_recent_enclosing_type(self, expr: BindableExpression, type: Type) -> Type | None:\n        type = get_proper_type(type)\n        if isinstance(type, AnyType):\n            return get_declaration(expr)\n        key = literal_hash(expr)\n        assert key is not None\n        enclosers = [get_declaration(expr)] + [\n            f.types[key].type\n            for f in self.frames\n            if key in f.types and is_subtype(type, f.types[key][0])\n        ]\n        return enclosers[-1]\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 = f.unreachable\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    @contextmanager\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    ) -> Iterator[Frame]:\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        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        assert len(self.frames) > 1\n\n        if break_frame:\n            self.break_frames.append(len(self.frames) - break_frame)\n        if continue_frame:\n            self.continue_frames.append(len(self.frames) - continue_frame)\n        if try_frame:\n            self.try_frames.add(len(self.frames) - 1)\n\n        new_frame = self.push_frame(conditional_frame)\n        if try_frame:\n            # An exception may occur immediately\n            self.allow_jump(-1)\n        yield new_frame\n        self.pop_frame(can_skip, fall_through)\n\n        if break_frame:\n            self.break_frames.pop()\n        if continue_frame:\n            self.continue_frames.pop()\n        if try_frame:\n            self.try_frames.remove(len(self.frames) - 1)\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    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 errno\nimport gc\nimport json\nimport os\nimport platform\nimport re\nimport stat\nimport sys\nimport time\nimport types\nfrom collections.abc import Iterator, Mapping, Sequence, Set as AbstractSet\nfrom json import JSONDecodeError\nfrom pathlib import Path\nfrom sys import stderr\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    ClassVar,\n    Final,\n    NamedTuple,\n    NoReturn,\n    TextIO,\n    TypedDict,\n    cast,\n)\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nimport mypy.semanal_main\nfrom mypy.checker import TypeChecker\nfrom mypy.error_formatter import OUTPUT_CHOICES, ErrorFormatter\nfrom mypy.errors import CompileError, ErrorInfo, Errors, StoredBaselineError, report_internal_error\nfrom mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort\nfrom mypy.indirection import TypeIndirectionVisitor\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import Import, ImportAll, ImportBase, ImportFrom, MypyFile, SymbolTable, TypeInfo\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    getattr,\n    hash_digest,\n    is_stub_package_file,\n    is_sub_path_normabs,\n    is_typeshed_file,\n    module_prefix,\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 defaults, errorcodes as codes, util\nfrom mypy.config_parser import 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 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\nfrom mypy.typestate import reset_global_state, type_state\nfrom mypy.util import json_dumps, json_loads\nfrom mypy.version import __based_version__, __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\nGraph: _TypeAlias = dict[str, \"State\"]\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\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) -> 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\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    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    try:\n        result = _build(\n            sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr, extra_plugins\n        )\n        result.errors = messages\n        return result\n    except CompileError as e:\n        # CompileErrors raised from an errors object carry all of 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        # don't write anything if there was a compile error\n        options.write_baseline = False\n        flush_errors(None, e.messages, serious)\n        e.messages = messages\n        raise\n\n\ndef _build(\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) -> BuildResult:\n    if platform.python_implementation() == \"CPython\":\n        # Run gc less frequently, as otherwise we can spent 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    load_baseline(options, errors, stdout)\n    plugin, snapshot = load_plugins(options, errors, stdout, extra_plugins)\n\n    # Add catch-all .gitignore to cache dir if we created it\n    cache_dir_existed = os.path.isdir(options.cache_dir)\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=__based_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    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        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 not cache_dir_existed and 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 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\nclass CacheMeta(NamedTuple):\n    id: str\n    path: str\n    mtime: int\n    size: int\n    hash: str\n    dependencies: list[str]  # names of imported modules\n    data_mtime: int  # mtime of data_json\n    data_json: str  # path of <id>.data.json\n    suppressed: list[str]  # dependencies that weren't imported\n    options: dict[str, object] | None  # build options\n    # dep_prios and dep_lines are in parallel with dependencies + suppressed\n    dep_prios: list[int]\n    dep_lines: list[int]\n    interface_hash: str  # hash representing the public interface\n    version_id: str  # mypy version for cache invalidation\n    ignore_all: bool  # if errors were ignored\n    plugin_data: Any  # config data from plugins\n    baseline_hash: str | None  # hash representing the baselined errors of this module\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\ndef cache_meta_from_dict(meta: dict[str, Any], data_json: str) -> CacheMeta:\n    \"\"\"Build a CacheMeta object from a json metadata dictionary\n\n    Args:\n      meta: JSON metadata read from the metadata cache file\n      data_json: Path to the .data.json file containing the AST trees\n    \"\"\"\n    sentinel: Any = None  # Values to be validated by the caller\n    return CacheMeta(\n        meta.get(\"id\", sentinel),\n        meta.get(\"path\", sentinel),\n        int(meta[\"mtime\"]) if \"mtime\" in meta else sentinel,\n        meta.get(\"size\", sentinel),\n        meta.get(\"hash\", sentinel),\n        meta.get(\"dependencies\", []),\n        int(meta[\"data_mtime\"]) if \"data_mtime\" in meta else sentinel,\n        data_json,\n        meta.get(\"suppressed\", []),\n        meta.get(\"options\"),\n        meta.get(\"dep_prios\", []),\n        meta.get(\"dep_lines\", []),\n        meta.get(\"interface_hash\", \"\"),\n        meta.get(\"version_id\", sentinel),\n        meta.get(\"ignore_all\", True),\n        meta.get(\"plugin_data\", None),\n        meta.get(\"baseline_hash\", None),\n    )\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: Set of modules that could not be imported encountered so far\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    ) -> 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.missing_modules: set[str] = set()\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        # 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        )\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.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)\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        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\n    def dump_stats(self) -> None:\n        if self.options.dump_build_stats:\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 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\n        def correct_rel_imp(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.errors.report(\n                    imp.line, 0, \"No parent module -- cannot perform relative import\", blocker=True\n                )\n\n            return new_id\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 = correct_rel_imp(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 of 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 for some bugs in cycle handling (#4498),\n                    # if all of 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, correct_rel_imp(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, id: str, path: str, source: str, ignore_errors: bool, options: Options\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        t0 = time.time()\n        if ignore_errors:\n            self.errors.ignored_files.add(path)\n        tree = parse(source, path, id, self.errors, options=options)\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\n        self.errors.set_file_ignored_lines(path, tree.ignored_lines, ignore_errors)\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: Any = 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        import mypy.build\n\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\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 of 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.errors.report(0, 0, \"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\n#  Documenting baseline formats\nUnknownBaseline = dict[str, object]\n\n\nclass BaselineType(TypedDict):\n    targets: list[str]\n    format: str\n    files: dict[str, list[StoredBaselineError]]\n\n\ndef save_baseline(manager: BuildManager):\n    if (\n        not manager.options.baseline_file\n        or not (manager.options.write_baseline or manager.options.auto_baseline)\n        or (\n            manager.options.auto_baseline\n            and not manager.options.write_baseline\n            and (\n                manager.errors.filtered_baseline\n                or manager.errors.baseline_targets != manager.options._targets\n            )\n        )\n    ):\n        # Indicate that writing was canceled\n        manager.options.write_baseline = False\n        return\n    new_baseline = manager.errors.prepare_baseline_errors()\n    file = Path(manager.options.baseline_file)\n    if not new_baseline:\n        if file.exists():\n            file.unlink()\n            print(\"No errors, baseline file removed\")\n        elif manager.options.write_baseline:\n            print(\"No errors, no baseline to write\")\n        # Indicate that writing was canceled\n        manager.options.write_baseline = False\n        return\n    if new_baseline == manager.errors.original_baseline:\n        return\n    if not file.parent.exists():\n        file.parent.mkdir(parents=True)\n    data: BaselineType = {\n        \"files\": new_baseline,\n        \"format\": \"1.7\",\n        \"targets\": manager.options._targets,\n    }\n    with file.open(\"w\") as f:\n        json.dump(data, f, indent=2, sort_keys=True)\n    if not manager.options.write_baseline and manager.options.auto_baseline:\n        manager.stdout.write(f\"Baseline successfully updated at {file}\\n\")\n\n\ndef load_baseline(options: Options, errors: Errors, stdout: TextIO):\n    if not options.baseline_file:\n        return\n\n    from mypy import main\n\n    formatter = util.FancyFormatter(\n        stdout, stderr, options.hide_error_codes, color=options.color_output\n    )\n    file = Path(options.baseline_file)\n\n    if not file.exists():\n        if options.baseline_file != defaults.BASELINE_FILE and not options.write_baseline:\n            msg = formatter.style(f\"error: Baseline file not found at {file}\", \"red\", bold=True)\n            main.fail(msg, stderr, options)\n        return\n    try:\n        data: Any = json.loads(file.read_text())\n    except JSONDecodeError:\n        msg = formatter.style(f\"error: Invalid JSON in baseline file {file}\", \"red\", bold=True)\n        main.fail(msg, stderr, options)\n\n    def error(msg: str | None = None) -> bool:\n        if msg is None:\n            if options.write_baseline:\n                msg = (\n                    f\"error: Baseline file '{file}' has an invalid data format.\\n\"\n                    \"It's content is being ignored while a new baseline is being written.\"\n                )\n            else:\n                msg = (\n                    f\"error: Baseline file '{file}' has an invalid data format.\\n\"\n                    \"It should be regenerated with `--write-baseline`.\"\n                )\n        msg = formatter.style(msg, \"red\", bold=True)\n        if options.write_baseline:\n            stdout.write(msg)\n            return True\n        main.fail(msg, stderr, options)\n\n    # Validate data\n    if not isinstance(data, dict) and error():\n        return\n    # try to detect format:\n    baseline_format = data.get(\"format\")\n    if not baseline_format:\n        metadata = data.get(\"__baseline_metadata__\")\n        baseline_format = metadata.get(\"format\") if isinstance(metadata, dict) else None\n\n    if baseline_format is None and error():\n        return\n    elif baseline_format != \"1.7\":\n        if not options.write_baseline:\n            error(\n                f\"error: Baseline file '{file}' was generated with an old version of basedmypy.\\n\"\n                \"It should be regenerated with `--write-baseline`.\"\n            )\n        return\n    if (\n        not isinstance(data.get(\"files\"), dict) or not isinstance(data.get(\"targets\"), list)\n    ) and error():\n        return\n\n    # pull out data\n    baseline_errors = data.get(\"files\", {})\n    targets = data.get(\"targets\")\n    if baseline_errors and targets:\n        try:\n            errors.initialize_baseline(\n                cast(dict[str, list[StoredBaselineError]], baseline_errors),\n                cast(list[str], targets),\n            )\n        except TypeError:\n            if error():\n                return\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.errors.report(0, 0, \"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 \",\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)}\")\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        try:\n            with open(options.quickstart_file, \"rb\") as f:\n                raw_quickstart = json_loads(f.read())\n\n            quickstart = {file: (x, y, z) for file, (x, y, z) in raw_quickstart.items()}\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 of 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_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_json_load_time=time.time() - t1)\n    except json.JSONDecodeError:\n        manager.errors.set_file(file, None, manager.options)\n        manager.errors.report(\n            -1,\n            -1,\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(\n                \"\"\"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            )\n    except FileExistsError:\n        pass\n\n\ndef create_metastore(options: Options) -> MetadataStore:\n    \"\"\"Create the appropriate metadata store.\"\"\"\n    if options.sqlite_cache:\n        mds: MetadataStore = SqliteMetadataStore(_cache_dir_prefix(options))\n    else:\n        mds = FilesystemMetadataStore(_cache_dir_prefix(options))\n    return mds\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      cache_dir: cache directory\n      pyversion: Python version (major, minor)\n\n    Returns:\n      A tuple with the file names to be used for the meta JSON, the\n      data JSON, 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    return (prefix + \".meta.json\", prefix + \".data.json\", deps_json)\n\n\ndef find_cache_meta(id: str, path: str, manager: BuildManager) -> CacheMeta | None:\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\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_json, data_json, _ = get_cache_names(id, path, manager.options)\n    manager.trace(f\"Looking for {id} at {meta_json}\")\n    t0 = time.time()\n    meta = _load_json_file(\n        meta_json, manager, log_success=f\"Meta {id} \", log_error=f\"Could not load cache for {id}: \"\n    )\n    t1 = time.time()\n    if meta is None:\n        return None\n    if not isinstance(meta, dict):\n        manager.log(f\"Could not load cache for {id}: meta cache is not a dict: {repr(meta)}\")\n        return None\n    m = cache_meta_from_dict(meta, data_json)\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\n    # Don't check for path match, that is dealt with in validate_meta().\n    if (\n        m.id != id\n        or m.mtime is None\n        or m.size is None\n        or m.dependencies is None\n        or m.data_mtime is None\n    ):\n        manager.log(f\"Metadata abandoned for {id}: attributes are missing\")\n        return None\n\n    # Ignore cache if generated by an older mypy version.\n    if (\n        (m.version_id != manager.version_id and not manager.options.skip_version_check)\n        or m.options is None\n        or len(m.dependencies) + len(m.suppressed) != len(m.dep_prios)\n        or len(m.dependencies) + len(m.suppressed) != len(m.dep_lines)\n    ):\n        manager.log(f\"Metadata abandoned for {id}: new attributes are missing\")\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 = manager.options.clone_for_module(id).select_options_affecting_cache()\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    # 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(\n        json_dumps(manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=True)))\n    )\n    if m.plugin_data != plugin_data:\n        manager.log(f\"Metadata abandoned for {id}: plugin configuration differs\")\n        return None\n\n    baseline_hash = None\n    baseline_errors = manager.errors.baseline.get(path)\n    if baseline_errors:\n        errors = [\n            {\n                \"code\": error[\"code\"],\n                \"column\": error[\"column\"],\n                \"line\": error[\"line\"],\n                \"message\": error[\"message\"],\n            }\n            for error in baseline_errors\n        ]\n        baseline_hash = hash_digest(json.dumps(errors).encode())\n    if baseline_hash != m.baseline_hash:\n        manager.log(f\"Metadata abandoned for {id}: baseline is different\")\n        return None\n    if baseline_errors:\n        manager.errors.all_errors[path] = \"fresh\"\n\n    manager.add_stats(fresh_metas=1)\n    return m\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    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_json; assume if its mtime matches it's good.\n        try:\n            data_mtime = manager.getmtime(meta.data_json)\n        except OSError:\n            manager.log(f\"Metadata abandoned for {id}: failed to stat data_json\")\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    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 = meta._replace(mtime=mtime, 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            t0 = time.time()\n            # Optimization: update mtime and path (otherwise, this mismatch will reappear).\n            meta = meta._replace(mtime=mtime, path=path)\n            # Construct a dict we can pass to json.dumps() (compare to write_cache()).\n            meta_dict = {\n                \"id\": id,\n                \"path\": path,\n                \"mtime\": mtime,\n                \"size\": size,\n                \"hash\": source_hash,\n                \"data_mtime\": meta.data_mtime,\n                \"dependencies\": meta.dependencies,\n                \"suppressed\": meta.suppressed,\n                \"options\": (manager.options.clone_for_module(id).select_options_affecting_cache()),\n                \"dep_prios\": meta.dep_prios,\n                \"dep_lines\": meta.dep_lines,\n                \"interface_hash\": meta.interface_hash,\n                \"version_id\": manager.version_id,\n                \"ignore_all\": meta.ignore_all,\n                \"plugin_data\": meta.plugin_data,\n            }\n            meta_bytes = json_dumps(meta_dict, manager.options.debug_cache)\n            meta_json, _, _ = get_cache_names(id, path, manager.options)\n            manager.log(\n                \"Updating mtime for {}: file {}, meta {}, mtime {}\".format(\n                    id, path, meta_json, meta.mtime\n                )\n            )\n            t1 = time.time()\n            manager.metastore.write(meta_json, meta_bytes)  # Ignore errors, just an optimization.\n            manager.add_stats(validate_update_time=time.time() - t1, validate_munging_time=t1 - t0)\n            return meta\n\n    # It's a match on (id, path, size, hash, mtime).\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    dep_prios: list[int],\n    dep_lines: list[int],\n    old_interface_hash: str,\n    source_hash: str,\n    ignore_all: bool,\n    manager: BuildManager,\n    baseline_errors: list[ErrorInfo] | None,\n) -> tuple[str, CacheMeta | 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 CacheMeta\n      corresponding to the metadata that was written (the latter may\n      be None if the cache 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_json, data_json, _ = get_cache_names(id, path, manager.options)\n    manager.log(f\"Writing {id} {path} {meta_json} {data_json}\")\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    # Serialize data and analyze interface\n    data = tree.serialize()\n    data_bytes = json_dumps(data, manager.options.debug_cache)\n    interface_hash = hash_digest(data_bytes)\n\n    plugin_data = manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=False))\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_json, meta_json]:\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_json, 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 data JSON file {data_json}\")\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_json)\n    except OSError:\n        manager.log(f\"Error in os.stat({data_json!r}), skipping cache write\")\n        return interface_hash, None\n\n    baseline_hash = None\n    if baseline_errors:\n        errors = [\n            {\n                \"code\": error.code and error.code.code,\n                \"column\": error.column,\n                \"line\": error.line,\n                \"message\": error.message,\n            }\n            for error in baseline_errors\n        ]\n        baseline_hash = hash_digest(json.dumps(errors).encode())\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    options = manager.options.clone_for_module(id)\n    assert source_hash is not None\n    meta = {\n        \"id\": id,\n        \"path\": path,\n        \"mtime\": mtime,\n        \"size\": size,\n        \"hash\": source_hash,\n        \"data_mtime\": data_mtime,\n        \"dependencies\": dependencies,\n        \"suppressed\": suppressed,\n        \"options\": options.select_options_affecting_cache(),\n        \"dep_prios\": dep_prios,\n        \"dep_lines\": dep_lines,\n        \"interface_hash\": interface_hash,\n        \"version_id\": manager.version_id,\n        \"ignore_all\": ignore_all,\n        \"plugin_data\": plugin_data,\n        \"baseline_hash\": baseline_hash,\n    }\n\n    # Write meta cache file\n    meta_str = json_dumps(meta, manager.options.debug_cache)\n    if not metastore.write(meta_json, meta_str):\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 meta JSON file {meta_json}\")\n\n    return interface_hash, cache_meta_from_dict(meta, data_json)\n\n\ndef delete_cache(id: str, path: str, manager: BuildManager) -> None:\n    \"\"\"Delete cache files for a module.\n\n    The cache files for a module are deleted when mypy finds errors there.\n    This avoids inconsistent states with cache files from different mypy runs,\n    see #4043 for an example.\n    \"\"\"\n    # We don't delete .deps files on errors, since the dependencies\n    # are mostly generated from other files and the metadata is\n    # tracked separately.\n    meta_path, data_path, _ = get_cache_names(id, path, manager.options)\n    cache_paths = [meta_path, data_path]\n    manager.log(f\"Deleting {id} {path} {' '.join(x for x in cache_paths if x)}\")\n\n    for filename in cache_paths:\n        try:\n            manager.metastore.remove(filename)\n        except OSError as e:\n            if e.errno != errno.ENOENT:\n                manager.log(f\"Error deleting cache file {filename}: {e.strerror}\")\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.  We also handle (c)\nabove; if a module has valid cache data *but* any of its\ndependencies was processed from source, then the module should be\nprocessed from source.\n\nA relatively simple optimization (outside SCCs) we might do in the\nfuture is as follows: if a node's cache data is valid, but one or more\nof its dependencies are out of date so we have to re-parse the node\nfrom source, once we have fully type-checked the node, we can decide\nwhether its symbol table actually changed compared to the cache data\n(by reading the cache data and comparing it to the data we would be\nwriting).  If there is no change we can declare the node up to date,\nand any node that depends (and for which we have cached data, and\nwhose other dependencies are up to date) on it won't need to be\nre-parsed from source.\n\nImport cycles\n-------------\n\nFinally we have to decide how to handle (c), 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 ModuleNotFound(Exception):\n    \"\"\"Control flow exception to signal that a module was not found.\"\"\"\n\n\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    data: str | 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    # 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    # The State from which this module was imported, if any\n    caller_state: State | None = None\n\n    # If caller_state is set, the line number in the caller where the import occurred\n    caller_line = 0\n\n    # If True, indicate that the public interface of this module is unchanged\n    externally_same = True\n\n    # Contains a hash of the public interface in incremental mode\n    interface_hash: str = \"\"\n\n    # Options, specialized for this file\n    options: Options\n\n    # Whether to ignore all errors\n    ignore_all = False\n\n    # Whether the module has an error or any of its dependencies have one.\n    transitive_error = 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    def __init__(\n        self,\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    ) -> None:\n        if not temporary:\n            assert id or path or source is not None, \"Neither id, path nor source given\"\n        self.manager = manager\n        State.order_counter += 1\n        self.order = State.order_counter\n        self.caller_state = caller_state\n        self.caller_line = caller_line\n        if caller_state:\n            self.import_context = caller_state.import_context.copy()\n            self.import_context.append((caller_state.xpath, caller_line))\n        else:\n            self.import_context = []\n        self.id = id or \"__main__\"\n        self.options = manager.options.clone_for_module(self.id)\n        self.early_errors = []\n        self._type_checker = None\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                    self.options,\n                    caller_state,\n                    caller_line,\n                    ancestor_for,\n                    root_source,\n                    skip_diagnose=temporary,\n                )\n            except ModuleNotFound:\n                if not temporary:\n                    manager.missing_modules.add(id)\n                raise\n            if follow_imports == \"silent\":\n                self.ignore_all = True\n        elif path and is_silent_import_module(manager, path) and not root_source:\n            self.ignore_all = True\n        self.path = path\n        if path:\n            self.abspath = os.path.abspath(path)\n        self.xpath = path or \"<string>\"\n        if path and source is None and self.manager.cache_enabled:\n            self.meta = find_cache_meta(self.id, path, manager)\n            # TODO: Get mtime if not cached.\n            if self.meta is not None:\n                self.interface_hash = self.meta.interface_hash\n                self.meta_source_hash = self.meta.hash\n        if path and source is None and self.manager.fscache.isdir(path):\n            source = \"\"\n        self.source = source\n        self.add_ancestors()\n        self.per_line_checking_time_ns = collections.defaultdict(int)\n        t0 = time.time()\n        self.meta = validate_meta(self.meta, self.id, self.path, self.ignore_all, manager)\n        self.manager.add_stats(validate_meta_time=time.time() - t0)\n        if self.meta:\n            # Make copies, since we may modify these and want to\n            # compare them to the originals later.\n            self.dependencies = list(self.meta.dependencies)\n            self.dependencies_set = set(self.dependencies)\n            self.suppressed = list(self.meta.suppressed)\n            self.suppressed_set = set(self.suppressed)\n            all_deps = self.dependencies + self.suppressed\n            assert len(all_deps) == len(self.meta.dep_prios)\n            self.priorities = {id: pri for id, pri in zip(all_deps, self.meta.dep_prios)}\n            assert len(all_deps) == len(self.meta.dep_lines)\n            self.dep_line_map = {id: line for id, line in zip(all_deps, self.meta.dep_lines)}\n            if temporary:\n                self.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(self.suppressed, manager, self.options):\n                    self.parse_file()  # This is safe because the cache is anyway stale.\n                    self.compute_dependencies()\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            self.parse_file(temporary=temporary)\n            self.compute_dependencies()\n\n    @property\n    def xmeta(self) -> CacheMeta:\n        assert self.meta, \"missing meta on allegedly fresh module\"\n        return self.meta\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        return (\n            self.meta is not None\n            and self.is_interface_fresh()\n            and self.dependencies == self.meta.dependencies\n        )\n\n    def is_interface_fresh(self) -> bool:\n        return self.externally_same\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, *, on_errors: bool = False) -> None:\n        \"\"\"Marks this module as having a stale public interface, and discards the cache data.\"\"\"\n        self.externally_same = False\n        if not on_errors:\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        assert (\n            self.meta is not None\n        ), \"Internal error: this method must be called only for cached modules\"\n\n        data = _load_json_file(\n            self.meta.data_json, self.manager, \"Load tree \", \"Could not load tree: \"\n        )\n        if data is None:\n            return\n\n        t0 = time.time()\n        # TODO: Assert data file wasn't changed.\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        if self.id == \"typing\":\n            # For cringe reasons, we extract Callable as soon as it's loaded\n            from mypy import typeanal\n            from mypy.types import Instance\n\n            typeanal.CALLABLE_TYPE = Instance(cast(TypeInfo, self.tree.names[\"Callable\"].node), [])\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) -> 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            self.source = None  # We won't need it again.\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: can't 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\"mypy: stubgen does not support .pyd files: '{self.path}'\"\n                    else:\n                        err = f\"mypy: can't decode file '{self.path}': {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            if not cached:\n                self.tree = manager.parse_file(\n                    self.id,\n                    self.xpath,\n                    source,\n                    ignore_errors=self.ignore_all or self.options.ignore_errors,\n                    options=self.options,\n                )\n\n            else:\n                # Reuse a cached AST\n                self.tree = manager.ast_cache[self.id][0]\n                manager.errors.set_file_ignored_lines(\n                    self.xpath,\n                    self.tree.ignored_lines,\n                    self.ignore_all or self.options.ignore_errors,\n                )\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        else:\n            self.early_errors = manager.ast_cache[self.id][1]\n\n        if not temporary:\n            modules[self.id] = self.tree\n\n        if not cached:\n            self.semantic_analysis_pass1()\n\n        if not temporary:\n            self.check_blockers()\n\n        manager.ast_cache[self.id] = (self.tree, self.early_errors)\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.errors.report(lineno, 0, error)\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        analyzer = SemanticAnalyzerPreAnalysis()\n        with self.wrap_context():\n            analyzer.visit_file(self.tree, self.xpath, self.id, options)\n        self.manager.errors.set_skipped_lines(self.xpath, self.tree.skipped_lines)\n        # TODO: Do this while constructing the AST?\n        self.tree.names = SymbolTable()\n        if not self.tree.is_stub:\n            # Always perform some low-key variable renaming\n            self.tree.accept(LimitedVariableRenameVisitor())\n            if options.allow_redefinition:\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        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        # Every module implicitly depends on builtins.\n        if self.id != \"builtins\":\n            self.add_dependency(\"builtins\")\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            # TODO: find a more robust way to traverse *all* relevant types?\n            all_types = list(self.type_map().values())\n            for _, sym, _ in self.tree.local_definitions():\n                if sym.type is not None:\n                    all_types.append(sym.type)\n                if isinstance(sym.node, TypeInfo):\n                    # TypeInfo symbols have some extra relevant types.\n                    all_types.extend(sym.node.bases)\n                    if sym.node.metaclass_type:\n                        all_types.append(sym.node.metaclass_type)\n                    if sym.node.typeddict_type:\n                        all_types.append(sym.node.typeddict_type)\n                    if sym.node.tuple_type:\n                        all_types.append(sym.node.tuple_type)\n            self._patch_indirect_dependencies(self.type_checker().module_refs, all_types)\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.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: list[Type]) -> None:\n        assert None not in types\n        valid = self.valid_references()\n\n        encountered = self.manager.indirection_detector.find_modules(types) | module_refs\n        extra = encountered - valid\n\n        for dep in sorted(extra):\n            if dep not in self.manager.modules:\n                continue\n            if dep not in self.suppressed_set and dep not in self.manager.missing_modules:\n                self.add_dependency(dep)\n                self.priorities[dep] = PRI_INDIRECT\n            elif dep not in self.suppressed_set and dep in self.manager.missing_modules:\n                self.suppress_dependency(dep)\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 valid_references(self) -> set[str]:\n        assert self.ancestors is not None\n        valid_refs = set(self.dependencies + self.suppressed + self.ancestors)\n        valid_refs.add(self.id)\n\n        if \"os\" in valid_refs:\n            valid_refs.add(\"os.path\")\n\n        return valid_refs\n\n    def write_cache(self, *, baseline_errors: list[ErrorInfo] | None) -> 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                    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\n        is_errors = self.transitive_error\n        if is_errors:\n            delete_cache(self.id, self.path, self.manager)\n            self.meta = None\n            self.mark_interface_stale(on_errors=True)\n            return\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, self.meta = write_cache(\n            self.id,\n            self.path,\n            self.tree,\n            list(self.dependencies),\n            list(self.suppressed),\n            dep_prios,\n            dep_lines,\n            self.interface_hash,\n            self.source_hash,\n            self.ignore_all,\n            self.manager,\n            baseline_errors,\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\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        if suppressed_only:\n            all_deps = self.suppressed\n        else:\n            # Strip out indirect dependencies. See comment in build.load_graph().\n            dependencies = [\n                dep for dep in self.dependencies if self.priorities.get(dep) != PRI_INDIRECT\n            ]\n            all_deps = dependencies + self.suppressed + 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            # If this file was initially loaded from the cache, it may have suppressed\n            # dependencies due to imports with ignores on them. We need to generate\n            # those errors to avoid spuriously flagging them as unused ignores.\n            if self.meta:\n                self.verify_dependencies(suppressed_only=True)\n            self.manager.errors.generate_unused_ignore_errors(self.xpath)\n\n    def generate_ignore_without_code_notes(self) -> None:\n        if self.manager.errors.is_error_code_enabled(codes.IGNORE_WITHOUT_CODE):\n            self.manager.errors.generate_ignore_without_code_errors(\n                self.xpath, self.options.warn_unused_ignores\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            raise ModuleNotFound\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, options: Options) -> 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        if options.follow_imports == \"skip\" and (\n            not path.endswith(\".pyi\") or options.follow_imports_for_stubs\n        ):\n            continue\n        if \"__init__.py\" in path:\n            # It is better to have a bit lenient test, this will only slightly reduce\n            # performance, while having a too strict test may affect correctness.\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    t0 = time.time()\n    x = manager.find_module_cache.find_module(id, fast_path=True)\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    t0 = time.time()\n    x = manager.find_module_cache.find_module(id, fast_path=False)\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        parent, _ = id.rsplit(\".\", 1)\n        if parent in manager.modules:\n            parent_mod: MypyFile | None = manager.modules[parent]\n        else:\n            # Parent is not in build, try quickly if we can find it.\n            try:\n                parent_st = State(\n                    id=parent, path=None, source=None, manager=manager, temporary=True\n                )\n            except (ModuleNotFound, CompileError):\n                parent_mod = None\n            else:\n                parent_mod = parent_st.tree\n        if parent_mod is not None:\n            # Bail out soon, complete subpackage found\n            return parent_mod.is_partial_stub_package\n        id = parent\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    if target == \"builtins\":\n        errors.report(\n            line, 0, \"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        errors.report(line, 0, 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            errors.report(line, 0, note, severity=\"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.errors.report(line, 0, f'Import of \"{id}\" ignored', severity=\"error\")\n    manager.errors.report(\n        line,\n        0,\n        \"(Using --follow-imports=error, module not passed on command line)\",\n        severity=\"note\",\n        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.errors.report(\n        -1, -1, f'Ancestor package \"{id}\" ignored', severity=\"error\", only_once=True\n    )\n    manager.errors.report(\n        -1,\n        -1,\n        \"(Using --follow-imports=error, submodule passed on command line)\",\n        severity=\"note\",\n        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    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        (\"Basedmypy Version\", __based_version__),\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    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    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 baseline\n        save_baseline(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)\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(\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.errors.report(\n                -1,\n                -1,\n                f'Duplicate module named \"{st.id}\" (also at \"{graph[st.id].xpath}\")',\n                blocker=True,\n            )\n            manager.errors.report(\n                -1,\n                -1,\n                \"See https://kotlinisland.github.io/basedmypy/running_mypy.html#mapping-file-paths-to-modules \"\n                \"for more info\",\n                severity=\"note\",\n            )\n            manager.errors.report(\n                -1,\n                -1,\n                \"Common resolutions include: a) using `--exclude` to avoid checking one of them, \"\n                \"b) adding `__init__.py` somewhere, c) using `--explicit-package-bases` or \"\n                \"adjusting MYPYPATH\",\n                severity=\"note\",\n            )\n\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            # TODO: Ideally we could skip here modules that appeared in st.suppressed\n            # because they are not in build with `follow-imports=skip`.\n            # This way we could avoid overhead of cloning options in `State.__init__()`\n            # below to get the option value. This is quite minor performance loss however.\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.__init__()`.\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.add(dep)\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(\n                            id=dep, path=None, source=None, manager=manager, ancestor_for=st\n                        )\n                    else:\n                        newst = 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 = os.path.abspath(newst.path)\n\n                        if newst_path in seen_files:\n                            manager.errors.report(\n                                -1,\n                                0,\n                                \"Source file found twice under different module names: \"\n                                '\"{}\" and \"{}\"'.format(seen_files[newst_path].id, newst.id),\n                                blocker=True,\n                            )\n                            manager.errors.report(\n                                -1,\n                                0,\n                                \"See https://kotlinisland.github.io/basedmypy/running_mypy.html#mapping-file-paths-to-modules \"\n                                \"for more info\",\n                                severity=\"note\",\n                            )\n                            manager.errors.report(\n                                -1,\n                                0,\n                                \"Common resolutions include: a) adding `__init__.py` somewhere, \"\n                                \"b) using `--explicit-package-bases` or adjusting MYPYPATH\",\n                                severity=\"note\",\n                            )\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            if dep in graph and dep in st.suppressed_set:\n                # Previously suppressed file is now visible\n                st.add_dependency(dep)\n    manager.plugin.set_modules(manager.modules)\n    return graph\n\n\ndef process_graph(graph: Graph, manager: BuildManager) -> None:\n    \"\"\"Process everything in dependency order.\"\"\"\n    sccs = sorted_components(graph)\n    manager.log(\"Found %d SCCs; largest has %d nodes\" % (len(sccs), max(len(scc) for scc in sccs)))\n\n    fresh_scc_queue: list[list[str]] = []\n\n    # We're processing SCCs from leaves (those without further\n    # dependencies) to roots (those from which everything else can be\n    # reached).\n    for ascc in sccs:\n        # Order the SCC's nodes using a heuristic.\n        # Note that ascc is a set, and scc is a list.\n        scc = order_ascc(graph, ascc)\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:\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        if manager.options.verbosity >= 2:\n            for id in scc:\n                manager.trace(\n                    f\"Priorities for {id}:\",\n                    \" \".join(\n                        \"%s:%d\" % (x, graph[id].priorities[x])\n                        for x in graph[id].dependencies\n                        if x in ascc and x in graph[id].priorities\n                    ),\n                )\n        # Because the SCCs are presented in topological sort order, we\n        # don't need to look at dependencies recursively for staleness\n        # -- the immediate dependencies are sufficient.\n        stale_scc = {id for id in scc if not graph[id].is_fresh()}\n        fresh = not stale_scc\n        deps = set()\n        for id in scc:\n            deps.update(graph[id].dependencies)\n        deps -= ascc\n        stale_deps = {id for id in deps if id in graph and not graph[id].is_interface_fresh()}\n        fresh = fresh and not stale_deps\n        undeps = set()\n        if fresh:\n            # Check if any dependencies that were suppressed according\n            # to the cache have been added back in this run.\n            # NOTE: Newly suppressed dependencies are handled by is_fresh().\n            for id in scc:\n                undeps.update(graph[id].suppressed)\n            undeps &= graph.keys()\n            if undeps:\n                fresh = False\n        if fresh:\n            # All cache files are fresh.  Check that no dependency's\n            # cache file is newer than any scc node's cache file.\n            oldest_in_scc = min(graph[id].xmeta.data_mtime for id in scc)\n            viable = {id for id in stale_deps if graph[id].meta is not None}\n            newest_in_deps = (\n                0 if not viable else max(graph[dep].xmeta.data_mtime for dep in viable)\n            )\n            if manager.options.verbosity >= 3:  # Dump all mtimes for extreme debugging.\n                all_ids = sorted(ascc | viable, key=lambda id: graph[id].xmeta.data_mtime)\n                for id in all_ids:\n                    if id in scc:\n                        if graph[id].xmeta.data_mtime < newest_in_deps:\n                            key = \"*id:\"\n                        else:\n                            key = \"id:\"\n                    else:\n                        if graph[id].xmeta.data_mtime > oldest_in_scc:\n                            key = \"+dep:\"\n                        else:\n                            key = \"dep:\"\n                    manager.trace(\" %5s %.0f %s\" % (key, graph[id].xmeta.data_mtime, id))\n            # If equal, give the benefit of the doubt, due to 1-sec time granularity\n            # (on some platforms).\n            if oldest_in_scc < newest_in_deps:\n                fresh = False\n                fresh_msg = f\"out of date by {newest_in_deps - oldest_in_scc:.0f} seconds\"\n            else:\n                fresh_msg = \"fresh\"\n        elif undeps:\n            fresh_msg = f\"stale due to changed suppression ({' '.join(sorted(undeps))})\"\n        elif stale_scc:\n            fresh_msg = \"inherently stale\"\n            if stale_scc != ascc:\n                fresh_msg += f\" ({' '.join(sorted(stale_scc))})\"\n            if stale_deps:\n                fresh_msg += f\" with stale deps ({' '.join(sorted(stale_deps))})\"\n        else:\n            fresh_msg = f\"stale due to deps ({' '.join(sorted(stale_deps))})\"\n\n        # Initialize transitive_error for all SCC members from union\n        # of transitive_error of dependencies.\n        if any(graph[dep].transitive_error for dep in deps if dep in graph):\n            for id in scc:\n                graph[id].transitive_error = True\n\n        scc_str = \" \".join(scc)\n        if fresh:\n            manager.trace(f\"Queuing {fresh_msg} SCC ({scc_str})\")\n            fresh_scc_queue.append(scc)\n        else:\n            if fresh_scc_queue:\n                manager.log(f\"Processing {len(fresh_scc_queue)} queued fresh SCCs\")\n                # Defer processing fresh SCCs until we actually run into a stale SCC\n                # and need the earlier modules to be loaded.\n                #\n                # Note that `process_graph` may end with us not having processed every\n                # single fresh SCC. This is intentional -- we don't need those modules\n                # loaded if there are no more stale SCCs to be rechecked.\n                #\n                # Also note we shouldn't have to worry about transitive_error here,\n                # since modules with transitive errors aren't written to the cache,\n                # and if any dependencies were changed, this SCC would be stale.\n                # (Also, in quick_and_dirty mode we don't care about transitive errors.)\n                #\n                # TODO: see if it's possible to determine if we need to process only a\n                # _subset_ of the past SCCs instead of having to process them all.\n                for prev_scc in fresh_scc_queue:\n                    process_fresh_modules(graph, prev_scc, manager)\n                fresh_scc_queue = []\n            size = len(scc)\n            if size == 1:\n                manager.log(f\"Processing SCC singleton ({scc_str}) as {fresh_msg}\")\n            else:\n                manager.log(\"Processing SCC of size %d (%s) as %s\" % (size, scc_str, fresh_msg))\n            process_stale_scc(graph, scc, manager)\n\n    sccs_left = len(fresh_scc_queue)\n    nodes_left = sum(len(scc) for scc in fresh_scc_queue)\n    manager.add_stats(sccs_left=sccs_left, nodes_left=nodes_left)\n    if sccs_left:\n        manager.log(\n            \"{} fresh SCCs ({} nodes) left in queue (and will remain unprocessed)\".format(\n                sccs_left, nodes_left\n            )\n        )\n        manager.trace(str(fresh_scc_queue))\n    else:\n        manager.log(\"No fresh SCCs left in queue\")\n\n\ndef order_ascc(graph: Graph, ascc: AbstractSet[str], pri_max: int = PRI_ALL) -> 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(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\n    This involves loading the tree from JSON and then doing various cleanups.\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(graph: Graph, scc: list[str], manager: BuildManager) -> None:\n    \"\"\"Process the modules in one SCC from source code.\n\n    Exception: If quick_and_dirty is set, use the cache for fresh modules.\n    \"\"\"\n    stale = scc\n    for id in stale:\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    # 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    for id in stale:\n        manager.errors.filter_baseline_pre(graph[id].xpath)\n    if any(manager.errors.is_errors_for_file(graph[id].xpath) for id in stale):\n        for id in stale:\n            graph[id].transitive_error = True\n    for id in stale:\n        file = graph[id].xpath\n        if file not in manager.errors.ignored_files:\n            errors = manager.errors.file_messages(file, formatter=manager.error_formatter)\n            manager.flush_errors(manager.errors.simplify_path(file), errors, False)\n        all_errors = manager.errors.all_errors.get(file)\n        if all_errors == \"fresh\":\n            raise ValueError(\"huh?\")\n        if file in manager.errors.ignored_files:\n            all_errors = None\n        # here, the `all_errors` will only be cached if not `transitive_error`, so `all_errors` is baselined errors\n        graph[id].write_cache(baseline_errors=all_errors)\n        graph[id].mark_as_rechecked()\n\n\ndef sorted_components(\n    graph: Graph, vertices: AbstractSet[str] | None = None, pri_max: int = PRI_ALL\n) -> list[AbstractSet[str]]:\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    This works for a subset of the full dependency graph too;\n    dependencies that aren't present in graph.keys() are ignored.\n    \"\"\"\n    # Compute SCCs.\n    if vertices is None:\n        vertices = set(graph)\n    edges = {id: deps_filtered(graph, vertices, id, pri_max) for id in vertices}\n    sccs = list(strongly_connected_components(vertices, edges))\n    # Topsort.\n    res = []\n    for ready in topsort(prepare_sccs(sccs, edges)):\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        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 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"
  },
  {
    "path": "mypy/checker.py",
    "content": "\"\"\"Mypy type checker.\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nfrom collections import defaultdict\nfrom collections.abc import Iterable, Iterator, Mapping, Sequence, Set as AbstractSet\nfrom contextlib import ExitStack, contextmanager\nfrom typing import Callable, Final, Generic, NamedTuple, Optional, TypeVar, Union, cast, overload\nfrom typing_extensions import TypeAlias as _TypeAlias\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.checkexpr import has_untyped_type\nfrom mypy.checkmember import (\n    MemberContext,\n    analyze_decorator_or_funcbase_access,\n    analyze_descriptor_access,\n    analyze_member_access,\n    type_object_type,\n)\nfrom mypy.checkpattern import PatternChecker\nfrom mypy.constraints import SUPERTYPE_OF\nfrom mypy.erasetype import erase_type, erase_typevars, remove_instance_last_known_values\nfrom mypy.errorcodes import TYPE_VAR, UNUSED_AWAITABLE, UNUSED_COROUTINE, ErrorCode\nfrom mypy.errors import Errors, ErrorWatcher, report_internal_error\nfrom mypy.expandtype import expand_self_type, expand_type, expand_type_by_instance\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 (\n    is_overlapping_erased_types,\n    is_overlapping_types,\n    meet_types,\n    narrow_declared_type,\n)\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    AssertStmt,\n    AssignmentExpr,\n    AssignmentStmt,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    ClassDef,\n    ComparisonExpr,\n    Context,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    ForStmt,\n    FuncBase,\n    FuncDef,\n    FuncItem,\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    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    PassStmt,\n    PromoteExpr,\n    RaiseStmt,\n    RefExpr,\n    ReturnStmt,\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    TypeVarExpr,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\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 CheckerPluginInterface, 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.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 (\n    CALLABLE_NAME,\n    check_for_explicit_any,\n    has_any_from_unimported_type,\n    make_optional_type,\n)\nfrom mypy.typeops import (\n    bind_self,\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    get_type_type_item,\n    is_literal_type_like,\n    is_singleton_type,\n    make_simplified_intersection,\n    make_simplified_union,\n    map_type_from_supertype,\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)\nfrom mypy.types import (\n    ANY_STRATEGY,\n    MYPYC_NATIVE_INT_NAMES,\n    OVERLOAD_NAMES,\n    AnyType,\n    BoolTypeQuery,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FunctionLike,\n    Instance,\n    IntersectionType,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeTranslator,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    UntypedType,\n    find_unpack_in_list,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n    is_literal_type,\n    is_named_instance,\n    is_unannotated_any,\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, safe\nfrom mypy.visitor import NodeVisitor\n\nT = TypeVar(\"T\")\n\nDEFAULT_LAST_PASS: Final = 1  # 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 = Union[FuncDef, LambdaExpr, OverloadedFuncDef, Decorator]\nFineGrainedDeferredNodeType: _TypeAlias = Union[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# and 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 = Optional[dict[Expression, Type]]\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# 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 InvalidTypeType(Exception):\n    \"\"\"For when an invalid TypeType appears.\"\"\"\n\n\nclass TypeChecker(NodeVisitor[None], CheckerPluginInterface):\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    # 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    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\n    # The set of all dependencies (suppressed or not) that this module accesses, either\n    # directly or indirectly.\n    module_refs: set[str]\n\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    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()\n        self.globals = tree.names\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._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\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        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        # 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        self.pattern_checker = PatternChecker(self, self.msg, self.plugin, options)\n\n        # always allow the next if statement to have a redundant expression\n        self.allow_redundant_expr = False\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()\n        self._type_maps[1:] = []\n        self._type_maps[0].clear()\n        self.temp_type_map = None\n        self.expr_checker.reset()\n\n        assert self.inferred_attribute_types is None\n        assert self.partial_types == []\n        assert self.deferred_nodes == []\n        assert len(self.scope.stack) == 1\n        assert self.partial_types == []\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):\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, todo: Sequence[DeferredNode | FineGrainedDeferredNode] | None = None\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.recurse_into_functions = True\n        with state.strict_optional_set(self.options.strict_optional):\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        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                if isinstance(node, LambdaExpr):\n                    self.expr_checker.accept(node)\n                else:\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_non_lambda_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()\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    ) -> 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\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\n            # Disable error types that we cannot safely identify in intermediate iteration steps:\n            warn_unreachable = self.options.warn_unreachable\n            warn_redundant = codes.REDUNDANT_EXPR in self.options.enabled_error_codes\n            self.options.warn_unreachable = False\n            self.options.enabled_error_codes.discard(codes.REDUNDANT_EXPR)\n\n            allow_redundant_expr = self.allow_redundant_expr\n\n            while True:\n                self.allow_redundant_expr = allow_redundant_expr\n                with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1):\n                    self.accept(body)\n                partials_new = sum(len(pts.map) for pts in self.partial_types)\n                if (partials_new == partials_old) and not self.binder.last_pop_changed:\n                    break\n                partials_old = partials_new\n\n            # If necessary, reset the modified options and make up for the postponed error checks:\n            self.options.warn_unreachable = warn_unreachable\n            if warn_redundant:\n                self.options.enabled_error_codes.add(codes.REDUNDANT_EXPR)\n            if warn_unreachable or warn_redundant:\n                self.allow_redundant_expr = allow_redundant_expr\n                with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1):\n                    self.accept(body)\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, do_items=True) -> None:\n        if not self.recurse_into_functions:\n            return\n        with self.tscope.function_scope(defn):\n            self._visit_overloaded_func_def(defn, do_items)\n\n    def _visit_overloaded_func_def(self, defn: OverloadedFuncDef, do_items=True) -> 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 do_items:\n            for fdef in defn.items:\n                assert isinstance(fdef, Decorator)\n                if defn.is_property:\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            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_types.append(item_type)\n                if item_types:\n                    defn.type = Overloaded(item_types)\n        # Check override validity after we analyzed current definition.\n        if 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            ):\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    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: CallableType | None = None\n        if inner_type is not None and not isinstance(inner_type, AnyType):\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, CallableType):\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                        msg=self.msg,\n                        original_type=inner_type,\n                        chk=self,\n                    )\n                )\n                if isinstance(inner_call, CallableType):\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, CallableType):\n                            outer_type = joined_type\n                else:\n                    return self.extract_callable_type(union_type, ctx)\n            if outer_type is None:\n                self.msg.not_callable(inner_type, ctx)\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.msg.errors.file in self.msg.errors.ignored_files or (\n            self.is_typeshed_stub and self.options.test_env\n        ):\n            # This is a little hacky, however, the quadratic check here is really expensive, this\n            # method has no side effects, so we should skip it if we aren't going to report\n            # anything. In some other places we swallow errors in stubs, but this error is very\n            # useful for stubs!\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            if impl_type and isinstance(defn.type, FunctionLike):\n                defn.type.fallback = impl_type.fallback\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                impl.fallback = sig1.fallback\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_arg_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:\n            return\n        # If possible, transform def into an overload from super information\n        #  This is intentionally disabled for now (it should be moved to semanal I think)\n        # if defn.info and not defn.is_overload and (\n        #     # if it's fully annotated then we allow the invalid override\n        #     not (defn.type and isinstance(defn.type, CallableType) and defn.type.fully_typed)\n        #     or not defn.unanalyzed_type\n        #\n        #     or (defn.unanalyzed_type and isinstance(defn.unanalyzed_type, CallableType) and (\n        #         is_unannotated_any(defn.unanalyzed_type.ret_type)\n        #         or any(is_unannotated_any(typ) for typ in defn.unanalyzed_type.arg_types[1:])\n        #     ))\n        # ) and self.options.infer_function_types:\n        #     for base in defn.info.mro[1:]:\n        #         super_ = base.names.get(defn.name)\n        #         if not super_ or not isinstance(super_.node, OverloadedFuncDef):\n        #             continue\n        #         super_type = get_proper_type(super_.type)\n        #         assert isinstance(super_type, Overloaded)\n        #         if super_.node.impl:\n        #             super_types = {\n        #                 arg: arg_type\n        #                 for arg, arg_type in zip(\n        #                     (\n        #                         super_.node.impl\n        #                         if isinstance(super_.node.impl, FuncDef)\n        #                         else super_.node.impl.func\n        #                     ).arg_names,\n        #                     cast(CallableType, super_.node.impl.type).arg_types,\n        #                 )\n        #             }\n        #         else:\n        #             super_types = {}\n        #         item_arg_types: Dict[str, List[Type]] = defaultdict(list)\n        #         item_ret_types = []\n        #         for item in super_.node.items:\n        #             assert isinstance(item, Decorator)\n        #             if not isinstance(item.func.type, CallableType):\n        #                 continue\n        #             for arg, arg_type in zip(item.func.arg_names, item.func.type.arg_types):\n        #                 if not arg:\n        #                     continue\n        #                 if arg not in super_types and arg in defn.arg_names:\n        #                     if arg_type not in item_arg_types[arg]:\n        #                         item_arg_types[arg].append(arg_type)\n        #             if item.func.type.ret_type not in item_ret_types:\n        #                 item_ret_types.append(item.func.type.ret_type)\n        #         super_types.update({\n        #           arg: UnionType.make_union(arg_type) for arg, arg_type in item_arg_types.items()\n        #         })\n        #         any_ = UntypedType()\n        #         if defn.unanalyzed_type and super_.node.impl:\n        #             assert isinstance(defn.unanalyzed_type, CallableType)\n        #             assert isinstance(defn.type, CallableType)\n        #             t = get_proper_type(super_.node.impl.type)\n        #             assert isinstance(t, CallableType)\n        #             ret_type = (\n        #                 defn.type.ret_type\n        #                 if not is_unannotated_any(defn.unanalyzed_type.ret_type)\n        #                 else t.ret_type\n        #             )\n        #         elif super_.node.impl:\n        #             t = get_proper_type(super_.node.impl.type)\n        #             assert isinstance(t, CallableType)\n        #             ret_type = t.ret_type\n        #         elif item_ret_types:\n        #             ret_type = UnionType.make_union(item_ret_types)\n        #         else:\n        #             ret_type = any_\n        #         if not defn.type:\n        #             defn.type = self.function_type(defn)\n        #         assert isinstance(defn.type, CallableType)\n        #         arg_types = [defn.type.arg_types[0]]\n        #         if defn.unanalyzed_type:\n        #             assert isinstance(defn.unanalyzed_type, CallableType)\n        #             arg_types.extend([\n        #                 arg_type\n        #                 if not is_unannotated_any(unanalyzed)\n        #                 else super_types.get(arg, any_)\n        #                 for arg, arg_type, unanalyzed in zip(\n        #                     defn.arg_names[1:],\n        #                     defn.type.arg_types[1:],\n        #                     defn.unanalyzed_type.arg_types[1:]\n        #                 )\n        #             ])\n        #         else:\n        #             arg_types.extend([super_types.get(arg, any_) for arg in defn.arg_names[1:]])\n        #         defn.type = defn.type.copy_modified(arg_types=arg_types, ret_type=ret_type)\n        #         new = OverloadedFuncDef(super_.node.items)\n        #         # the TypeInfo isn't set on each part, but idc\n        #         new.info = defn.info\n        #         new.impl = defn\n        #         new.type = Overloaded([item.copy_modified() for item in super_type.items])\n        #         if not defn.is_static:\n        #             for new_item in new.type.items:\n        #                 new_item.arg_types[0] = defn.type.arg_types[0]\n        #         defn.is_overload = True\n        #         self.visit_overloaded_func_def(new, do_items=False)\n        #         defn.type = new.type\n        #         return\n        with self.tscope.function_scope(defn):\n            self._visit_func_def(defn)\n\n    def _visit_func_def(self, defn: FuncDef) -> None:\n        \"\"\"Type check a function definition.\"\"\"\n        self.check_func_item(defn, name=defn.name)\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        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 = False\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\n        # Infer argument types from base class\n        #  This is disabled for now.\n        # if defn.info and self.options.infer_function_types and not (\n        #     defn.type and isinstance(defn.type, CallableType) and defn.type.fully_typed\n        # ):\n        #     for base in defn.info.mro[1:]:\n        #         super_ = base.names.get(defn.name)\n        #         if not super_ or not super_.type:\n        #             continue\n        #         super_type = get_proper_type(super_.type)\n        #         if not isinstance(super_type, CallableType):\n        #             continue\n        #\n        #         arg_types: List[Type] = []\n        #         for arg_i, arg_name in enumerate(defn.arg_names):\n        #             # skip self/class\n        #             if arg_i == 0 and not defn.is_static:\n        #                 arg_types.append(typ.arg_types[0])\n        #                 continue\n        #             if (\n        #                 isinstance(defn.type, CallableType)\n        #                 and not isinstance(get_proper_type(defn.type.arg_types[arg_i]), AnyType)\n        #             ):\n        #                 continue\n        #             if arg_name in super_type.arg_names:\n        #                 super_i = super_type.arg_names.index(arg_name)\n        #                 if defn.type:\n        #                     assert isinstance(defn.type, CallableType)\n        #                     defn.type.arg_types[arg_i] = super_type.arg_types[super_i]\n        #                 else:\n        #                     arg_types.append(super_type.arg_types[super_i])\n        #             elif not defn.type:\n        #                 arg_types.append(UntypedType())\n        #\n        #         if defn.type:\n        #             assert isinstance(defn.type, CallableType)\n        #             if self.options.default_return and isinstance(get_proper_type(\n        #                 defn.type.ret_type), NoneType\n        #             ):\n        #                 if defn.unanalyzed_type:\n        #                    assert isinstance(defn.unanalyzed_type, CallableType)\n        #                    if is_unannotated_any(get_proper_type(defn.unanalyzed_type.ret_type)):\n        #                         defn.type.ret_type = super_type.ret_type\n        #                 else:\n        #                     defn.type.ret_type = super_type.ret_type\n        #\n        #             if is_unannotated_any(get_proper_type(defn.type.ret_type)):\n        #                 defn.type.ret_type = super_type.ret_type\n        #         else:\n        #             typ = defn.type = CallableType(\n        #                 arg_types,\n        #                 defn.arg_kinds,\n        #                 defn.arg_names,\n        #                 super_type.ret_type\n        #                 if defn.name != \"__new__\"\n        #                 else fill_typevars_with_any(defn.info),\n        #                 self.named_type('builtins.function'))\n        #         break\n\n        # Infer argument types from default values,\n        #  The issue is that we need to get the type before other nodes are evaluated.\n        #  perhaps if the arg has a default, we could mark it as 'InferableType', and if something\n        #  encounters that type, then defer it.\n        # if self.options.infer_function_types and not typ.fully_typed:\n        #     arg_types = []\n        #     for arg, arg_type in zip(defn.arguments, typ.arg_types):\n        #         if arg.initializer and is_unannotated_any(arg_type):\n        #             arg_types.append(self.expr_checker.accept(arg.initializer))\n        #         else:\n        #             arg_types.append(arg_type)\n        #     typ = typ.copy_modified(arg_types=arg_types)\n        #     defn.type = typ\n\n        if not defn.is_dynamic():\n            self.dynamic_funcs[-1] = False\n\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()\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 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(\n                            get_proper_type(typ.ret_type), (NoneType, UninhabitedType)\n                        )\n                        and not self.dynamic_funcs[-1]\n                    ):\n                        self.fail(\n                            message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name), item\n                        )\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 defn.info and self.is_reverse_op_method(name):\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(\n                            message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT, typ.ret_type\n                        )\n                        self.note(message_registry.UNSAFE_VARIANCE_NOTE, typ.ret_type)\n                    self.check_unbound_return_typevar(typ)\n                elif (\n                    isinstance(original_typ.ret_type, TypeVarType) and original_typ.ret_type.values\n                ):\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(\n                                message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR, typ\n                            )\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                # 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 (not defn.is_static or defn.name == \"__new__\"):\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                for i in range(len(typ.arg_types)):\n                    arg_type = typ.arg_types[i]\n                    if (\n                        isinstance(defn, FuncDef)\n                        and ref_type is not None\n                        and i == 0\n                        and (not defn.is_static or defn.name == \"__new__\")\n                        and typ.arg_kinds[0] not in [nodes.ARG_STAR, nodes.ARG_STAR2]\n                    ):\n                        if defn.is_class or defn.name == \"__new__\":\n                            ref_type = mypy.types.TypeType.make_normalized(ref_type)\n                        if not is_same_type(arg_type, ref_type):\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 typ.arg_names[i] in {\"self\", \"cls\"}:\n                                    if mypy.options._based:\n                                        msg = None\n                                    else:\n                                        msg = (\n                                            message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format(\n                                                erased.str_with_options(self.options),\n                                                ref_type.str_with_options(self.options),\n                                            )\n                                        )\n                                else:\n                                    msg = message_registry.MISSING_OR_INVALID_SELF_TYPE\n                                if msg:\n                                    self.fail(msg, defn)\n                    elif 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                        ):\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                            self.note(message_registry.UNSAFE_VARIANCE_NOTE, 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                self.check_default_args(item, body_is_trivial)\n\n                if mypy.options._based and typ.type_guard:\n                    if typ.type_guard.target_value in typ.arg_names:\n                        idx = typ.arg_names.index(typ.type_guard.target_value)  # type: ignore[arg-type]\n                    elif typ.type_guard.target_is_positional:\n                        idx = typ.type_guard.target_value  # type: ignore[assignment]\n                    else:\n                        assert isinstance(typ.definition, FuncDef)\n                        idx = [arg.variable.name for arg in typ.definition.arguments].index(\n                            typ.type_guard.target_value  # type: ignore[arg-type]\n                        )\n                    self.check_subtype(\n                        typ.type_guard.type_guard,\n                        typ.arg_types[idx],\n                        typ.type_guard.type_guard,\n                        ErrorMessage(\n                            \"A type-guard's type must be assignable to its parameter's type.\",\n                            code=codes.TYPEGUARD_SUBTYPE,\n                        ),\n                        \"guard has type\",\n                        \"parameter has type\",\n                        notes=[\n                            \"If this is correct, try making it an intersection with the parameter type\"\n                        ],\n                    )\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                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                    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                # Ignore plugin generated methods, these usually don't need any bodies.\n                if defn.info is not FUNC_NO_INFO and (\n                    defn.name not in defn.info.names or defn.info.names[defn.name].plugin_generated\n                ):\n                    show_error = False\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                if isinstance(defn, FuncDef) and defn.is_mypy_only:\n                    show_error = False\n\n                # We want to minimize the fallout from checking empty bodies\n                # that was absent in many mypy versions.\n                if body_is_trivial and is_subtype(NoneType(), return_type):\n                    show_error = False\n\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\n                if self.options.warn_no_return:\n                    if (\n                        not self.current_node_deferred\n                        and not isinstance(return_type, (NoneType, UntypedType))\n                        and (\n                            not isinstance(return_type, AnyType)\n                            or return_type.type_of_any == TypeOfAny.explicit\n                        )\n                        and show_error\n                    ):\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                elif show_error:\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 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        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_args(self, item: FuncItem, body_is_trivial: bool) -> None:\n        for arg in item.arguments:\n            if arg.initializer is None:\n                continue\n            if body_is_trivial and isinstance(arg.initializer, EllipsisExpr):\n                continue\n            name = arg.variable.name\n            msg = \"Incompatible default for \"\n            if name.startswith(\"__tuple_arg_\"):\n                msg += f\"tuple argument {name[12:]}\"\n            else:\n                msg += f'argument \"{name}\"'\n            if (\n                not self.options.implicit_optional\n                and isinstance(arg.initializer, NameExpr)\n                and arg.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                arg.variable.type,\n                arg.initializer,\n                context=arg.initializer,\n                msg=ErrorMessage(msg, code=codes.ASSIGNMENT),\n                lvalue_name=\"argument\",\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        # Check for functions with unspecified/not fully specified types.\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        if fdef.type and fdef.is_dynamic():\n            return\n        show_untyped = not self.is_typeshed_stub or self.options.warn_incomplete_stub\n        check_incomplete_defs = self.options.disallow_incomplete_defs and has_explicit_annotation\n        if show_untyped and (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 and (fdef.arg_names[0] in (\"self\", \"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.ARGUMENT_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), (AnyType, Instance, TupleType, UninhabitedType)\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            fallback=forward_item.fallback,\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                typ2.fallback = typ.fallback\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(CALLABLE_NAME),\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        # 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_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 base_attr:\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            # TODO: this logic is much less complete than similar one in checkmember.py\n            if isinstance(defn, (FuncDef, OverloadedFuncDef)):\n                typ: Type = self.function_type(defn)\n                override_class_or_static = defn.is_class or defn.is_static\n                override_class = defn.is_class\n            else:\n                assert defn.var.is_ready\n                assert defn.var.type is not None\n                typ = defn.var.type\n                override_class_or_static = defn.func.is_class or defn.func.is_static\n                override_class = defn.func.is_class\n            typ = get_proper_type(typ)\n            if isinstance(typ, FunctionLike) and not is_static(context):\n                typ = bind_self(typ, self.scope.active_self_type(), is_classmethod=override_class)\n            # Map the overridden method type to subtype context so that\n            # it can be checked for compatibility.\n            original_type = get_proper_type(base_attr.type)\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            if original_type is None or isinstance(original_type, PartialType):\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                    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            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            if isinstance(original_type, FunctionLike):\n                original_type = self.bind_and_map_method(base_attr, original_type, defn.info, base)\n                if original_node and is_property(original_node):\n                    original_type = get_property_type(original_type)\n\n            if isinstance(original_node, Var):\n                expanded_type = map_type_from_supertype(original_type, defn.info, base)\n                expanded_type = expand_self_type(\n                    original_node, expanded_type, fill_typevars(defn.info)\n                )\n                original_type = get_proper_type(expanded_type)\n\n            if is_property(defn):\n                inner: FunctionLike | None\n                if isinstance(typ, FunctionLike):\n                    inner = typ\n                else:\n                    inner = self.extract_callable_type(typ, context)\n                if inner is not None:\n                    typ = inner\n                    typ = get_property_type(typ)\n                    if (\n                        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,\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 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                ):\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)\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 bind_and_map_method(\n        self, sym: SymbolTableNode, typ: FunctionLike, sub_info: TypeInfo, super_info: TypeInfo\n    ) -> FunctionLike:\n        \"\"\"Bind self-type and map type variables for a method.\n\n        Arguments:\n            sym: a symbol that points to method definition\n            typ: method type on the definition\n            sub_info: class where the method is used\n            super_info: class where the method was defined\n        \"\"\"\n        if isinstance(sym.node, (FuncDef, OverloadedFuncDef, Decorator)) and not is_static(\n            sym.node\n        ):\n            if isinstance(sym.node, Decorator):\n                is_class_method = sym.node.func.is_class\n            else:\n                is_class_method = sym.node.is_class\n\n            mapped_typ = cast(FunctionLike, map_type_from_supertype(typ, sub_info, super_info))\n            active_self_type = fill_typevars(sub_info)\n            if isinstance(mapped_typ, Overloaded):\n                # If we have an overload, filter to overloads that match the self type.\n                # This avoids false positives for concrete subclasses of generic classes,\n                # see testSelfTypeOverrideCompatibility for an example.\n                filtered_items = []\n                for item in mapped_typ.items:\n                    if not item.arg_types:\n                        filtered_items.append(item)\n                    item_arg = item.arg_types[0]\n                    if isinstance(item_arg, TypeVarType):\n                        item_arg = item_arg.upper_bound\n                    if is_subtype(active_self_type, item_arg):\n                        filtered_items.append(item)\n                # If we don't have any filtered_items, maybe it's always a valid override\n                # of the superclass? However if you get to that point you're in murky type\n                # territory anyway, so we just preserve the type and have the behaviour match\n                # that of older versions of mypy.\n                if filtered_items:\n                    mapped_typ = Overloaded(filtered_items)\n\n            return bind_self(mapped_typ, active_self_type, is_class_method)\n        else:\n            return cast(FunctionLike, map_type_from_supertype(typ, sub_info, super_info))\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\n        if not is_subtype(\n            override, original, ignore_pos_arg_names=self.options.work_not_properly_function_names\n        ):\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 not fail and 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                if isinstance(override.definition, FuncDef):\n                    type_name = override.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 isinstance(node, FuncDef) and not node.is_property:\n                            arg_node = node.arguments[i + len(override.bound_args)]\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                            secondary_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        with self.tscope.class_scope(defn.info), self.enter_partial_types(is_class=True):\n            old_binder = self.binder\n            self.binder = ConditionalTypeBinder()\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 (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    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(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        for sym in base.names.values():\n            if self.is_final_enum_value(sym):\n                self.fail(f'Cannot extend enum with existing members: \"{base.name}\"', defn)\n                break\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 = cast(Optional[Instance], 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 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        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            if tvar.values:\n                continue\n            up_args: list[Type] = [\n                object_type if i == j else AnyType(TypeOfAny.special_form)\n                for j, _ in enumerate(tvars)\n            ]\n            down_args: list[Type] = [\n                UninhabitedType() if i == j else AnyType(TypeOfAny.special_form)\n                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 determine_type_of_member(self, sym: SymbolTableNode) -> Type | None:\n        if sym.type is not None:\n            return sym.type\n        if isinstance(sym.node, FuncBase):\n            return self.function_type(sym.node)\n        if isinstance(sym.node, TypeInfo):\n            if sym.node.typeddict_type:\n                # We special-case TypedDict, because they don't define any constructor.\n                return self.expr_checker.typeddict_callable(sym.node)\n            else:\n                return type_object_type(sym.node, self.named_type)\n        if isinstance(sym.node, TypeVarExpr):\n            # Use of TypeVars is rejected in an expression/runtime context, so\n            # we don't need to check supertype compatibility for them.\n            return AnyType(TypeOfAny.special_form)\n        if isinstance(sym.node, TypeAlias):\n            with self.msg.filter_errors():\n                # Suppress any errors, they will be given when analyzing the corresponding node.\n                # Here we may have incorrect options and location context.\n                return self.expr_checker.alias_type_in_runtime_context(sym.node, ctx=sym.node)\n        # TODO: handle more node kinds here.\n        return None\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        first_type = get_proper_type(self.determine_type_of_member(first))\n        second_type = get_proper_type(self.determine_type_of_member(second))\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\n        # start with the special case that Instance can be a subtype of FunctionLike\n        call = None\n        if isinstance(first_type, Instance):\n            call = find_member(\"__call__\", first_type, first_type, is_operator=True)\n        if call and isinstance(second_type, FunctionLike):\n            second_sig = self.bind_and_map_method(second, second_type, ctx, base2)\n            ok = is_subtype(call, second_sig)\n        elif isinstance(first_type, FunctionLike) and isinstance(second_type, FunctionLike):\n            if first_type.is_type_obj() and 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(first_type.type_object()),\n                    right=fill_typevars_with_any(second_type.type_object()),\n                )\n            else:\n                # First bind/map method types when necessary.\n                first_sig = self.bind_and_map_method(first, first_type, ctx, base1)\n                second_sig = self.bind_and_map_method(second, second_type, ctx, base2)\n                ok = is_subtype(first_sig, second_sig)\n        elif first_type and second_type:\n            if isinstance(first.node, Var):\n                first_type = get_proper_type(map_type_from_supertype(first_type, ctx, base1))\n                first_type = expand_self_type(first.node, first_type, fill_typevars(ctx))\n            if isinstance(second.node, Var):\n                second_type = get_proper_type(map_type_from_supertype(second_type, ctx, base2))\n                second_type = expand_self_type(second.node, second_type, fill_typevars(ctx))\n            ok = is_equivalent(first_type, second_type)\n            if not ok:\n                second_node = base2[name].node\n                if (\n                    isinstance(second_type, FunctionLike)\n                    and second_node is not None\n                    and is_property(second_node)\n                ):\n                    second_type = get_property_type(second_type)\n                    ok = is_subtype(first_type, second_type)\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        metaclasses = [\n            entry.metaclass_type\n            for entry in typ.mro[1:-1]\n            if entry.metaclass_type\n            and not is_named_instance(entry.metaclass_type, \"builtins.type\")\n        ]\n        if not metaclasses:\n            return\n        if typ.metaclass_type is not None and all(\n            is_subtype(typ.metaclass_type, meta) for meta in metaclasses\n        ):\n            return\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        )\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(artificial=True)\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\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, (RaiseStmt, PassStmt)):\n            return True\n        elif isinstance(s, ExpressionStmt):\n            if isinstance(s.expr, EllipsisExpr):\n                return True\n            elif isinstance(s.expr, CallExpr):\n                with self.expr_checker.msg.filter_errors():\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 check_assignment_for_untyped(self, lvalues: list[Lvalue]):\n        for l in lvalues:\n            if isinstance(l, TupleExpr):\n                self.check_assignment_for_untyped(l.items)\n            elif isinstance(l, (NameExpr, MemberExpr)):\n                t = get_proper_type(self._type_maps[0].get(l))\n                if not t:\n                    # No type? it's either deferred or can't be inferred (handled elsewhere)\n                    continue\n                if is_unannotated_any(t) or isinstance(t, UntypedType):\n                    self.msg.untyped_name_usage(l.name, l)\n            elif isinstance(l, IndexExpr):\n                if not l.method_type or has_untyped_type(l.method_type):\n                    self.msg.untyped_indexed_assignment(l)\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(\n                    s.lvalues[-1],\n                    s.rvalue,\n                    s.type is None,\n                    s.new_syntax,\n                    override_infer=s.unanalyzed_type is not None,\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        if (\n            not self.current_node_deferred\n            and self.options.disallow_untyped_calls\n            and not isinstance(s.rvalue, TempNode)\n        ):\n            self.check_assignment_for_untyped(s.lvalues)\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_function_on_class(\n        self,\n        lvalue: Lvalue,\n        rvalue: Expression,\n        p_lvalue_type: ProperType | None,\n        p_rvalue_type: ProperType | None,\n    ):\n        \"\"\"Special case: function assigned to an instance var via the class will be methodised\"\"\"\n        type_type = None\n        expr_type = None\n        if isinstance(lvalue, MemberExpr):\n            expr_type = self.expr_checker.accept(lvalue.expr)\n            proper = get_proper_type(expr_type)\n            if isinstance(proper, CallableType) and proper.is_type_obj():\n                type_type = expr_type\n        if not (\n            (type_type or self.scope.active_class())\n            and isinstance(p_rvalue_type, CallableType)\n            and isinstance(p_lvalue_type, CallableType)\n        ):\n            return\n        node = None\n        if type_type:\n            assert expr_type\n            proper = get_proper_type(expr_type)\n            assert isinstance(proper, CallableType)\n            proper = get_proper_type(proper.ret_type)\n            if isinstance(proper, TupleType):\n                proper = proper.partial_fallback\n            if not isinstance(proper, Instance):\n                self.msg.fail(\n                    \"This value is some special cased thing, needs to be handled separately\",\n                    rvalue,\n                    code=codes.UNHANDLED_SCENARIO,\n                )\n                return\n            assert isinstance(lvalue, (NameExpr, MemberExpr))\n            table_node = proper.type.get(lvalue.name)\n            if table_node is None:\n                # work around https://github.com/python/mypy/issues/17316\n                return\n            node = table_node.node\n        class_var = (isinstance(node, Var) and node.is_classvar) or (\n            isinstance(lvalue, NameExpr)\n            and isinstance(lvalue.node, Var)\n            and lvalue.node.is_classvar\n        )\n        if p_rvalue_type.is_function:\n            if codes.CALLABLE_FUNCTIONTYPE in self.options.enabled_error_codes:\n                if not (class_var and p_lvalue_type.is_function):\n                    self.msg.fail(\n                        'Assigning a \"FunctionType\" on the class will become a \"MethodType\"',\n                        rvalue,\n                        code=codes.CALLABLE_FUNCTIONTYPE,\n                    )\n                if not class_var:\n                    self.msg.note(\n                        'Consider setting it on the instance, or using \"ClassVar\"', rvalue\n                    )\n        elif (\n            codes.POSSIBLE_FUNCTION in self.options.enabled_error_codes\n            and type(p_rvalue_type) is CallableType\n            and p_rvalue_type.is_callable\n        ):\n            self.msg.fail(\n                'This \"CallableType\" could be a \"FunctionType\", which when assigned via the class, would produce a \"MethodType\"',\n                rvalue,\n                code=codes.POSSIBLE_FUNCTION,\n            )\n            if class_var:\n                self.msg.note('Consider changing the type to \"FunctionType\"', rvalue)\n            elif not p_lvalue_type.is_function:\n                self.msg.note('Consider setting it on the instance, or using \"ClassVar\"', rvalue)\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        override_infer=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, override_infer\n            )\n        else:\n            self.try_infer_partial_generic_type_from_assignment(lvalue, rvalue, \"=\")\n            lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue)\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__\":\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            # Defer PartialType's super type checking.\n            if (\n                isinstance(lvalue, RefExpr)\n                and not (isinstance(lvalue_type, PartialType) and lvalue_type.type is None)\n                and not (isinstance(lvalue, NameExpr) and lvalue.name == \"__match_args__\")\n            ):\n                if self.check_compatibility_all_supers(lvalue, lvalue_type, rvalue):\n                    # We hit an error on this line; don't check for any others\n                    return\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(rvalue_type, is_lvalue_final=var.is_final):\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. No need to check the return value, as\n                        # an error will be reported elsewhere.\n                        self.infer_partial_type(lvalue_type.var, lvalue, rvalue_type)\n                    # Handle None PartialType's super type checking here, after it's resolved.\n                    if isinstance(lvalue, RefExpr) and self.check_compatibility_all_supers(\n                        lvalue, lvalue_type, rvalue\n                    ):\n                        # We hit an error on this line; don't check for any others\n                        return\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                        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                        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 = self.check_simple_assignment(lvalue_type, rvalue, context=rvalue)\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\n                self.check_function_on_class(lvalue, rvalue, p_lvalue_type, p_rvalue_type)\n\n                proper_right = get_proper_type(rvalue_type)\n                if (\n                    isinstance(lvalue, RefExpr)\n                    and isinstance(lvalue.node, Var)\n                    and lvalue.node.is_final\n                    and (\n                        (\n                            # assign_type will use a non-unique key for a final literal\n                            isinstance(proper_right, LiteralType)\n                            or isinstance(proper_right, Instance)\n                            and proper_right.last_known_value is not None\n                        )\n                        # assign_type wouldn't be in the right frame\n                        or (isinstance(lvalue, MemberExpr) or self.scope.active_class())\n                    )\n                ):\n                    # HACK: working around some functionality of assign_type\n                    assert lvalue.node.type\n                    if (\n                        not isinstance(rvalue, TempNode)\n                        and not isinstance(get_proper_type(lvalue_type), AnyType)\n                        and is_subtype(rvalue_type, lvalue.node.type)\n                    ):\n                        if isinstance(lvalue, MemberExpr) or self.scope.active_class():\n                            t = narrow_declared_type(rvalue_type, lvalue.node.type)\n                            self.store_type(lvalue, t)\n                            lvalue.node.type = t\n                        else:\n                            self.store_type(lvalue, rvalue_type)\n                            lvalue.node.type = rvalue_type\n\n                elif (\n                    ((override_infer and not isinstance(rvalue, TempNode)) or infer_lvalue_type)\n                    and not isinstance(lvalue_type, PartialType)\n                    and rvalue_type\n                ):\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, False)\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\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)\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\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) -> Type | None:\n        type_contexts = []\n        if inferred.info:\n            for base in inferred.info.mro[1:]:\n                base_type, base_node = self.lvalue_type_from_base(inferred, base)\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            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(rvalue_type):\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(\n        self, lvalue: RefExpr, lvalue_type: Type | None, rvalue: Expression\n    ) -> bool:\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            and lvalue.kind in (MDEF, None)\n            and len(lvalue_node.info.bases) > 0  # None for Vars defined via self\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            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.lvalue_type_from_base(lvalue_node, base)\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, lvalue_type, rvalue, base, base_type, base_node\n                    ):\n                        # Only show one error per variable; even if other\n                        # base classes are also incompatible\n                        return True\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        return False\n\n    def check_compatibility_super(\n        self,\n        lvalue: RefExpr,\n        lvalue_type: Type | None,\n        rvalue: Expression,\n        base: TypeInfo,\n        base_type: Type,\n        base_node: Node,\n    ) -> bool:\n        lvalue_node = lvalue.node\n        assert isinstance(lvalue_node, Var)\n\n        # Do not check whether the rvalue is compatible if the\n        # lvalue had a type defined; this is handled by other\n        # parts, and all we have to worry about in that case is\n        # that lvalue is compatible with the base class.\n        compare_node = None\n        if lvalue_type:\n            compare_type = lvalue_type\n            compare_node = lvalue.node\n        else:\n            compare_type = self.expr_checker.accept(rvalue, base_type)\n            if isinstance(rvalue, NameExpr):\n                compare_node = rvalue.node\n                if isinstance(compare_node, Decorator):\n                    compare_node = compare_node.func\n\n        base_type = get_proper_type(base_type)\n        compare_type = get_proper_type(compare_type)\n        if compare_type:\n            if isinstance(base_type, CallableType) and isinstance(compare_type, CallableType):\n                base_static = is_node_static(base_node)\n                compare_static = is_node_static(compare_node)\n\n                # In case compare_static is unknown, also check\n                # if 'definition' is set. The most common case for\n                # this is with TempNode(), where we lose all\n                # information about the real rvalue node (but only get\n                # the rvalue type)\n                if compare_static is None and compare_type.definition:\n                    compare_static = is_node_static(compare_type.definition)\n\n                # Compare against False, as is_node_static can return None\n                if base_static is False and compare_static is False:\n                    # Class-level function objects and classmethods become bound\n                    # methods: the former to the instance, the latter to the\n                    # class\n                    base_type = bind_self(base_type, self.scope.active_self_type())\n                    compare_type = bind_self(compare_type, self.scope.active_self_type())\n\n                # If we are a static method, ensure to also tell the\n                # lvalue it now contains a static method\n                if base_static and compare_static:\n                    lvalue_node.is_staticmethod = True\n\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            ):\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        return True\n\n    def lvalue_type_from_base(\n        self, expr_node: Var, base: TypeInfo\n    ) -> tuple[Type | None, Node | None]:\n        \"\"\"For a NameExpr that is part of a class, walk all base classes and try\n        to find the first class that defines a Type for the same name.\"\"\"\n        expr_name = expr_node.name\n        base_var = base.names.get(expr_name)\n\n        if base_var:\n            base_node = base_var.node\n            base_type = base_var.type\n            if isinstance(base_node, Var) and base_type is not None:\n                base_type = expand_self_type(base_node, base_type, fill_typevars(expr_node.info))\n            if isinstance(base_node, Decorator):\n                base_node = base_node.func\n                base_type = base_node.type\n\n            if base_type:\n                if not has_no_typevars(base_type):\n                    self_type = self.scope.active_self_type()\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                    itype = map_instance_to_supertype(instance, base)\n                    base_type = expand_type_by_instance(base_type, itype)\n\n                base_type = get_proper_type(base_type)\n                if isinstance(base_type, CallableType) and isinstance(base_node, FuncDef):\n                    # If we are a property, return the Type of the return\n                    # value, not the Callable\n                    if base_node.is_property:\n                        base_type = get_proper_type(base_type.ret_type)\n                if isinstance(base_type, FunctionLike) and isinstance(\n                    base_node, OverloadedFuncDef\n                ):\n                    # Same for properties with setter\n                    if base_node.is_property:\n                        base_type = base_type.items[0].ret_type\n\n                return base_type, base_node\n\n        return None, None\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 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        override_infer=False,\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) for i 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, override_infer)\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        elif isinstance(rvalue_type, Instance) and rvalue_type.type.fullname == \"builtins.str\":\n            self.msg.unpacking_strings_disallowed(context)\n        else:\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[0].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 todo 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                False,\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) and isinstance(\n            rvalue_type, (Instance, CallableType, TypeType, Overloaded)\n        ):\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(self, lvalue: Lvalue) -> tuple[Type | None, IndexExpr | None, Var | None]:\n        lvalue_type = None\n        index_lvalue = None\n        inferred = None\n\n        if self.is_definition(lvalue) and (\n            not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var)\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)\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            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(init_type, is_lvalue_final=name.is_final)\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 not self.infer_partial_type(name, lvalue, init_type):\n                self.msg.need_annotation_for_var(name, context, self.options.python_version)\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.python_version)\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\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):\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            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\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 if can 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(rvalue.callee.node, FuncBase):\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 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    ) -> Type:\n        if self.is_stub and isinstance(rvalue, EllipsisExpr):\n            # '...' is always a valid initializer in a stub.\n            return AnyType(TypeOfAny.special_form)\n        else:\n            always_allow_any = lvalue_type is not None and not isinstance(\n                get_proper_type(lvalue_type), AnyType\n            )\n            rvalue_type = self.expr_checker.accept(\n                rvalue, lvalue_type, always_allow_any=always_allow_any\n            )\n            if (\n                isinstance(get_proper_type(lvalue_type), UnionType)\n                # Skip literal types, as they have special logic (for better errors).\n                and not isinstance(get_proper_type(rvalue_type), LiteralType)\n                and not self.simple_rvalue(rvalue)\n            ):\n                # Try re-inferring r.h.s. in empty context, and use that if it\n                # results in a narrower type. We don't do this always because this\n                # may cause some perf impact, plus we want to partially preserve\n                # the old behavior. This helps with various practical examples, see\n                # e.g. testOptionalTypeNarrowedByGenericCall.\n                with self.msg.filter_errors() as local_errors, self.local_type_map() as type_map:\n                    alt_rvalue_type = self.expr_checker.accept(\n                        rvalue, None, always_allow_any=always_allow_any\n                    )\n                if (\n                    not local_errors.has_new_errors()\n                    # Skip Any type, since it is special cased in binder.\n                    and not isinstance(get_proper_type(alt_rvalue_type), AnyType)\n                    and is_valid_inferred_type(alt_rvalue_type)\n                    and is_proper_subtype(alt_rvalue_type, rvalue_type)\n                ):\n                    rvalue_type = alt_rvalue_type\n                    self.store_types(type_map)\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                if not self.current_node_deferred and isinstance(rvalue, (NameExpr, MemberExpr)):\n                    rvalue_type_ = get_proper_type(rvalue_type)\n                    if self.options.disallow_untyped_calls and isinstance(\n                        rvalue_type_, UntypedType\n                    ):\n                        self.msg.untyped_name_usage(rvalue.name, rvalue)\n                    elif self.options.disallow_any_expr and isinstance(rvalue_type_, AnyType):\n                        # TODO: this could probably be extracted to a common call\n                        if self.options.hide_any_from_error and (\n                            rvalue_type_.type_of_any == TypeOfAny.from_error\n                            or rvalue_type_.type_of_any == TypeOfAny.from_another_any\n                            and rvalue_type_.source_any\n                            and rvalue_type_.source_any.type_of_any == TypeOfAny.from_error\n                        ):\n                            pass\n                        else:\n                            self.msg.disallowed_any_type(rvalue_type_, rvalue)\n            return rvalue_type\n\n    def check_member_assignment(\n        self, instance_type: Type, attribute_type: Type, rvalue: Expression, 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        Note: this method exists here and not in checkmember.py, because we need to take\n        care about interaction between binder and __set__().\n        \"\"\"\n        instance_type = get_proper_type(instance_type)\n        attribute_type = get_proper_type(attribute_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(attribute_type, rvalue, context)\n            return rvalue_type, attribute_type, True\n\n        if not isinstance(attribute_type, Instance):\n            # TODO: support __set__() for union types.\n            rvalue_type = self.check_simple_assignment(attribute_type, rvalue, context)\n            return rvalue_type, attribute_type, True\n\n        mx = MemberContext(\n            is_lvalue=False,\n            is_super=False,\n            is_operator=False,\n            original_type=instance_type,\n            context=context,\n            self_type=None,\n            msg=self.msg,\n            chk=self,\n        )\n        get_type = analyze_descriptor_access(attribute_type, mx, assignment=True)\n        if not attribute_type.type.has_readable_member(\"__set__\"):\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            rvalue_type = self.check_simple_assignment(get_type, rvalue, context)\n            return rvalue_type, get_type, True\n\n        dunder_set = attribute_type.type.get_method(\"__set__\")\n        if dunder_set is None:\n            self.fail(\n                message_registry.DESCRIPTOR_SET_NOT_CALLABLE.format(\n                    attribute_type.str_with_options(self.options)\n                ),\n                context,\n            )\n            return AnyType(TypeOfAny.from_error), get_type, False\n\n        bound_method = analyze_decorator_or_funcbase_access(\n            defn=dunder_set,\n            itype=attribute_type,\n            info=attribute_type.type,\n            self_type=attribute_type,\n            name=\"__set__\",\n            mx=mx,\n        )\n        typ = map_instance_to_supertype(attribute_type, dunder_set.info)\n        dunder_set_type = expand_type_by_instance(bound_method, typ)\n\n        callable_name = self.expr_checker.method_fullname(attribute_type, \"__set__\")\n        dunder_set_type = self.expr_checker.transform_callee_type(\n            callable_name,\n            dunder_set_type,\n            [TempNode(instance_type, context=context), rvalue],\n            [nodes.ARG_POS, nodes.ARG_POS],\n            context,\n            object_type=attribute_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 self.msg.filter_errors():\n            _, inferred_dunder_set_type = self.expr_checker.check_call(\n                dunder_set_type,\n                [TempNode(instance_type, context=context), type_context],\n                [nodes.ARG_POS, nodes.ARG_POS],\n                context,\n                object_type=attribute_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=context)\n        self.expr_checker.check_call(\n            dunder_set_type,\n            [TempNode(instance_type, context=context), type_context],\n            [nodes.ARG_POS, nodes.ARG_POS],\n            context,\n            object_type=attribute_type,\n            callable_name=callable_name,\n        )\n\n        # Search for possible deprecations:\n        mx.chk.check_deprecated(dunder_set, mx.context)\n        mx.chk.warn_deprecated_overload_item(\n            dunder_set, mx.context, target=inferred_dunder_set_type, selftype=attribute_type\n        )\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), get_type, False\n\n        set_type = inferred_dunder_set_type.arg_types[1]\n        # Special case: if the rvalue_type is a subtype of both '__get__' and '__set__' types,\n        # and '__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_type, rvalue, context)\n        infer = is_subtype(rvalue_type, get_type) and is_subtype(get_type, set_type)\n        return rvalue_type if infer else set_type, get_type, infer\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 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)\n                        and is_valid_inferred_type(value_type)\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                        var.type = self.named_generic_type(typename, [key_type, value_type])\n                        del partial_types[var]\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 check_return_stmt(self, s: ReturnStmt) -> None:\n        defn = self.scope.top_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(self.scope.top_function(), 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            # We pretend the return type is Any here so that we don't report errors in partially\n            #  inferred functions\n            if defn.is_dynamic() and not self.options.check_untyped_defs:\n                return_type = AnyType(TypeOfAny.unannotated)\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                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 (\n                    isinstance(typ, Instance)\n                    and typ.type.fullname == \"builtins._NotImplementedType\"\n                ):\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            is_stub = self.is_stub\n            if s.is_mypy_only:\n                self.is_stub = True\n            for e, b in zip(s.expr, s.body):\n                t = get_proper_type(self.expr_checker.accept(e))\n                allow_redundant_expr = self.allow_redundant_expr\n                self.allow_redundant_expr = False\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                # If if_map is None then we know mypy considers the expression\n                # to be redundant.\n                if codes.REDUNDANT_EXPR in self.options.enabled_error_codes and if_map is None:\n                    self.msg.fail(\"Condition is always false\", e, code=codes.REDUNDANT_EXPR)\n\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                if (\n                    codes.REDUNDANT_EXPR in self.options.enabled_error_codes\n                    and else_map is None\n                    and not allow_redundant_expr\n                ):\n                    self.msg.fail(\"Condition is always true\", e, code=codes.REDUNDANT_EXPR)\n                self.push_type_map(else_map, from_assignment=False)\n            if s.is_mypy_only is False:\n                self.is_stub = True\n            else:\n                self.is_stub = is_stub\n            with self.binder.frame_context(can_skip=False, fall_through=2):\n                if s.else_body:\n                    self.accept(s.else_body)\n            self.is_stub = is_stub\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        allow_redundant_expr = self.allow_redundant_expr\n        self.allow_redundant_expr = True\n        try:\n            self.accept_loop(if_stmt, s.else_body, exit_condition=s.expr)\n        finally:\n            self.allow_redundant_expr = allow_redundant_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, method_type = self.expr_checker.check_op(method, lvalue_type, s.rvalue, s)\n            if isinstance(inst := get_proper_type(lvalue_type), Instance) and isinstance(\n                defn := inst.type.get_method(method), OverloadedFuncDef\n            ):\n                for item in defn.items:\n                    if (\n                        isinstance(item, Decorator)\n                        and isinstance(typ := item.func.type, CallableType)\n                        and (bind_self(typ) == method_type)\n                    ):\n                        self.warn_deprecated(item.func, 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: list[Type] = [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 == \"builtins._NotImplementedType\":\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        # 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                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            if not self.binder.is_unreachable():\n                self.accept(s.finally_body)\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                                var.node.type = DeletedType(source=source)\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            return typ.items\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        elif is_named_instance(typ, \"builtins.tuple\"):\n            # variadic tuple\n            return [typ.args[0]]\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        self.analyze_index_variables(s.index, item_type, s.index_type is None, s)\n        self.accept_loop(s.body, s.else_body)\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            if not self.current_node_deferred:\n                t = get_proper_type(s.expr.accept(self.expr_checker))\n                if isinstance(t, UntypedType) and isinstance(s.expr, (NameExpr, MemberExpr)):\n                    self.msg.untyped_name_usage(s.expr.name, s.expr)\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), False\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(self, e: Decorator, allow_empty: bool = False) -> None:\n        if self.recurse_into_functions:\n            with self.tscope.function_scope(e.func):\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        for d in reversed(e.decorators):\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            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 a 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        self.check_untyped_after_decorator(sig, e.func)\n        sig = set_callable_name(sig, e.func)\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 we already checked override for overload as a whole.\n        if allow_empty:\n            return\n        if e.func.info and not e.func.is_dynamic() 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            ):\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        # detect default_return and warn against it\n        #  This isn't perfect, as None return could come from inheritance, but who cares\n        if (\n            self.options.disallow_untyped_defs\n            and e.var.is_property\n            and isinstance(e.func.type, CallableType)\n        ):\n            if isinstance(get_proper_type(e.func.type.ret_type), NoneType) and (\n                not e.func.unanalyzed_type\n                or (\n                    isinstance(e.func.unanalyzed_type, CallableType)\n                    and is_unannotated_any(e.func.unanalyzed_type.ret_type)\n                )\n            ):\n                self.fail(\n                    \"Property is missing a type annotation\", e.func, code=codes.NO_UNTYPED_DEF\n                )\n        # Special case: most decorators are typed to remove the FunctionType, so warn here\n        if (\n            e.func.info\n            and isinstance(sig, CallableType)\n            and not sig.is_function\n            and not e.func.is_static\n            and not e.func.is_class\n        ):\n            self.fail(\n                'This decorator returns a \"Callable\", not a \"FunctionType\". Decorate this decorator with \"basedtyping.as_functiontype\", or add a \\'type: ignore\\' if it\\'s intentional',\n                e,\n                code=codes.CALLABLE_FUNCTIONTYPE,\n            )\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        ):\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:\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        named_subject: Expression\n        if isinstance(s.subject, CallExpr):\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            id = s.subject.callee.fullname if isinstance(s.subject.callee, RefExpr) else \"\"\n            name = \"dummy-match-\" + id\n            v = Var(name)\n            named_subject = NameExpr(name)\n            named_subject.node = v\n        else:\n            named_subject = s.subject\n\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            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                    if b.is_unreachable or isinstance(\n                        get_proper_type(pattern_type.type), UninhabitedType\n                    ):\n                        self.push_type_map(None, from_assignment=False)\n                        else_map: TypeMap = {}\n                    else:\n                        pattern_map, else_map = conditional_types_to_typemaps(\n                            named_subject, pattern_type.type, pattern_type.rest_type\n                        )\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                                        if not type_map:\n                                            continue\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\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 _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 tm is not None:\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 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 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    ) -> IntersectionType | 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 every time you call it,\n        even if you pass in the exact same arguments. So this means calling\n        `self.intersect_intersection([inst_1, inst_2], ctx)` twice will result\n        in instances of two distinct subclasses of inst_1 and inst_2.\n\n        This is by design: we want each ad-hoc intersection to be unique since\n        they're supposed represent some other unknown subclass.\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\n        ) -> tuple[TypeInfo, str]:\n            names_list = pretty_seq([x.type.name for x in base_classes_], \"&\")\n            short_name = f\"{names_list}\"\n            full_name_ = gen_unique_name(short_name, curr_module_.names)\n            cdef, info_ = self.make_fake_typeinfo(\n                curr_module_.fullname, full_name_, short_name, base_classes_\n            )\n            return info_, full_name_\n\n        base_classes = _get_base_classes(instances)\n        # We use the pretty_names_list for error messages but can't\n        # use it for the real name that goes into the symbol table\n        # because it can have dots in it.\n        pretty_names_list = \" & \".join(\n            format_type_distinctly(*base_classes, options=self.options, bare=True)\n        )\n        pretty_names_list = f'\"{pretty_names_list}\"'\n        bases = base_classes\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(base_classes, curr_module)\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(base_classes, curr_module)\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)\n        return IntersectionType(bases)\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 = []\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)} if callables else None\n            uncallable_map = {expr: UnionType.make_union(uncallables)} if uncallables else None\n            return callable_map, uncallable_map\n\n        elif callables:\n            return {}, None\n\n        return None, {}\n\n    def conditional_types_for_iterable(\n        self, item_type: Type, iterable_type: Type\n    ) -> tuple[Type | None, Type | None]:\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 (\n            UnionType.make_union(if_types) if if_types else None,\n            UnionType.make_union(else_types) if else_types else None,\n        )\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_type_equals_check(\n        self, node: ComparisonExpr, expr_indices: list[int]\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Narrow types based on any checks of the type ``type(x) == T``\n\n        Args:\n            node: The node that might contain the comparison\n            expr_indices: The list of indices of expressions in ``node`` that are being\n                compared\n        \"\"\"\n\n        def is_type_call(expr: CallExpr) -> bool:\n            \"\"\"Is expr a call to type with one argument?\"\"\"\n            return refers_to_fullname(expr.callee, \"builtins.type\") and len(expr.args) == 1\n\n        # exprs that are being passed into type\n        exprs_in_type_calls: list[Expression] = []\n        # type that is being compared to type(expr)\n        type_being_compared: list[TypeRange] | None = None\n        # whether the type being compared to is final\n        is_final = False\n\n        for index in expr_indices:\n            expr = node.operands[index]\n\n            if isinstance(expr, CallExpr) and is_type_call(expr):\n                exprs_in_type_calls.append(expr.args[0])\n            else:\n                current_type = self.get_isinstance_type(expr)\n                if current_type is None:\n                    continue\n                if type_being_compared is not None:\n                    # It doesn't really make sense to have several types being\n                    # compared to the output of type (like type(x) == int == str)\n                    # because whether that's true is solely dependent on what the\n                    # types being compared are, so we don't try to narrow types any\n                    # further because we can't really get any information about the\n                    # type of x from that check\n                    return {}, {}\n                else:\n                    if isinstance(expr, RefExpr) and isinstance(expr.node, TypeInfo):\n                        is_final = expr.node.is_final\n                    type_being_compared = current_type\n\n        if not exprs_in_type_calls:\n            return {}, {}\n\n        if_maps: list[TypeMap] = []\n        else_maps: list[TypeMap] = []\n        for expr in exprs_in_type_calls:\n            current_if_type, current_else_type = self.conditional_types_with_intersection(\n                self.lookup_type(expr), type_being_compared, expr\n            )\n            current_if_map, current_else_map = conditional_types_to_typemaps(\n                expr, current_if_type, current_else_type\n            )\n            if_maps.append(current_if_map)\n            else_maps.append(current_else_map)\n\n        def combine_maps(list_maps: list[TypeMap]) -> TypeMap:\n            \"\"\"Combine all typemaps in list_maps into one typemap\"\"\"\n            result_map = {}\n            for d in list_maps:\n                if d is not None:\n                    result_map.update(d)\n            return result_map\n\n        if_map = combine_maps(if_maps)\n        # type(x) == T is only true when x has the same type as T, meaning\n        # that it can be false if x is an instance of a subclass of T. That means\n        # we can't do any narrowing in the else case unless T is final, in which\n        # case T can't be subclassed\n        if is_final:\n            else_map = combine_maps(else_maps)\n        else:\n            else_map = {}\n        return if_map, else_map\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 upstream_typeis(self, node: CallExpr, expr: Expression) -> tuple[TypeMap, TypeMap]:\n        assert isinstance(node.callee, RefExpr)\n        if node.arg_kinds[0] != nodes.ARG_POS:\n            # the first argument might be used as a kwarg\n            called_type = get_proper_type(self.lookup_type(node.callee))\n\n            # TODO: there are some more cases in check_call() to handle.\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\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 node.callee.type_guard is not None else \"narrower\"\n                    self.fail(message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node)\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 node.callee.type_guard is not None:\n                # return {expr: TypeGuardedType(node.callee.type_guard)}, {}\n                return {}, {}\n            else:\n                assert node.callee.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(node.callee.type_is, is_upper_bound=False)],\n                        expr,\n                    ),\n                )\n        return {}, {}\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 {}, None\n        if is_false_literal(node):\n            return None, {}\n\n        if isinstance(node, CallExpr):\n            if 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),\n                                self.get_isinstance_type(node.args[1]),\n                                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                if isinstance(node.callee, RefExpr) and node.callee.type_is:\n                    return self.upstream_typeis(node, expr)\n            if isinstance(node.callee, (RefExpr, CallExpr, LambdaExpr)):\n                # TODO: AssignmentExpr `(a := A())()`\n                if node.callee.type_guard is not None:\n                    # TODO: Follow *args, **kwargs\n                    called_type = get_proper_type(self.lookup_type(node.callee))\n                    if isinstance(called_type, Instance):\n                        called_type = get_proper_type(\n                            analyze_member_access(\n                                name=\"__call__\",\n                                typ=called_type,\n                                context=node,\n                                is_lvalue=False,\n                                is_super=False,\n                                is_operator=True,\n                                msg=self.msg,\n                                original_type=called_type,\n                                chk=self,\n                            )\n                        )\n                    assert isinstance(called_type, (CallableType, Overloaded))\n                    guard = node.callee.type_guard\n                    target = guard.target_value\n                    if guard.target_is_class or guard.target_is_self:\n                        if isinstance(node.callee, (CallExpr, NameExpr)):\n                            expr = node.callee\n                        elif isinstance(node.callee, MemberExpr):\n                            expr = node.callee.expr\n                        else:\n                            raise AssertionError(\"What is this?\")\n                        if guard.target_is_class and isinstance(\n                            get_proper_type(self.lookup_type(expr)), Instance\n                        ):\n                            guarded = get_type_type_item(\n                                get_proper_type(node.callee.type_guard.type_guard)\n                            )\n                            if not guarded:\n                                return {}, {}\n                        else:\n                            guarded = node.callee.type_guard.type_guard\n                        return {collapse_walrus(expr): guarded}, {}\n                    if isinstance(target, int):\n                        idx = target\n                        if called_type.items[0].def_extras.get(\"first_arg\"):\n                            self.fail(\n                                \"type-guard on positional class function is unsupported\",\n                                node,\n                                code=codes.TYPEGUARD_LIMITATION,\n                            )\n                            return {}, {}\n                    elif target in called_type.items[0].arg_names:\n                        idx = called_type.items[0].arg_names.index(target)\n                    elif target == \"first argument\":\n                        idx = 0\n                        if not node.args:\n                            return {}, {}\n                    else:\n                        definition = called_type.items[0].definition\n                        assert isinstance(definition, FuncDef)\n                        idx = [arg.variable.name for arg in definition.arguments].index(target)\n                    if target in node.arg_names:\n                        idx = node.arg_names.index(target)  # type: ignore[arg-type]\n                    if len(node.arg_kinds) <= idx:\n                        return {}, {}\n                    if node.arg_kinds[idx].is_star():\n                        self.fail(message_registry.TYPE_GUARD_POS_LIMITATION, node)\n                        return {}, {}\n                    # we want the idx-th variable to be narrowed\n                    expr = collapse_walrus(node.args[idx])\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                        #\n                        # Based: We don't do any of that.\n                        if guard.only_true:\n                            return {expr: guard.type_guard}, {}\n                        return conditional_types_to_typemaps(\n                            expr,\n                            *self.conditional_types_with_intersection(\n                                self.lookup_type(expr),\n                                [TypeRange(guard.type_guard, is_upper_bound=False)],\n                                expr,\n                                erase=False,\n                            ),\n                        )\n        if isinstance(node, CallExpr) and isinstance(node.callee, LambdaExpr):\n            return self.find_isinstance_check_helper(\n                safe(cast(ReturnStmt, node.callee.body.body[0]).expr)\n            )\n        elif isinstance(node, ComparisonExpr):\n            return self.comparison_type_narrowing_helper(node)\n        elif isinstance(node, AssignmentExpr):\n            if_map: dict[Expression, Type] | None\n            else_map: dict[Expression, Type] | None\n            if_map = {}\n            else_map = {}\n\n            if_assignment_map, else_assignment_map = self.find_isinstance_check(node.target)\n\n            if if_assignment_map is not None:\n                if_map.update(if_assignment_map)\n            if else_assignment_map is not None:\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 if_condition_map is not None:\n                if_map.update(if_condition_map)\n            if else_condition_map is not None:\n                else_map.update(else_condition_map)\n\n            return (\n                (None if if_assignment_map is None or if_condition_map is None else if_map),\n                (None if else_assignment_map is None or else_condition_map is None else else_map),\n            )\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 yes_type is not None:\n                yes_type = true_only(yes_type)\n            else:\n                yes_type = UninhabitedType()\n            if no_type is not None:\n                no_type = false_only(no_type)\n            else:\n                no_type = UninhabitedType()\n            if_map = {node: yes_type} if not isinstance(yes_type, UninhabitedType) else None\n            else_map = {node: no_type} if not isinstance(no_type, UninhabitedType) else None\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_type = true_only(vartype)\n        else_type = false_only(vartype)\n        if_map = {node: if_type} if not isinstance(if_type, UninhabitedType) else None\n        else_map = {node: else_type} if not isinstance(else_type, UninhabitedType) else None\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 self.is_literal_enum(expr)\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 operator in {\"is\", \"is not\", \"==\", \"!=\"}:\n                if_map, else_map = self.equality_type_narrowing_helper(\n                    node,\n                    operator,\n                    operands,\n                    operand_types,\n                    expr_indices,\n                    narrowable_operand_index_to_hash,\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, else_map = {}, {}\n\n                if left_index in narrowable_operand_index_to_hash:\n                    # We only try and narrow away 'None' for now\n                    if is_overlapping_none(item_type):\n                        collection_item_type = get_proper_type(builtin_item_type(iterable_type))\n                        if (\n                            collection_item_type is not None\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 if_type is None:\n                        if_map = None\n                    else:\n                        if_map[expr] = if_type\n                    if else_type is None:\n                        else_map = None\n                    else:\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 equality_type_narrowing_helper(\n        self,\n        node: ComparisonExpr,\n        operator: str,\n        operands: list[Expression],\n        operand_types: list[Type],\n        expr_indices: list[int],\n        narrowable_operand_index_to_hash: dict[int, tuple[Key, ...]],\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Calculate type maps for '==', '!=', 'is' or 'is not' expression.\"\"\"\n        # is_valid_target:\n        #   Controls which types we're allowed to narrow exprs to. Note that\n        #   we cannot use 'is_literal_type_like' in both cases since doing\n        #   'x = 10000 + 1; x is 10001' is not always True in all Python\n        #   implementations.\n        #\n        # coerce_only_in_literal_context:\n        #   If true, coerce types into literal types only if one or more of\n        #   the provided exprs contains an explicit Literal type. This could\n        #   technically be set to any arbitrary value, but it seems being liberal\n        #   with narrowing when using 'is' and conservative when using '==' seems\n        #   to break the least amount of real-world code.\n        #\n        # should_narrow_by_identity:\n        #   Set to 'false' only if the user defines custom __eq__ or __ne__ methods\n        #   that could cause identity-based narrowing to produce invalid results.\n        if operator in {\"is\", \"is not\"}:\n            is_valid_target: Callable[[Type], bool] = is_singleton_type\n            coerce_only_in_literal_context = False\n            should_narrow_by_identity = True\n        else:\n\n            def is_exactly_literal_type(t: Type) -> bool:\n                return isinstance(get_proper_type(t), LiteralType)\n\n            def has_no_custom_eq_checks(t: Type) -> bool:\n                return not custom_special_method(\n                    t, \"__eq__\", check_all=False\n                ) and not custom_special_method(t, \"__ne__\", check_all=False)\n\n            is_valid_target = is_exactly_literal_type\n            coerce_only_in_literal_context = True\n\n            expr_types = [operand_types[i] for i in expr_indices]\n            should_narrow_by_identity = all(\n                map(has_no_custom_eq_checks, expr_types)\n            ) and not is_ambiguous_mix_of_enums(expr_types)\n\n        if_map: TypeMap = {}\n        else_map: TypeMap = {}\n        if should_narrow_by_identity:\n            if_map, else_map = self.refine_identity_comparison_expression(\n                operands,\n                operand_types,\n                expr_indices,\n                narrowable_operand_index_to_hash.keys(),\n                is_valid_target,\n                coerce_only_in_literal_context,\n            )\n\n        if if_map == {} and else_map == {}:\n            if_map, else_map = self.refine_away_none_in_comparison(\n                operands, operand_types, expr_indices, narrowable_operand_index_to_hash.keys()\n            )\n\n        # If we haven't been able to narrow types yet, we might be dealing with a\n        # explicit type(x) == some_type check\n        if if_map == {} and else_map == {}:\n            if_map, else_map = self.find_type_equals_check(node, expr_indices)\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        if new_types is None:\n            return None\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 = collapse_walrus(expr.expr)\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                            msg=self.msg,\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 = collapse_walrus(expr.base)\n                parent_type = self.lookup_type_or_none(parent_expr)\n\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 refine_identity_comparison_expression(\n        self,\n        operands: list[Expression],\n        operand_types: list[Type],\n        chain_indices: list[int],\n        narrowable_operand_indices: AbstractSet[int],\n        is_valid_target: Callable[[ProperType], bool],\n        coerce_only_in_literal_context: bool,\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Produce conditional type maps refining expressions by an identity/equality comparison.\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_operand_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        Although this function could theoretically try setting the types of the operands\n        in the chains to the meet, doing that causes too many issues in real-world code.\n        Instead, we use 'is_valid_target' to identify which of the given chain types\n        we could plausibly use as the refined type for the expressions in the chain.\n\n        Similarly, 'coerce_only_in_literal_context' controls whether we should try coercing\n        expressions in the chain to a Literal type. Performing this coercion is sometimes\n        too aggressive of a narrowing, depending on context.\n        \"\"\"\n        should_coerce = True\n        if coerce_only_in_literal_context:\n\n            def should_coerce_inner(typ: Type) -> bool:\n                typ = get_proper_type(typ)\n                return is_literal_type_like(typ) or (\n                    isinstance(typ, Instance) and typ.type.is_enum\n                )\n\n            should_coerce = any(should_coerce_inner(operand_types[i]) for i in chain_indices)\n\n        target: Type | None = None\n        possible_target_indices = []\n        for i in chain_indices:\n            expr_type = operand_types[i]\n            if should_coerce:\n                expr_type = coerce_to_literal(expr_type)\n            if not is_valid_target(get_proper_type(expr_type)):\n                continue\n            if target and not is_same_type(target, expr_type):\n                # We have multiple disjoint target types. So the 'if' branch\n                # must be unreachable.\n                return None, {}\n            target = expr_type\n            possible_target_indices.append(i)\n\n        # There's nothing we can currently infer if none of the operands are valid targets,\n        # so we end early and infer nothing.\n        if target is None:\n            return {}, {}\n\n        # If possible, use an unassignable expression as the target.\n        # We skip refining the type of the target below, so ideally we'd\n        # want to pick an expression we were going to skip anyways.\n        singleton_index = -1\n        for i in possible_target_indices:\n            if i not in narrowable_operand_indices:\n                singleton_index = i\n\n        # But if none of the possible singletons are unassignable ones, we give up\n        # and arbitrarily pick the last item, mostly because other parts of the\n        # type narrowing logic bias towards picking the rightmost item and it'd be\n        # nice to stay consistent.\n        #\n        # That said, it shouldn't matter which index we pick. For example, suppose we\n        # have this if statement, where 'x' and 'y' both have singleton types:\n        #\n        #     if x is y:\n        #         reveal_type(x)\n        #         reveal_type(y)\n        #     else:\n        #         reveal_type(x)\n        #         reveal_type(y)\n        #\n        # At this point, 'x' and 'y' *must* have the same singleton type: we would have\n        # ended early in the first for-loop in this function if they weren't.\n        #\n        # So, we should always get the same result in the 'if' case no matter which\n        # index we pick. And while we do end up getting different results in the 'else'\n        # case depending on the index (e.g. if we pick 'y', then its type stays the same\n        # while 'x' is narrowed to '<uninhabited>'), this distinction is also moot: mypy\n        # currently will just mark the whole branch as unreachable if either operand is\n        # narrowed to <uninhabited>.\n        if singleton_index == -1:\n            singleton_index = possible_target_indices[-1]\n\n        sum_type_name = None\n        target = get_proper_type(target)\n        if isinstance(target, LiteralType) and (\n            target.is_enum_literal() or isinstance(target.value, bool)\n        ):\n            sum_type_name = target.fallback.type.fullname\n\n        target_type = [TypeRange(target, is_upper_bound=False)]\n\n        partial_type_maps = []\n        for i in chain_indices:\n            # If we try refining a type against itself, conditional_type_map\n            # will end up assuming that the 'else' branch is unreachable. This is\n            # typically not what we want: generally the user will intend for the\n            # target type to be some fixed 'sentinel' value and will want to refine\n            # the other exprs against this one instead.\n            if i == singleton_index:\n                continue\n\n            # Naturally, we can't refine operands which are not permitted to be refined.\n            if i not in narrowable_operand_indices:\n                continue\n\n            expr = operands[i]\n            expr_type = coerce_to_literal(operand_types[i])\n\n            if sum_type_name is not None:\n                expr_type = try_expanding_sum_type_to_union(expr_type, sum_type_name)\n\n            # We intentionally use 'conditional_types' directly here instead of\n            # 'self.conditional_types_with_intersection': we only compute ad-hoc\n            # intersections when working with pure instances.\n            types = conditional_types(expr_type, target_type)\n            partial_type_maps.append(conditional_types_to_typemaps(expr, *types))\n\n        return reduce_conditional_maps(partial_type_maps)\n\n    def refine_away_none_in_comparison(\n        self,\n        operands: list[Expression],\n        operand_types: list[Type],\n        chain_indices: list[int],\n        narrowable_operand_indices: AbstractSet[int],\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Produces conditional type maps refining away None in an identity/equality chain.\n\n        For more details about what the different arguments mean, see the\n        docstring of 'refine_identity_comparison_expression' up above.\n        \"\"\"\n\n        non_optional_types = []\n        for i in chain_indices:\n            typ = operand_types[i]\n            if not is_overlapping_none(typ):\n                non_optional_types.append(typ)\n\n        if_map, else_map = {}, {}\n\n        if not non_optional_types or (len(non_optional_types) != len(chain_indices)):\n\n            # Narrow e.g. `Optional[A] == \"x\"` or `Optional[A] is \"x\"` to `A` (which may be\n            # convenient but is strictly not type-safe):\n            for i in narrowable_operand_indices:\n                expr_type = operand_types[i]\n                if not is_overlapping_none(expr_type):\n                    continue\n                if any(is_overlapping_erased_types(expr_type, t) for t in non_optional_types):\n                    if_map[operands[i]] = remove_optional(expr_type)\n\n            # Narrow e.g. `Optional[A] != None` to `A` (which is stricter than the above step and\n            # so type-safe but less convenient, because e.g. `Optional[A] == None` still results\n            # in `Optional[A]`):\n            if any(isinstance(get_proper_type(ot), NoneType) for ot in operand_types):\n                for i in narrowable_operand_indices:\n                    expr_type = operand_types[i]\n                    if is_overlapping_none(expr_type):\n                        else_map[operands[i]] = remove_optional(expr_type)\n\n        return if_map, else_map\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        # 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                    return [(None, {})]\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 = None if yes_type is None else {tpl: yes_type}\n                    no_map = None if no_type is None else {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 = None if yes_type is None else {left.args[0]: yes_type}\n                no_map = None if no_type is None else {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 | None, Type | None]:\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                if yt is not None:\n                    yes_types.append(yt)\n                if nt is not None:\n                    no_types.append(nt)\n            yes_types += other_types\n            no_types += other_types\n            if yes_types:\n                yes_type = make_simplified_union(yes_types)\n            else:\n                yes_type = None\n            if no_types:\n                no_type = make_simplified_union(no_types)\n            else:\n                no_type = None\n            return yes_type, no_type\n        else:\n            assert False, \"Unsupported type for len narrowing\"\n\n    def refine_tuple_type_with_len(\n        self, typ: TupleType, op: str, size: int\n    ) -> tuple[Type | None, Type | None]:\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, None\n            return None, 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 None, 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 None, 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 None, 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 None, 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 | None, Type | None]:\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 | None = 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 | None = 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        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))\n        ):\n            self.msg.report_protocol_problems(subtype, supertype, context, code=msg.code)\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        # 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)\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)\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    @contextmanager\n    def local_type_map(self) -> Iterator[dict[Expression, Type]]:\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        temp_type_map: dict[Expression, Type] = {}\n        self._type_maps.append(temp_type_map)\n        yield temp_type_map\n        self._type_maps.pop()\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 we require local partial types, there are a few exceptions where\n                # we fall back to inferring just \"None\" as the type from a None initializer:\n                #\n                # 1. If all happens within a single function this is acceptable, since only\n                #    the topmost function is a separate target in fine-grained incremental mode.\n                #    We primarily want to avoid \"splitting\" partial types across targets.\n                #\n                # 2. A None initializer in the class body if the attribute is defined in a base\n                #    class is fine, since the attribute is already defined and it's currently okay\n                #    to vary the type of an attribute covariantly. The None type will still be\n                #    checked for compatibility with base classes elsewhere. Without this exception\n                #    mypy could require an annotation for an attribute that already has been\n                #    declared in a base class, which would be bad.\n                allow_none = (\n                    not self.options.local_partial_types\n                    or is_function\n                    or (is_class and self.is_defined_in_base_class(var))\n                )\n                if (\n                    allow_none\n                    and isinstance(var.type, PartialType)\n                    and var.type.type is None\n                    and not permissive\n                ):\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.python_version)\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(\n                            node, context, self.options.python_version\n                        )\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                if isinstance(var.type, PartialType) and var.type.type is not None and var.info:\n                    # This is an ugly hack to make partial generic self attributes behave\n                    # as if --local-partial-types is always on (because it used to be like this).\n                    disallow_other_scopes = True\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    ) -> None:\n        \"\"\"Produce an error message.\"\"\"\n        if isinstance(msg, ErrorMessage):\n            self.msg.fail(msg.value, context, code=msg.code)\n            return\n        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(\n        self, it: Instance | CallableType | TypeType | Overloaded, context: Context\n    ) -> 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 type_map is None:\n            self.binder.unreachable()\n        else:\n            with self.binder.collect_artificial_keys():\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\n        def search_type_type(it: ProperType) -> ProperType:\n            if isinstance(it, UnionType):\n                union_list = []\n                for t in get_proper_types(it.items):\n                    t = search_type_type(t)\n                    if isinstance(t, TypeType):\n                        union_list.append(t.item)\n                    else:\n                        raise InvalidTypeType\n                return UnionType(union_list)\n            elif isinstance(it, IntersectionType):\n                intersection_list = []\n                for t in get_proper_types(it.items):\n                    t = search_type_type(t)\n                    if isinstance(t, TypeType):\n                        intersection_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                        raise InvalidTypeType\n                return IntersectionType(intersection_list)\n            return it\n\n        if isinstance(vartype, (UnionType, IntersectionType)):\n            try:\n                vartype = search_type_type(vartype)\n            except InvalidTypeType:\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        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        erase=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        erase=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        erase=True,\n    ) -> tuple[Type | None, Type | None]:\n        initial_types = conditional_types(expr_type, type_ranges, default, erase=erase)\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                if not isinstance(v, IntersectionType):\n                    return yes_type, no_type\n                for t in possible_target_types:\n                    for v_item in v.items:\n                        v_type = get_proper_type(v_item)\n                        if (\n                            isinstance(t, Instance)\n                            and isinstance(v_type, Instance)\n                            and self.intersect_instances((v_type, t), errors)\n                        ):\n                            break\n                    else:\n                        continue\n                    # Not necessarily a valid Intersection, but who asked????\n                    out.append(make_simplified_intersection((*v.items, t)))\n                break\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(self, expr: Expression) -> list[TypeRange] | None:\n        if isinstance(expr, OpExpr) and expr.op == \"|\":\n            left = self.get_isinstance_type(expr.left)\n            if left is None and is_literal_none(expr.left):\n                left = [TypeRange(NoneType(), is_upper_bound=False)]\n            right = self.get_isinstance_type(expr.right)\n            if right is None and is_literal_none(expr.right):\n                right = [TypeRange(NoneType(), is_upper_bound=False)]\n            if left is None or right is None:\n                return None\n            return left + right\n        all_types = get_proper_types(flatten_types(self.lookup_type(expr)))\n        types: list[TypeRange] = []\n        for typ in all_types:\n            if isinstance(typ, FunctionLike) and typ.is_type_obj():\n                # Type variables may be present -- erase them, which is the best\n                # we can do (outside disallowing them here).\n                erased_type = erase_typevars(typ.items[0].ret_type)\n                types.append(TypeRange(erased_type, is_upper_bound=False))\n            elif 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                types.append(TypeRange(typ.item, is_upper_bound=is_upper_bound))\n            elif isinstance(typ, Instance) and typ.type.fullname == \"builtins.type\":\n                object_type = Instance(typ.type.mro[-1], [])\n                types.append(TypeRange(object_type, is_upper_bound=True))\n            elif isinstance(typ, Instance) and typ.type.fullname == \"types.UnionType\" and typ.args:\n                types.append(TypeRange(UnionType(typ.args), is_upper_bound=False))\n            elif isinstance(typ, AnyType):\n                types.append(TypeRange(typ, is_upper_bound=False))\n            else:  # we didn't see an actual type, but rather a variable with unknown value\n                return None\n        if not types:\n            # this can happen if someone has empty tuple as 2nd argument to isinstance\n            # strictly speaking, we should return UninhabitedType but for simplicity we will simply\n            # refuse to do any type inference for now\n            return None\n        return types\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(self.add_any_attribute_to_type(typ.item, name))\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                msg=self.msg,\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 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        ):\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 warn_deprecated_overload_item(\n        self, node: Node | None, context: Context, *, target: Type, selftype: Type | None = None\n    ) -> None:\n        \"\"\"Warn if the overload item corresponding to the given callable is deprecated.\"\"\"\n        target = get_proper_type(target)\n        if isinstance(node, OverloadedFuncDef) and isinstance(target, CallableType):\n            for item in node.items:\n                if isinstance(item, Decorator) and isinstance(\n                    candidate := item.func.type, CallableType\n                ):\n                    if selftype is not None:\n                        candidate = bind_self(candidate, selftype)\n                    if candidate == target:\n                        self.warn_deprecated(item.func, context)\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        t.upper_bound.accept(self)\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    erase=False,\n) -> tuple[Type | None, Type | None]: ...\n\n\n@overload\ndef conditional_types(\n    current_type: Type, proposed_type_ranges: list[TypeRange] | None, default: Type, *, erase=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    erase=True,\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: The first element is the proposed type, if the expression\n    can be the proposed type. The second element is the type it would hold\n    if it was not the proposed type, if any. UninhabitedType means unreachable.\n    None means no new information can be inferred. If default is set it is returned\n    instead.\"\"\"\n    if proposed_type_ranges:\n        if len(proposed_type_ranges) == 1:\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        proposed_items = [type_range.item for type_range in proposed_type_ranges]\n        proposed_type = make_simplified_union(proposed_items)\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        elif not any(\n            type_range.is_upper_bound for type_range in proposed_type_ranges\n        ) and is_proper_subtype(current_type, proposed_type, ignore_promotions=True):\n            # Expression is always of one of the types in proposed_type_ranges\n            return default, UninhabitedType()\n        elif not is_overlapping_types(\n            current_type, proposed_type, ignore_promotions=True, check_variance=True\n        ):\n            # Expression is never of any type in proposed_type_ranges\n            return UninhabitedType(), default\n        else:\n            # we can only restrict when the type is precise, not bounded\n            proposed_precise_type = UnionType.make_union(\n                [\n                    type_range.item\n                    for type_range in proposed_type_ranges\n                    if not type_range.is_upper_bound\n                ]\n            )\n            remaining_type = restrict_subtype_away(\n                current_type, proposed_precise_type, erase=erase\n            )\n            return proposed_type, remaining_type\n    else:\n        # An isinstance check, but we don't understand the type\n        return current_type, default\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    maps: list[TypeMap] = []\n    for typ in (yes_type, no_type):\n        proper_type = get_proper_type(typ)\n        if isinstance(proper_type, UninhabitedType):\n            maps.append(None)\n        elif proper_type is None:\n            maps.append({})\n        else:\n            assert typ is not None\n            maps.append({expr: typ})\n\n    return cast(tuple[TypeMap, TypeMap], tuple(maps))\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) -> 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 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\n    if m1 is None or m2 is None:\n        # One of the conditions can never be true.\n        return None\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(get_proper_type(m1[n1]), AnyType):\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 m1 is None:\n        return m2\n    if m2 is None:\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 convert_to_typetype(type_map: TypeMap) -> TypeMap:\n    converted_type_map: dict[Expression, Type] = {}\n    if type_map is None:\n        return None\n    for expr, typ in type_map.items():\n        t = typ\n        if isinstance(t, TypeVarType):\n            t = t.upper_bound\n        # TODO: should we only allow unions of instances as per PEP 484?\n        if not isinstance(get_proper_type(t), (UnionType, IntersectionType, Instance, NoneType)):\n            # unknown type; error was likely reported earlier\n            return {}\n        converted_type_map[expr] = TypeType.make_normalized(typ)\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(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, TupleType):\n        return [b for a in t.items for b in flatten_types(a)]\n    elif is_named_instance(t, \"builtins.tuple\"):\n        return [t.args[0]]\n    else:\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    for sig_variant in expand_callable_variants(signature):\n        for other_variant in expand_callable_variants(other):\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    )\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(typ: Type, is_lvalue_final: bool = False) -> 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\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\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_node_static(node: Node | None) -> bool | None:\n    \"\"\"Find out if a node describes a static function method.\"\"\"\n\n    if isinstance(node, FuncDef):\n        return node.is_static\n\n    if isinstance(node, Var):\n        return node.is_staticmethod\n\n    return None\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 top_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_non_lambda_function(self) -> FuncItem | None:\n        for e in reversed(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) -> TypeInfo | None:\n        \"\"\"Is there a class *directly* enclosing this function?\"\"\"\n        top = self.top_function()\n        assert top, \"This method must be called from inside a function\"\n        index = self.stack.index(top)\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.top_function():\n            info = self.enclosing_class()\n        if info:\n            return fill_typevars(info)\n        return None\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\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, 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 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(\n        left,\n        right,\n        ignore_promotions=True,\n        prohibit_none_typevar_overlap=True,\n        overlap_for_overloads=True,\n    )\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 is_ambiguous_mix_of_enums(types: list[Type]) -> bool:\n    \"\"\"Do types have IntEnum/StrEnum types that are potentially overlapping with other types?\n\n    If True, we shouldn't attempt type narrowing based on enum values, as it gets\n    too ambiguous.\n\n    For example, return True if there's an 'int' type together with an IntEnum literal.\n    However, IntEnum together with a literal of the same IntEnum type is not ambiguous.\n    \"\"\"\n    # We need these things for this to be ambiguous:\n    #  (1) an IntEnum or StrEnum type\n    #  (2) either a different IntEnum/StrEnum type or a non-enum type (\"<other>\")\n    #\n    # It would be slightly more correct to calculate this separately for IntEnum and\n    # StrEnum related types, as an IntEnum can't be confused with a StrEnum.\n    return len(_ambiguous_enum_variants(types)) > 1\n\n\ndef _ambiguous_enum_variants(types: list[Type]) -> set[str]:\n    result = set()\n    for t in types:\n        t = get_proper_type(t)\n        if isinstance(t, UnionType):\n            result.update(_ambiguous_enum_variants(t.items))\n        elif isinstance(t, Instance):\n            if t.last_known_value:\n                result.update(_ambiguous_enum_variants([t.last_known_value]))\n            elif t.type.is_enum and any(\n                base.fullname in (\"enum.IntEnum\", \"enum.StrEnum\") 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_variants([t.fallback]))\n        elif isinstance(t, NoneType):\n            pass\n        else:\n            result.add(\"<other>\")\n    return result\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 Iterable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom typing import Callable, ClassVar, Final, Optional, cast, overload\nfrom typing_extensions import TypeAlias as _TypeAlias, assert_never\n\nimport mypy.checker\nimport mypy.errorcodes as codes\nfrom mypy import applytype, erasetype, errorcodes, join, message_registry, nodes, operators, types\nfrom mypy.argmap import ArgTypeExpander, map_actuals_to_formals, map_formals_to_actuals\nfrom mypy.checkmember import (\n    MemberContext,\n    analyze_member_access,\n    freeze_all_type_vars,\n    report_missing_attribute,\n    type_object_type,\n)\nfrom mypy.checkstrformat import StringFormatterChecker\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.infer import ArgumentInferContext, infer_function_type_arguments, infer_type_arguments\nfrom mypy.literals import literal\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, format_type_inner\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    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    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\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    TempNode,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\n    TypeInfo,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    YieldExpr,\n    YieldFromExpr,\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    find_member,\n    is_equivalent,\n    is_same_type,\n    is_subtype,\n    non_method_protocol_members,\n)\nfrom mypy.traverser import has_await_expression\nfrom mypy.typeanal import (\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    bind_self,\n    callable_type,\n    custom_special_method,\n    erase_to_union_or_bound,\n    false_only,\n    fixup_partial_type,\n    function_type,\n    get_all_type_vars,\n    get_type_vars,\n    is_literal_type_like,\n    make_simplified_intersection,\n    make_simplified_union,\n    simple_literal_type,\n    true_only,\n    try_expanding_sum_type_to_union,\n    try_getting_str_literals,\n    tuple_fallback,\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    IntersectionType,\n    LiteralType,\n    LiteralValue,\n    NamedOverloaded,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecFlavor,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeGuardType,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    UntypedType,\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.util import split_module_names\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, Optional[Type], 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\ndef extract_refexpr_names(expr: RefExpr) -> set[str]:\n    \"\"\"Recursively extracts all module references from a reference expression.\n\n    Note that currently, the only two subclasses of RefExpr are NameExpr and\n    MemberExpr.\"\"\"\n    output: set[str] = set()\n    while isinstance(expr.node, MypyFile) or expr.fullname:\n        if isinstance(expr.node, MypyFile) and expr.fullname:\n            # If it's None, something's wrong (perhaps due to an\n            # import cycle or a suppressed error).  For now we just\n            # skip it.\n            output.add(expr.fullname)\n\n        if isinstance(expr, NameExpr):\n            is_suppressed_import = isinstance(expr.node, Var) and expr.node.is_suppressed_import\n            if isinstance(expr.node, TypeInfo):\n                # Reference to a class or a nested class\n                output.update(split_module_names(expr.node.module_name))\n            elif \".\" in expr.fullname and not is_suppressed_import:\n                # Everything else (that is not a silenced import within a class)\n                output.add(expr.fullname.rsplit(\".\", 1)[0])\n            break\n        elif isinstance(expr, MemberExpr):\n            if isinstance(expr.expr, RefExpr):\n                expr = expr.expr\n            else:\n                break\n        else:\n            raise AssertionError(f\"Unknown RefExpr subclass: {type(expr)}\")\n    return output\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]):\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    # cache resolved types in some cases\n    resolved_type: dict[Expression, ProperType]\n\n    strfrm_checker: StringFormatterChecker\n    plugin: Plugin\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, self.chk, self.msg)\n\n        self.resolved_type = {}\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    def reset(self) -> None:\n        self.resolved_type = {}\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        self.chk.module_refs.update(extract_refexpr_names(e))\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, FuncDef):\n            # Reference to a global function.\n            if node.is_type_check_only and not self.chk.is_stub:\n                self.chk.fail(message_registry.TYPE_CHECK_ONLY.format(node.name), e)\n            result = function_type(node, self.named_type(\"builtins.function\"))\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, TypeInfo):\n            # Reference to a type object.\n            if node.is_type_check_only and not self.chk.is_stub:\n                self.chk.fail(message_registry.TYPE_CHECK_ONLY.format(node.name), e)\n            if node.typeddict_type:\n                # We special-case TypedDict, because they don't define any constructor.\n                result = 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                result = TypeType(NoneType())\n            else:\n                result = type_object_type(node, self.named_type)\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        elif isinstance(node, MypyFile):\n            # Reference to a module object.\n            result = self.module_type(node)\n        elif isinstance(node, Decorator):\n            if node.func.is_type_check_only and not self.chk.is_stub:\n                self.chk.fail(message_registry.TYPE_CHECK_ONLY.format(node.name), e)\n            result = self.analyze_var_ref(node.var, e)\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            result = self.alias_type_in_runtime_context(\n                node, ctx=e, alias_definition=e.is_alias_rvalue or lvalue\n            )\n        elif isinstance(node, TypeVarExpr):\n            return self.named_type(\"typing.TypeVar\")\n        elif isinstance(node, (ParamSpecExpr, TypeVarTupleExpr)):\n            result = self.object_type()\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        assert result is not None\n        return result\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            result = self.named_type(\"builtins.object\")\n        module_attrs = {}\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            typ = self.chk.determine_type_of_member(n)\n            if typ:\n                module_attrs[name] = typ\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] = AnyType(TypeOfAny.special_form)\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 union_target.uses_pep604_syntax\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.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                if callee_type.implicit:\n                    self.msg.untyped_function_call(callee_type, e)\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                if callee_type.implicit:\n                    self.msg.untyped_function_call(callee_type, e)\n                elif has_untyped_type(callee_type):\n                    # Get module of the function, to get its settings\n                    #  This is fairly sus, and I'm sure there are cases where it gets\n                    #   the wrong module. We should instead set it in CallableType\n                    if isinstance(e.callee, MemberExpr):\n                        if e.callee.kind is None:\n                            # class, kinda hacky\n                            it = get_proper_type(self.chk._type_maps[0][e.callee.expr])\n                            if isinstance(it, CallableType):\n                                # callable class reference\n                                ret_type_ = get_proper_type(it.ret_type)\n                                if isinstance(ret_type_, TupleType):\n                                    callee_module = ret_type_.partial_fallback.type.module_name\n                                elif isinstance(ret_type_, Instance):\n                                    callee_module = ret_type_.type.module_name\n                                else:\n                                    callee_module = None\n                            elif isinstance(it, TypeType):\n                                # type reference\n                                if isinstance(it.item, TupleType):\n                                    callee_module = it.item.partial_fallback.type.module_name\n                                elif isinstance(it.item, Instance):\n                                    callee_module = it.item.type.module_name\n                                elif isinstance(it.item, UnionType):\n                                    # TODO: have to figure out which part of the union has the Untyped\n                                    callee_module = self.chk.tree.name\n                                else:\n                                    callee_module = None\n                            elif isinstance(it, Instance):\n                                # instance reference\n                                callee_module = it.type.module_name\n                            elif isinstance(it, UnionType):\n                                # TODO: have to figure out which part of the union has the Untyped\n                                callee_module = self.chk.tree.name\n                            else:\n                                callee_module = None\n                        else:\n                            # module\n                            assert isinstance(e.callee.expr, RefExpr)\n                            callee_module = e.callee.expr.fullname\n                    elif isinstance(e.callee, NameExpr):\n                        assert e.callee.fullname\n                        if \".\" not in e.callee.fullname:\n                            # local def\n                            callee_module = self.chk.tree.name\n                        else:\n                            callee_module = e.callee.fullname.rpartition(\".\")[0]\n                    elif isinstance(e.callee, MemberExpr) and isinstance(e.callee.expr, NameExpr):\n                        if e.callee.expr.fullname:\n                            callee_module = e.callee.expr.fullname.rpartition(\".\")[0]\n                        elif e.callee.name == \"__init_subclass__\":\n                            t = get_proper_type(callee_type.bound_args[0])\n                            assert isinstance(t, TypeType)\n                            assert isinstance(t.item, Instance)\n                            assert isinstance(t.item.type, TypeInfo)\n                            callee_module = t.item.type.module_name\n                        else:\n                            # TODO: test time error\n                            callee_module = None\n                    else:\n                        # If this branch gets hit then look for a new way to get the module name\n                        # TODO: test time error\n                        callee_module = None\n                    if callee_module:\n                        callee_options = self.chk.options.per_module(callee_module)\n                        if not callee_options.incomplete_is_typed:\n                            self.msg.partially_typed_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, IntersectionType):\n            ret_type = make_simplified_intersection(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            # field lies about its return type and must be special-cased\n            and fullname not in {\"dataclasses.field\", \"pydantic.fields.Field\"}\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.\"\"\"\n        assert isinstance(e.callee, MemberExpr)\n        format_value = None\n        if isinstance(e.callee.expr, StrExpr):\n            format_value = e.callee.expr.value\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, Decorator):\n            defn = defn.func\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        expected_types = list(target.items.values())\n        kinds = [ArgKind.ARG_NAMED] * len(expected_types)\n        names = list(target.items.keys())\n        return CallableType(\n            expected_types,\n            kinds,\n            names,\n            target,\n            self.named_type(\"builtins.type\"),\n            variables=info.defn.type_vars,\n        )\n\n    def typeddict_callable_from_context(self, callee: TypedDictType) -> 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        )\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                var.type = typ\n                del partial_types[var]\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):\n                    # Store inferred partial type.\n                    assert partial_type.type is not None\n                    typename = partial_type.type.fullname\n                    var.type = self.chk.named_generic_type(typename, [key_type, value_type])\n                    del partial_types[var]\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):\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)\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, (NameExpr, MemberExpr)):\n            self.chk.warn_deprecated_overload_item(e.callee.node, e, target=callee_type)\n        if isinstance(e.callee, (RefExpr, CallExpr, LambdaExpr)) and isinstance(\n            proper_callee, CallableType\n        ):\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                if isinstance(e.callee, RefExpr):\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 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                    msg=self.msg,\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, callee)\n        elif isinstance(callee, UnionType):\n            return self.check_union_call(callee, args, arg_kinds, arg_names, context)\n        elif isinstance(callee, IntersectionType):\n            return self.check_intersection_call(\n                callee, args, arg_kinds, arg_names, context, object_type\n            )\n        elif isinstance(callee, Instance):\n            if callee.type.fullname == \"typing.Callable\":\n                # YEAH!!!\n                # this is only the case when union joins are disabled\n                self.chk.fail(\"Cannot call function of unknown type\", context, code=codes.OPERATOR)\n                return AnyType(1), AnyType(1)\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                msg=self.msg,\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        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        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        # 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            need_refresh = any(\n                isinstance(v, (ParamSpecType, TypeVarTupleType)) for v in callee.variables\n            )\n            callee = freshen_function_type_vars(callee)\n            callee = self.infer_function_type_arguments_using_context(callee, context)\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            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                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        res: list[Type | None] = [None] * len(args)\n\n        for i, actuals in enumerate(formal_to_actual):\n            for ai in actuals:\n                if not arg_kinds[ai].is_star():\n                    arg_type = callee.arg_types[i]\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(arg_type)\n                    res[ai] = self.accept(args[ai], arg_type)\n                    # We need to manually restore union inference state, ugh.\n                    type_state.infer_unions = old\n\n        # Fill in the rest of the argument types.\n        for i, t in enumerate(res):\n            if not t:\n                res[i] = self.accept(args[i])\n        assert all(tp is not None for tp in res)\n        return cast(list[Type], 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        if isinstance(ret_type, TypeVarType):\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 = [UntypedType()] * 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        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        return ArgumentInferContext(\n            self.chk.named_type(\"typing.Mapping\"), self.chk.named_type(\"typing.Iterable\")\n        )\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 i, inferred_type in enumerate(inferred_args):\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, i + 1, 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            if kind.is_required() and not formal_to_actual[i] 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                formal_to_actual[i], actual_types, actual_kinds\n            ):\n                if self.chk.in_checked_function() or isinstance(\n                    get_proper_type(actual_types[formal_to_actual[i][0]]), TupleType\n                ):\n                    self.msg.duplicate_argument_value(callee, i, context)\n                    ok = False\n            elif (\n                kind.is_named()\n                and formal_to_actual[i]\n                and actual_kinds[formal_to_actual[i][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 (\n                callee.param_spec() is not None\n                and not formal_to_actual[i]\n                and callee.special_sig != \"partial\"\n            ):\n                self.msg.too_few_arguments(callee, context, actual_names)\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_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        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 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        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                if actual_type is None:\n                    continue  # Some kind of error was already reported.\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            code = 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            self.msg.incompatible_argument_note(\n                original_caller_type, callee_type, context, code=code\n            )\n            if not self.msg.prefer_simple_messages():\n                self.chk.check_possible_missing_await(caller_type, callee_type, context, code)\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        # We perform the infer step with Any's allowed\n        # We do not want `--disallow-any-expr` to affect the inferred types\n        # TODO: consider which other options should not affect the overload inference.\n        disallow_any_expr = self.chk.options.disallow_any_expr\n        self.chk.options.disallow_any_expr = False\n        try:\n            # We suppress notes here for the case of `reveal_type` within a lambda argument.\n            with self.msg.filter_errors(\n                filter_errors=lambda _, error_info: error_info.severity == \"note\"\n            ):\n                arg_types = self.infer_arg_types_in_empty_context(args)\n        finally:\n            self.chk.options.disallow_any_expr = disallow_any_expr\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        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, inferred_types = zip(*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(list(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, 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                return inferred_result\n            return unioned_result\n        elif unioned_result is not None:\n            return unioned_result\n        elif inferred_result is not None:\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        inferred_errors: list[list[ErrorInfo]] = []\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() as w:\n                with self.msg.filter_errors(\n                    filter_errors=lambda _, error_info: error_info.code\n                    in (errorcodes.ANY_EXPR, errorcodes.REVEAL),\n                    save_filtered_errors=True,\n                ) as w2:\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                    self.msg.add_errors(w2.filtered_errors())\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                inferred_errors.append(w2.filtered_errors())\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                self.msg.add_errors(inferred_errors[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                self.msg.add_errors(inferred_errors[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            self.msg.add_errors(inferred_errors[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(self, args: list[Expression], callee: Type) -> tuple[Type, Type]:\n        self.infer_arg_types_in_empty_context(args)\n        callee = get_proper_type(callee)\n        if isinstance(callee, UntypedType):\n            return UntypedType(), UntypedType()\n        elif 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 check_intersection_call(\n        self,\n        callee: IntersectionType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        context: Context,\n        object_type: Type | None = None,\n    ) -> tuple[Type, Type]:\n        def flatten_overloads(\n            t: IntersectionType | FunctionLike, result: list[Type] | None = None\n        ) -> list[Type]:\n            if result is None:\n                result = []\n            for item in t.items:\n                proper_item = get_proper_type(item)\n                if isinstance(proper_item, FunctionLike):\n                    result.extend(proper_item.items)\n                else:\n                    result.append(item)\n            return result\n\n        with self.msg.disable_type_names(), self.msg.filter_errors(save_filtered_errors=True):\n            results: list[CallableType] = []\n            for subtype in flatten_overloads(callee):\n                res = self.check_call(subtype, args, arg_kinds, context, arg_names)\n                if isinstance(get_proper_type(res[1]), CallableType):\n                    results.append(cast(CallableType, res[1]))\n        if not results:\n            report_missing_attribute(\n                callee,\n                callee,\n                \"__call__\",\n                MemberContext(\n                    is_lvalue=False,\n                    is_super=False,\n                    is_operator=True,\n                    original_type=callee,\n                    context=context,\n                    msg=self.chk.msg,\n                    chk=self.chk,\n                    self_type=None,\n                ),\n            )\n            return AnyType(TypeOfAny.from_error), callee\n        if isinstance(context, CallExpr) and isinstance(context.callee, MemberExpr):\n            name = f\"{context.callee.name} of {object_type}\"\n        else:\n            name = format_type_inner(callee, 0, self.chk.options, None)\n        return self.check_call(NamedOverloaded(results, name), args, arg_kinds, context, arg_names)\n\n    def visit_member_expr(self, e: MemberExpr, is_lvalue: bool = False) -> Type:\n        \"\"\"Visit member expression (of form e.id).\"\"\"\n        self.chk.module_refs.update(extract_refexpr_names(e))\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(self, e: MemberExpr, is_lvalue: bool) -> Type:\n        \"\"\"Analyse member expression or member lvalue.\"\"\"\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                msg=self.msg,\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            )\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            msg=self.msg,\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            return typ.copy_modified(\n                last_known_value=LiteralType(\n                    value=value, fallback=typ, line=typ.line, column=typ.column\n                )\n            )\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, 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 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 self.dangerous_comparison(left_type, right_type):\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 self.dangerous_comparison(left_type, right_type):\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    ) -> 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 if there is a custom __eq__() method on either\n        # side. User defined (or even standard library) classes can define this\n        # to return True for comparisons between non-overlapping types.\n        if custom_special_method(left, \"__eq__\") or custom_special_method(right, \"__eq__\"):\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 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    ) -> 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.\n        \"\"\"\n        original_type = original_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            msg=self.msg,\n            original_type=original_type,\n            self_type=base_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            # even though it is mostly a subset of\n            # analyze_member_access.\n            # TODO: Find a way to remove this call without performance implications.\n            if not self.has_member(base_type, op_name):\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                    msg=self.msg,\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            is_subtype(right_type, left_type)\n            and isinstance(left_type, Instance)\n            and isinstance(right_type, Instance)\n            and not (\n                left_type.type.alt_promote is not None\n                and left_type.type.alt_promote.type is right_type.type\n            )\n            and lookup_definer(left_type, op_name) != lookup_definer(right_type, rev_op_name)\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(op_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                if isinstance(obj, Instance) and isinstance(\n                    defn := obj.type.get_method(name), OverloadedFuncDef\n                ):\n                    for item in defn.items:\n                        if (\n                            isinstance(item, Decorator)\n                            and isinstance(typ := item.func.type, CallableType)\n                            and bind_self(typ) == result[1]\n                        ):\n                            self.chk.check_deprecated(item.func, context)\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                # In theory, we should never enter this case, but it seems\n                # we sometimes do, when dealing with Type[...]? E.g. see\n                # check-classes.testTypeTypeComparisonWorks.\n                #\n                # This is probably related to the TODO in lookup_operator(...)\n                # up above.\n                #\n                # TODO: Remove this extra case\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, context: Context) -> 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 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(\n            self.accept(e.left, ctx), \"builtins.bool\"\n        )\n\n        assert e.op in (\"and\", \"or\")  # Checked by visit_op_expr\n\n        if e.right_always:\n            left_map: mypy.checker.TypeMap = None\n            right_map: mypy.checker.TypeMap = {}\n        elif e.right_unreachable:\n            left_map, right_map = {}, None\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 None then we know mypy considers the left expression\n        # to be redundant.\n        if (\n            codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes\n            and left_map is None\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        if (\n            self.chk.should_report_unreachable_issues()\n            and right_map is None\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(right_map, e.right, expanded_left_type)\n\n        if left_map is None and right_map is None:\n            return UninhabitedType()\n\n        if right_map is None:\n            # The boolean expression is statically known to be the left value\n            assert left_map is not None\n            return left_type\n        if left_map is None:\n            # The boolean expression is statically known to be the right value\n            assert right_map is not None\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, left_type: Type, e: IndexExpr, original_type: ProperType | 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).\n        \"\"\"\n        index = e.index\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 self.chk.options.python_version >= (3, 9) and (\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) and not self.has_member(\n            left_type.upper_bound, \"__getitem__\"\n        ):\n            return self.visit_index_with_type(left_type.upper_bound, e, original_type)\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__\", left_type, [e.index], [ARG_POS], e, original_type=original_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        if not is_overlapping_types(source_type, target_type):\n            self.msg.fail(\n                f'Conversion of type \"{source_type}\" to type \"{target_type}\" may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to \"object\" first.',\n                expr,\n                code=errorcodes.BAD_CAST,\n            )\n        options = self.chk.options\n        if (\n            options.warn_redundant_casts\n            and not isinstance(get_proper_type(target_type), AnyType)\n            and 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_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\n            defined = None\n            if isinstance(expr.expr, NameExpr):\n                if isinstance(expr.expr.node, Var):\n                    defined = expr.expr.node.type\n            # TODO: attributes, methods, properties\n            # elif isinstance(expr.expr, MemberExpr):\n            #     if isinstance(expr.expr.expr, NameExpr):\n            #         if isinstance(expr.expr.expr.node, Var):\n            #             ert = expr.expr.expr.node.type\n            #             if isinstance(ert, Instance):\n            #                 a = ert.type.names.get(expr.expr.name)\n            #                 if a:\n            #                     defined = a.type\n\n            if not mypy.options._based:\n                defined = None\n\n            if not self.chk.current_node_deferred:\n                self.msg.reveal_type(revealed_type, expr.expr, defined=defined)\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            # 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                result = 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                result = self.apply_type_arguments_to_callable(\n                    tp, item.partial_fallback.args, tapp\n                )\n            elif isinstance(item, TypedDictType):\n                result = self.typeddict_callable_from_context(item)\n            else:\n                if not tapp.expr.node.python_3_12_type_alias:\n                    self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)\n                result = AnyType(TypeOfAny.from_error)\n            if tapp.expr.node.python_3_12_type_alias:\n                return self.type_alias_type_type()\n            return result\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 isinstance(alias.target, Instance) and alias.target.invalid:  # type: ignore[misc]\n            # An invalid alias, error already has been reported\n            return AnyType(TypeOfAny.from_error)\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        # As an extension to the hack that Callable isn't a real type (#621),\n        #  we additionally pretend that BuiltInFunctionType is a Callable\n        if isinstance(item, CallableType):\n            item = item.fallback\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        if not vars or not any(isinstance(v, TypeVarTupleType) for v in vars):\n            return list(args)\n        # TODO: in future we may want to support type application to variadic functions.\n        assert t.is_type_obj()\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, empty_tuple_index=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                        bound_args=tp.bound_args,\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            for arg, type_var in zip(args, type_vars):\n                proper_type = get_proper_type(arg)\n                if isinstance(proper_type, AnyType):\n                    continue\n                if not isinstance(type_var, TypeVarType) or not type_var.values:\n                    continue\n                if not any(\n                    is_same_type(constraint, proper_type) for constraint in type_var.values\n                ):\n                    # TODO: can we make the context the arg\n                    self.msg.incompatible_typevar_value(\n                        tp, arg, type_var.name, ctx, constrained=True\n                    )\n\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         - no active type context\n         - no star expressions\n         - the joined type of all entries must be an Instance or Tuple type\n        \"\"\"\n        ctx = self.type_context[-1]\n        if ctx:\n            return None\n        rt = self.resolved_type.get(e, None)\n        if rt is not None:\n            return rt if isinstance(rt, Instance) else None\n        values: list[Type] = []\n        for item in e.items:\n            if isinstance(item, StarExpr):\n                # fallback to slow path\n                self.resolved_type[e] = NoneType()\n                return None\n            values.append(self.accept(item))\n        vt = join.join_type_list(values)\n        if not allow_fast_container_literal(vt):\n            self.resolved_type[e] = NoneType()\n            return None\n        ct = self.chk.named_generic_type(container_fullname, [vt])\n        self.resolved_type[e] = ct\n        return ct\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         - no active type context\n         - only supported star expressions are other dict instances\n         - the joined types of all keys and values must be Instance or Tuple types\n        \"\"\"\n        ctx = self.type_context[-1]\n        if ctx:\n            return None\n        rt = self.resolved_type.get(e, None)\n        if rt is not None:\n            return rt if isinstance(rt, Instance) else None\n        keys: list[Type] = []\n        values: list[Type] = []\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                    self.resolved_type[e] = NoneType()\n                    return None\n            else:\n                keys.append(self.accept(key))\n                values.append(self.accept(value))\n        kt = join.join_type_list(keys)\n        vt = join.join_type_list(values)\n        if not (allow_fast_container_literal(kt) and allow_fast_container_literal(vt)):\n            self.resolved_type[e] = NoneType()\n            return None\n        if stargs and (stargs[0] != kt or stargs[1] != vt):\n            self.resolved_type[e] = NoneType()\n            return None\n        dt = self.chk.named_generic_type(\"builtins.dict\", [kt, vt])\n        self.resolved_type[e] = dt\n        return dt\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 = self.find_typeddict_context(self.type_context[-1], e)\n        if typeddict_contexts:\n            if len(typeddict_contexts) == 1:\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            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    ) -> list[TypedDictType]:\n        context = get_proper_type(context)\n        if isinstance(context, TypedDictType):\n            return [context]\n        elif isinstance(context, UnionType):\n            items = []\n            for item in context.items:\n                item_contexts = 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            return items\n        # No TypedDict type in context.\n        return []\n\n    def visit_lambda_expr(self, e: LambdaExpr) -> Type:\n        \"\"\"Type check lambda expression.\"\"\"\n        self.chk.check_default_args(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            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            expr = e.expr()\n            ret_type = self.chk.lookup_type(expr)\n            if (\n                isinstance(expr, CallExpr)\n                and isinstance(expr.callee, (RefExpr, CallExpr, LambdaExpr))\n                and expr.callee.type_guard\n            ):\n                # map the target to the passed position\n                called_type = get_proper_type(self.chk.lookup_type(expr.callee))\n                if isinstance(called_type, Instance):\n                    called_type = get_proper_type(\n                        analyze_member_access(\n                            name=\"__call__\",\n                            typ=called_type,\n                            context=expr,\n                            is_lvalue=False,\n                            is_super=False,\n                            is_operator=True,\n                            msg=self.msg,\n                            original_type=called_type,\n                            chk=self.chk,\n                        )\n                    )\n                assert isinstance(called_type, (CallableType, Overloaded))\n                target = expr.callee.type_guard.target_value\n                new_target = None\n                if target in expr.arg_names:\n                    new_target_arg = expr.args[expr.arg_names.index(target)]  # type: ignore[arg-type]\n                    if isinstance(new_target_arg, NameExpr):\n                        new_target = new_target_arg.name\n                else:\n                    if called_type.items[0].def_extras.get(\"first_arg\") == target:\n                        if isinstance(expr.callee, MemberExpr):\n                            if isinstance(expr.callee.expr, NameExpr):\n                                # TODO: support case when it's not NameExpr\n                                new_target = expr.callee.expr.name\n                        elif isinstance(expr.callee, NameExpr):\n                            new_target = expr.callee.name\n                    elif isinstance(target, int):\n                        pass  # TODO: handle this\n                    else:\n                        idx = called_type.items[0].arg_names.index(target)\n                        it = expr.args[idx]\n                        if isinstance(it, NameExpr) and it.name in e.arg_names:\n                            new_target = it.name\n                if new_target:\n                    inferred_type.type_guard = TypeGuardType(\n                        new_target, expr.callee.type_guard.type_guard\n                    )\n            self.chk.return_types.pop()\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.top_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                    msg=self.msg,\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 UntypedType()\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.top_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            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\n                if true_map:\n                    self.chk.push_type_map(true_map)\n\n                if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes:\n                    if true_map is None:\n                        self.msg.redundant_condition_in_comprehension(False, condition)\n                    elif false_map is None:\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 = 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 if_map is None:\n                self.msg.redundant_condition_in_if(False, e.cond)\n            elif else_map is None:\n                self.msg.redundant_condition_in_if(True, e.cond)\n\n        if_type = self.analyze_cond_branch(\n            if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return\n        )\n\n        # we want to keep the narrowest value of if_type for union'ing the branches\n        # however, it would be silly to pass a literal as a type context. Pass the\n        # underlying fallback type instead.\n        if_type_fallback = simple_literal_type(get_proper_type(if_type)) or if_type\n\n        # Analyze the right branch using full type context and store the type\n        full_context_else_type = self.analyze_cond_branch(\n            else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return\n        )\n\n        if not mypy.checker.is_valid_inferred_type(if_type):\n            # Analyze the right branch disregarding the left branch.\n            else_type = full_context_else_type\n            # we want to keep the narrowest value of else_type for union'ing the branches\n            # however, it would be silly to pass a literal as a type context. Pass the\n            # underlying fallback type instead.\n            else_type_fallback = simple_literal_type(get_proper_type(else_type)) or else_type\n\n            # If it would make a difference, re-analyze the left\n            # branch using the right branch's type as context.\n            if ctx is None or not is_equivalent(else_type_fallback, ctx):\n                # TODO: If it's possible that the previous analysis of\n                # the left branch produced errors that are avoided\n                # using this context, suppress those errors.\n                if_type = self.analyze_cond_branch(\n                    if_map,\n                    e.if_expr,\n                    context=else_type_fallback,\n                    allow_none_return=allow_none_return,\n                )\n\n        elif if_type_fallback == ctx:\n            # There is no point re-running the analysis if if_type is equal to ctx.\n            # That would  be an exact duplicate of the work we just did.\n            # This optimization is particularly important to avoid exponential blowup with nested\n            # if/else expressions: https://github.com/python/mypy/issues/9591\n            # TODO: would checking for is_proper_subtype also work and cover more cases?\n            else_type = full_context_else_type\n        else:\n            # Analyze the right branch in the context of the left\n            # branch's type.\n            else_type = self.analyze_cond_branch(\n                else_map,\n                e.else_expr,\n                context=if_type_fallback,\n                allow_none_return=allow_none_return,\n            )\n\n        # In most cases using if_type as a context for right branch gives better inferred types.\n        # This is however not the case for literal types, so use the full context instead.\n        if is_literal_type_like(full_context_else_type) and not is_literal_type_like(else_type):\n            else_type = full_context_else_type\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] | None,\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 map is None:\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    #\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            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            else:\n                typ = node.accept(self)\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(\n                typ,\n                ignore_in_type_obj=True,\n                ignore_any_from_error=self.chk.options.hide_any_from_error,\n            )\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            # this is more of a placeholder I think\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 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        return (\n            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            or isinstance(typ, ParamSpecType)\n        )\n\n    def has_member(self, typ: Type, member: str) -> bool:\n        \"\"\"Does type have member with the given name?\"\"\"\n        # TODO: refactor this to use checkmember.analyze_member_access, otherwise\n        # these two should be carefully kept in sync.\n        # This is much faster than analyze_member_access, though, and so using\n        # it first as a filter is important for performance.\n        typ = get_proper_type(typ)\n\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, LiteralType):\n            typ = typ.fallback\n        if isinstance(typ, Instance):\n            return typ.type.has_readable_member(member)\n        if isinstance(typ, FunctionLike) and typ.is_type_obj():\n            return typ.fallback.type.has_readable_member(member)\n        elif isinstance(typ, AnyType):\n            return True\n        elif isinstance(typ, UnionType):\n            result = all(self.has_member(x, member) for x in typ.relevant_items())\n            return result\n        elif 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.\n            item = typ.item\n            if isinstance(item, TypeVarType):\n                item = get_proper_type(item.upper_bound)\n            if isinstance(item, TupleType):\n                item = tuple_fallback(item)\n            if isinstance(item, Instance) and item.type.metaclass_type is not None:\n                return self.has_member(item.type.metaclass_type, member)\n            if isinstance(item, AnyType):\n                return True\n            return False\n        else:\n            return False\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            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(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(\n                    known_type, restriction, prohibit_none_typevar_overlap=True\n                ):\n                    return None\n                return narrow_declared_type(known_type, restriction)\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\ndef has_any_type(\n    t: Type, ignore_in_type_obj: bool = False, ignore_any_from_error: bool = False\n) -> bool:\n    \"\"\"Whether t contains an Any type\"\"\"\n    return t.accept(HasAnyType(ignore_in_type_obj, ignore_any_from_error=ignore_any_from_error))\n\n\ndef has_untyped_type(t: Type, ignore_in_type_obj: bool = False) -> bool:\n    \"\"\"Whether ``t`` contains an untyped type\"\"\"\n    return t.accept(HasUntypedType())\n\n\nclass HasAnyType(types.BoolTypeQuery):\n    def __init__(self, ignore_in_type_obj: bool, ignore_any_from_error: bool = False) -> None:\n        super().__init__(types.ANY_STRATEGY)\n        self.ignore_in_type_obj = ignore_in_type_obj\n        self.ignore_any_from_error = ignore_any_from_error\n\n    def visit_any(self, t: AnyType) -> bool:\n        if self.ignore_any_from_error and (\n            t.type_of_any == TypeOfAny.from_error\n            or (\n                t.type_of_any == TypeOfAny.from_another_any\n                and t.source_any\n                and t.source_any.type_of_any == TypeOfAny.from_error\n            )\n        ):\n            return False\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])\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\nclass HasUntypedType(HasAnyType):\n    def __init__(self) -> None:\n        super().__init__(True, True)\n\n    def visit_any(self, t: AnyType) -> bool:\n        return isinstance(t, UntypedType) or t.type_of_any in (\n            TypeOfAny.unannotated,\n            TypeOfAny.from_omitted_generics,\n        )\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 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 Sequence\nfrom typing import TYPE_CHECKING, Callable, cast\n\nfrom mypy import meet, message_registry, subtypes, typeanal\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.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    FuncBase,\n    FuncDef,\n    IndexExpr,\n    MypyFile,\n    NameExpr,\n    OverloadedFuncDef,\n    SymbolNode,\n    SymbolTable,\n    TempNode,\n    TypeAlias,\n    TypeInfo,\n    TypeVarExpr,\n    Var,\n    is_final_node,\n)\nfrom mypy.plugin import AttributeContext\nfrom mypy.typeops import (\n    bind_self,\n    class_callable,\n    erase_to_bound,\n    function_type,\n    get_type_vars,\n    make_simplified_intersection,\n    make_simplified_union,\n    supported_self_type,\n    tuple_fallback,\n    type_object_type_from_function,\n)\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    FunctionLike,\n    Instance,\n    IntersectionType,\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    UnionType,\n    UntypedType,\n    get_proper_type,\n)\nfrom mypy.typetraverser import TypeTraverserVisitor\n\nif TYPE_CHECKING:  # import for forward declaration only\n    import mypy.checker\n\nfrom mypy import state\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        msg: MessageBuilder,\n        chk: mypy.checker.TypeChecker,\n        self_type: Type | None,\n        module_symbol_table: SymbolTable | None = None,\n        no_deferral: bool = False,\n        is_self: 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.msg = msg\n        self.chk = chk\n        self.module_symbol_table = module_symbol_table\n        self.no_deferral = no_deferral\n        self.is_self = is_self\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 copy_modified(\n        self,\n        *,\n        messages: MessageBuilder | None = None,\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            msg=self.msg,\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        )\n        if messages is not None:\n            mx.msg = messages\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    msg: MessageBuilder,\n    original_type: Type,\n    chk: mypy.checker.TypeChecker,\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) -> 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    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        msg=msg,\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    )\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    # TODO: This and following functions share some logic with subtypes.find_member;\n    #       consider refactoring.\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, UntypedType):\n        # The base object isn't typed.\n        return UntypedType()\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, IntersectionType):\n        return analyze_intersection_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        mx.msg.deleted_as_rvalue(typ, mx.context)\n        return AnyType(TypeOfAny.from_error)\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(name, aw_type, mx, override_info)\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    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    if name == \"__init__\" and not mx.is_super:\n        # Accessing __init__ in statically typed code would compromise\n        # type safety unless used via super().\n        mx.msg.fail(message_registry.CANNOT_ACCESS_INIT, mx.context)\n        return AnyType(TypeOfAny.from_error)\n\n    # The base object has an instance type.\n\n    info = typ.type\n    if override_info:\n        info = override_info\n\n    if (\n        state.find_occurrences\n        and info.name == state.find_occurrences[0]\n        and name == state.find_occurrences[1]\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    method = info.get_method(name)\n    if method and not isinstance(method, Decorator):\n        if mx.is_super:\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 (len(items := method.items) > 1):\n                mx.chk.warn_deprecated(items[1], mx.context)\n            return analyze_var(name, getter.var, typ, info, mx)\n\n        if mx.is_lvalue:\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        signature = freshen_all_functions_type_vars(signature)\n        if not method.is_static:\n            # TODO: use proper treatment of special methods on unions instead\n            #       of this hack here and below (i.e. mx.self_type).\n            dispatched_type = meet.meet_types(mx.original_type, typ)\n            signature = check_self_arg(\n                signature, dispatched_type, method.is_class, mx.context, name, mx.msg\n            )\n            signature = bind_self(\n                signature,\n                mx.self_type,\n                is_classmethod=method.is_class,\n                fallback=mx.named_type(\"typing._NamedCallable\"),\n            )\n        # TODO: should we skip these steps for static methods as well?\n        # Since generic static methods should not be allowed.\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        impl = node\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    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, 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_intersection_member_access(\n    name: str, typ: IntersectionType, mx: MemberContext\n) -> Type:\n    results = []\n    for subtype in typ.items:\n        with mx.msg.filter_errors(save_filtered_errors=True) as f:\n            # Self types should be bound to every individual item of an intersection.\n            item_mx = mx.copy_modified(self_type=subtype)\n            res = _analyze_member_access(name, subtype, item_mx)\n            if not f.has_new_errors():\n                results.append(res)\n    if not results:\n        report_missing_attribute(typ, typ, name, mx)\n        return AnyType(TypeOfAny.from_error)\n    return make_simplified_intersection(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    v = lookup_member_var_or_accessor(info, name, mx.is_lvalue)\n\n    mx.chk.warn_deprecated(v, mx.context)\n\n    vv = v\n    if isinstance(vv, Decorator):\n        # The associated Var node of a decorator contains the type.\n        if vv.func.is_type_check_only and not mx.chk.is_stub:\n            message = message_registry.TYPE_CHECK_ONLY.format(vv.name)\n            mx.msg.fail(message.value, mx.context, code=message.code)\n        v = vv.var\n        if mx.is_super:\n            validate_super_call(vv.func, mx)\n\n    if isinstance(vv, TypeInfo):\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.\n        v = Var(name, type=type_object_type(vv, mx.named_type))\n        v.info = info\n\n    if isinstance(vv, TypeAlias):\n        # Similar to the above TypeInfo case, we allow using\n        # qualified type aliases in runtime context if it refers to an\n        # instance type. For example:\n        #     class C:\n        #         A = List[int]\n        #     x = C.A() <- this is OK\n        typ = mx.chk.expr_checker.alias_type_in_runtime_context(\n            vv, ctx=mx.context, alias_definition=mx.is_lvalue\n        )\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, info, mx, implicit=implicit)\n    elif isinstance(v, FuncDef):\n        assert False, \"Did not expect a function\"\n    elif isinstance(v, MypyFile):\n        mx.chk.module_refs.add(v.fullname)\n        return mx.chk.expr_checker.module_type(v)\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,\n                        itype=itype,\n                        info=info,\n                        self_type=mx.self_type,\n                        name=method_name,\n                        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                    info=info,\n                    self_type=mx.self_type,\n                    name=name,\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:\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(\n    descriptor_type: Type, mx: MemberContext, *, assignment: bool = False\n) -> 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__`` 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 descriptor_type.type.has_readable_member(\"__get__\"):\n        return orig_descriptor_type\n\n    dunder_get = descriptor_type.type.get_method(\"__get__\")\n    if dunder_get is None:\n        mx.msg.fail(\n            message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(\n                descriptor_type.str_with_options(mx.msg.options)\n            ),\n            mx.context,\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        info=descriptor_type.type,\n        self_type=descriptor_type,\n        name=\"__get__\",\n        mx=mx,\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    if not assignment:\n        mx.chk.check_deprecated(dunder_get, mx.context)\n        mx.chk.warn_deprecated_overload_item(\n            dunder_get, mx.context, target=inferred_dunder_get_type, selftype=descriptor_type\n        )\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.msg.fail(\n            message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(\n                descriptor_type.str_with_options(mx.msg.options)\n            ),\n            mx.context,\n        )\n        return AnyType(TypeOfAny.from_error)\n\n    return inferred_dunder_get_type.ret_type\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  # Why????\n    )\n\n\ndef analyze_var(\n    name: str,\n    var: Var,\n    itype: Instance,\n    info: TypeInfo,\n    mx: MemberContext,\n    *,\n    implicit: 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    \"\"\"\n    # Found a member variable.\n    original_itype = itype\n    itype = map_instance_to_supertype(itype, var.info)\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 var.is_property and not var.is_settable_property:\n            # TODO allow setting attributes in subclass (although it is probably an error)\n            mx.msg.read_only_property(name, itype.type, mx.context)\n        if mx.is_lvalue and var.is_classvar:\n            mx.msg.cant_assign_to_classvar(name, mx.context)\n        t = freshen_all_functions_type_vars(typ)\n        t = expand_self_type_if_needed(t, mx, var, original_itype)\n        t = expand_type_by_instance(t, itype)\n        freeze_all_type_vars(t)\n        result = t\n        typ = get_proper_type(typ)\n\n        call_type: ProperType | None = None\n        if var.is_initialized_in_class and (not is_instance_var(var) or mx.is_operator):\n            if isinstance(typ, FunctionLike) and not typ.is_type_obj():\n                call_type = typ\n            elif var.is_property:\n                call_type = get_proper_type(_analyze_member_access(\"__call__\", typ, mx))\n            else:\n                call_type = typ\n\n        if isinstance(call_type, FunctionLike) and not call_type.is_type_obj():\n            if mx.is_lvalue:\n                if var.is_property:\n                    if not var.is_settable_property:\n                        mx.msg.read_only_property(name, itype.type, mx.context)\n                else:\n                    mx.msg.cant_assign_to_method(mx.context)\n            if var.is_staticmethod:\n                assert isinstance(get_proper_type(result), CallableType)\n                result = cast(CallableType, result).copy_modified(\n                    fallback=mx.named_type(\"typing._NamedCallable\")\n                )\n            else:\n                # Class-level function objects and classmethods become bound methods:\n                # the former to the instance, the latter to the class.\n                functype: FunctionLike = call_type\n                # Use meet to narrow original_type to the dispatched type.\n                # For example, assume\n                # * A.f: Callable[[A1], None] where A1 <: A (maybe A1 == A)\n                # * B.f: Callable[[B1], None] where B1 <: B (maybe B1 == B)\n                # * x: Union[A1, B1]\n                # In `x.f`, when checking `x` against A1 we assume x is compatible with A\n                # and similarly for B1 when checking against B\n                dispatched_type = meet.meet_types(mx.original_type, itype)\n                signature = freshen_all_functions_type_vars(functype)\n                bound = get_proper_type(expand_self_type(var, signature, mx.original_type))\n                assert isinstance(bound, FunctionLike)\n                signature = bound\n                if signature.is_function or var.is_classmethod:\n                    signature = check_self_arg(\n                        signature, dispatched_type, var.is_classmethod, mx.context, name, mx.msg\n                    )\n                    signature = bind_self(\n                        signature,\n                        mx.self_type,\n                        var.is_classmethod,\n                        fallback=mx.named_type(\"typing._NamedCallable\"),\n                    )\n                expanded_signature = expand_type_by_instance(signature, itype)\n                freeze_all_type_vars(expanded_signature)\n                if var.is_property:\n                    # A property cannot have an overloaded type => the cast is fine.\n                    assert isinstance(expanded_signature, CallableType)\n                    result = expanded_signature.ret_type\n                else:\n                    result = expanded_signature\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    if result and not mx.is_lvalue and not implicit:\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_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 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 lookup_member_var_or_accessor(info: TypeInfo, name: str, is_lvalue: bool) -> SymbolNode | None:\n    \"\"\"Find the attribute/accessor node that refers to a member of a type.\"\"\"\n    # TODO handle lvalues\n    node = info.get(name)\n    if node:\n        return node.node\n    else:\n        return None\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 meet(type(x), A) <: S. If the method is overloaded, we\n    select only overloads items that satisfy this requirement. If there are no matching\n    overloads, an error is generated.\n\n    Note: dispatched_arg_type uses a meet to select a relevant item in case if the\n    original type of 'x' is a union. This is done because several special methods\n    treat union types in ad-hoc manner, so we can't use MemberContext.self_type yet.\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\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        else:\n            selfarg = get_proper_type(item.arg_types[0])\n            # This level of erasure matches the one in checker.check_func_def(),\n            # better keep these two checks consistent.\n            if subtypes.is_subtype(dispatched_arg_type, erase_typevars(erase_to_bound(selfarg))):\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:\n        if is_method:\n            mx.msg.cant_assign_to_method(mx.context)\n        if isinstance(node.node, TypeInfo):\n            mx.msg.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, mx.context)\n\n    # Refuse class attribute access if slot defined\n    if info.slots and name in info.slots:\n        mx.msg.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name), mx.context)\n\n    # If a final attribute was declared on `self` in `__init__`, then it\n    # can't be accessed on the class object.\n    if node.implicit and isinstance(node.node, Var) and node.node.is_final:\n        mx.msg.fail(\n            message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name), mx.context\n        )\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            # 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            def_vars = set(node.node.info.defn.type_vars)\n            if not node.node.is_classvar and node.node.info.self_type:\n                def_vars.add(node.node.info.self_type)\n            typ_vars = set(get_type_vars(t))\n            if def_vars & typ_vars:\n                # Exception: access on Type[...], including first argument of class methods is OK.\n                if not isinstance(get_proper_type(mx.original_type), TypeType) or node.implicit:\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.msg.fail(message, mx.context)\n            t = expand_self_type_if_needed(t, mx, node.node, itype, is_class=True)\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            t = erase_typevars(expand_type_by_instance(t, isuper), {tv.id for tv in def_vars})\n\n        is_classmethod = (is_decorated and cast(Decorator, node.node).func.is_class) or (\n            isinstance(node.node, FuncBase) and node.node.is_class\n        )\n        is_staticmethod = (is_decorated and cast(Decorator, node.node).func.is_static) or (\n            isinstance(node.node, FuncBase) and node.node.is_static\n        )\n        t = get_proper_type(t)\n        if isinstance(t, FunctionLike) and is_classmethod:\n            t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg)\n        result = add_class_tvars(\n            t, isuper, is_classmethod, is_staticmethod, mx.self_type, original_vars=original_vars\n        )\n        if not mx.is_lvalue:\n            result = analyze_descriptor_access(result, mx)\n        proper_type = get_proper_type(result)\n        if (\n            isinstance(node.node, Decorator) and node.node.var.is_staticmethod or is_classmethod\n        ) and isinstance(proper_type, FunctionLike):\n            proper_type.fallback = mx.named_type(\"typing._NamedCallable\")\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, TypeVarExpr):\n        mx.msg.fail(\n            message_registry.CANNOT_USE_TYPEVAR_AS_EXPRESSION.format(info.name, name), mx.context\n        )\n        return AnyType(TypeOfAny.from_error)\n\n    if isinstance(node.node, TypeInfo):\n        return type_object_type(node.node, mx.named_type)\n\n    if isinstance(node.node, MypyFile):\n        # Reference to a module object.\n        return mx.named_type(\"types.ModuleType\")\n\n    if isinstance(node.node, TypeAlias):\n        return mx.chk.expr_checker.alias_type_in_runtime_context(\n            node.node, ctx=mx.context, alias_definition=mx.is_lvalue\n        )\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, FuncBase)\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(typ, is_classmethod=True)\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    # Dunders and private names are not Enum members\n    if name.startswith(\"__\") and name.replace(\"_\", \"\") != \"\":\n        return None\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    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:\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    is_staticmethod: bool,\n    original_type: Type,\n    original_vars: Sequence[TypeVarLikeType] | None = None,\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        is_staticmethod: True if this method is decorated with @staticmethod\n        original_type: The value of the type B in the expression B.foo() or the corresponding\n            component in case of a union (this is used to bind the self-types)\n        original_vars: Type variables of the class callable on which the method was accessed\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        t = freshen_all_functions_type_vars(t)\n        if is_classmethod:\n            t = bind_self(t, original_type, is_classmethod=True)\n        if is_classmethod or is_staticmethod:\n            assert 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(\n                        item,\n                        isuper,\n                        is_classmethod,\n                        is_staticmethod,\n                        original_type,\n                        original_vars=original_vars,\n                    ),\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 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\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    fallback = info.metaclass_type or named_type(\"builtins.type\")\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                    fallback=named_type(typeanal.CALLABLE_NAME),\n                )\n                return class_callable(sig, info, fallback, None, is_new=False)\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        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    return type_object_type_from_function(t, info, method.info, fallback, is_new)\n\n\ndef analyze_decorator_or_funcbase_access(\n    defn: Decorator | FuncBase,\n    itype: Instance,\n    info: TypeInfo,\n    self_type: Type | None,\n    name: str,\n    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, info, mx)\n    return bind_self(\n        function_type(defn, mx.chk.named_type(\"builtins.function\")), original_type=self_type\n    )\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, FuncBase):\n        return True\n    if isinstance(n, Decorator):\n        return isinstance(get_proper_type(n.type), FunctionLike)\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\nimport mypy.checker\nfrom mypy import message_registry\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, Context, Expression, NameExpr, TypeAlias, TypeInfo, 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    Instance,\n    LiteralType,\n    NoneType,\n    ProperType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    get_proper_type,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.typevars import fill_typevars\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: mypy.checker.TypeChecker\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: mypy.checker.TypeChecker, 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 = join_types(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        narrowed_type, rest_type = self.chk.conditional_types_with_intersection(\n            current_type, [get_type_range(typ)], o, default=get_proper_type(typ)\n        )\n        if not isinstance(get_proper_type(narrowed_type), (LiteralType, UninhabitedType)):\n            return PatternType(narrowed_type, UnionType.make_union([narrowed_type, rest_type]), {})\n        return PatternType(narrowed_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        # 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        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        # get inner types of original type\n        #\n        unpack_index = None\n        if isinstance(current_type, TupleType):\n            inner_types = 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        else:\n            inner_type = self.get_sequence_type(current_type, o)\n            if inner_type is None:\n                inner_type = self.chk.named_type(\"builtins.object\")\n            inner_types = [inner_type] * len(o.patterns)\n\n        #\n        # 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        # Calculate new type\n        #\n        new_type: Type\n        rest_type: Type = current_type\n        if isinstance(current_type, TupleType) and unpack_index is None:\n            narrowed_inner_types = []\n            inner_rest_types = []\n            for inner_type, new_inner_type in zip(inner_types, new_inner_types):\n                (narrowed_inner_type, inner_rest_type) = (\n                    self.chk.conditional_types_with_intersection(\n                        inner_type, [get_type_range(new_inner_type)], o, default=inner_type\n                    )\n                )\n                narrowed_inner_types.append(narrowed_inner_type)\n                inner_rest_types.append(inner_rest_type)\n            if all(not is_uninhabited(typ) for typ in narrowed_inner_types):\n                new_type = TupleType(narrowed_inner_types, current_type.partial_fallback)\n            else:\n                new_type = UninhabitedType()\n\n            if all(is_uninhabited(typ) for typ in inner_rest_types):\n                # All subpatterns always match, so we can apply negative narrowing\n                rest_type = TupleType(rest_inner_types, current_type.partial_fallback)\n            elif sum(not is_uninhabited(typ) for typ in inner_rest_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, inner_rest_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            if isinstance(current_type, TypeVarType):\n                new_bound = self.narrow_sequence_child(current_type.upper_bound, new_inner_type, o)\n                new_type = current_type.copy_modified(upper_bound=new_bound)\n            else:\n                new_type = self.narrow_sequence_child(current_type, new_inner_type, o)\n        return PatternType(new_type, rest_type, captures)\n\n    def get_sequence_type(self, t: Type, context: Context) -> Type | None:\n        t = get_proper_type(t)\n        if isinstance(t, AnyType):\n            return AnyType(TypeOfAny.from_another_any, t)\n        if isinstance(t, UnionType):\n            items = [self.get_sequence_type(item, context) for item in t.items]\n            not_none_items = [item for item in items if item is not None]\n            if not_none_items:\n                return make_simplified_union(not_none_items)\n            else:\n                return None\n\n        if self.chk.type_is_iterable(t) and isinstance(t, (Instance, TupleType)):\n            if isinstance(t, TupleType):\n                t = tuple_fallback(t)\n            return self.chk.iterable_item_type(t, context)\n        else:\n            return None\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 narrow_sequence_child(self, outer_type: Type, inner_type: Type, ctx: Context) -> Type:\n        new_type = self.construct_sequence_child(outer_type, inner_type)\n        if is_subtype(new_type, outer_type):\n            new_type, _ = self.chk.conditional_types_with_intersection(\n                outer_type, [get_type_range(new_type)], ctx, default=outer_type\n            )\n        else:\n            new_type = outer_type\n        return new_type\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        if can_match:\n            # We can't narrow the type here, as Mapping key is invariant.\n            new_type = self.type_context[-1]\n        else:\n            new_type = UninhabitedType()\n        return PatternType(new_type, current_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 type_info is None:\n            return PatternType(AnyType(TypeOfAny.from_error), AnyType(TypeOfAny.from_error), {})\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        if isinstance(type_info, TypeInfo):\n            any_type = AnyType(TypeOfAny.implementation_artifact)\n            args: list[Type] = []\n            for tv in type_info.defn.type_vars:\n                if isinstance(tv, TypeVarTupleType):\n                    args.append(\n                        UnpackType(self.chk.named_generic_type(\"builtins.tuple\", [any_type]))\n                    )\n                else:\n                    args.append(any_type)\n            typ: Type = Instance(type_info, args)\n        elif isinstance(type_info, TypeAlias):\n            typ = type_info.target\n        elif (\n            isinstance(type_info, Var)\n            and type_info.type is not None\n            and isinstance(get_proper_type(type_info.type), AnyType)\n        ):\n            typ = type_info.type\n        else:\n            if isinstance(type_info, Var) and type_info.type is not None:\n                name = type_info.type.str_with_options(self.options)\n            else:\n                name = type_info.name\n            self.msg.fail(message_registry.CLASS_PATTERN_TYPE_REQUIRED.format(name), o)\n            return self.early_non_match()\n\n        new_type, rest_type = self.chk.conditional_types_with_intersection(\n            current_type, [get_type_range(typ)], 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                        msg=self.msg,\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                        msg=self.msg,\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                self.msg.fail(\n                    message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format(\n                        typ.str_with_options(self.options), keyword\n                    ),\n                    pattern,\n                )\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 should_self_match(self, typ: Type) -> bool:\n        typ = get_proper_type(typ)\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, 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)\n    node = expr.node\n    assert isinstance(node, Var)\n    return node\n\n\ndef get_type_range(typ: Type) -> mypy.checker.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 mypy.checker.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 re import Match, Pattern\nfrom typing import TYPE_CHECKING, Callable, Final, Union, cast\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nimport mypy.errorcodes as codes\nfrom mypy.errors import Errors\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.types import (\n    AnyType,\n    Instance,\n    LiteralType,\n    NoneType,\n    ProperType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeStrVisitor,\n    TypeVarTupleType,\n    TypeVarType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    get_proper_type,\n    get_proper_types,\n)\n\nif TYPE_CHECKING:\n    # break import cycle only needed for mypy\n    import mypy.checker\n    import mypy.checkexpr\n\nfrom mypy import message_registry\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.messages import MessageBuilder\nfrom mypy.parse import parse\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import custom_special_method\n\nFormatStringExpr: _TypeAlias = Union[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\", \"\")\n        self.flags = m_dict.get(\"flags\", \"\")\n        self.width = m_dict.get(\"width\", \"\")\n        self.precision = m_dict.get(\"precision\", \"\")\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: mypy.checker.TypeChecker\n    # This is shared with TypeChecker, but stored also here for convenience.\n    msg: MessageBuilder\n    # Some services are provided by a ExpressionChecker instance.\n    exprchk: mypy.checkexpr.ExpressionChecker\n\n    def __init__(\n        self,\n        exprchk: mypy.checkexpr.ExpressionChecker,\n        chk: mypy.checker.TypeChecker,\n        msg: MessageBuilder,\n    ) -> None:\n        \"\"\"Construct an expression type checker.\"\"\"\n        self.chk = chk\n        self.exprchk = exprchk\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        if (\n            format_value == \"{:{}}\"\n            and len(call.args) == 2\n            and isinstance(arg := call.args[1], StrExpr)\n        ):\n            f_string = True\n            conv_specs = parse_format_value(f\"{{:{arg.value}}}\", call, self.msg)\n        else:\n            f_string = False\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, f_string=f_string)\n\n    def check_specs_in_format_call(\n        self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str, f_string=False\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        if f_string:\n            replacements = [call.args[0]]\n        else:\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            if f_string:\n                repl = call.args[0]\n            else:\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                self.helpful_check(a_type, call)\n                if custom_special_method(a_type, \"__format__\"):\n                    if spec.format_spec:\n                        self.check_datetime(a_type, spec.format_spec, call)\n                    continue\n                if spec.format_spec not in {None, \":\"}:\n                    if not self.check_builtins_type(a_type, call):\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 helpful_check(self, actual_type: ProperType, context: Context) -> bool:\n        if isinstance(actual_type, (TupleType, TypedDictType, LiteralType)):\n            return True\n        bad_builtin = False\n        if isinstance(actual_type, Instance):\n            if \"dataclass\" in actual_type.type.metadata:\n                return True\n            # TODO: improve this or add a configuration option or something\n            if actual_type.type.fullname == \"builtins.object\":\n                bad_builtin = True\n            else:\n                for base in actual_type.type.mro[:-1]:\n                    if base.fullname in {\n                        \"builtins.map\",\n                        \"builtins.filter\",\n                        \"builtins.super\",\n                        \"builtins.enumerate\",\n                        \"builtins.reversed\",\n                        \"builtins.zip\",\n                    }:\n                        bad_builtin = True\n                        break\n                    if base.module_name == \"builtins\":\n                        return True\n        type_string = actual_type.accept(TypeStrVisitor(options=self.chk.options))\n        if (\n            custom_special_method(actual_type, \"__format__\")\n            or custom_special_method(actual_type, \"__str__\")\n            or custom_special_method(actual_type, \"__repr__\")\n        ):\n            return True\n        if bad_builtin or isinstance(actual_type, NoneType):\n            self.msg.fail(\n                f'The string for \"{type_string}\" isn\\'t helpful in a user-facing or semantic string',\n                context,\n                code=codes.HELPFUL_STRING,\n            )\n        else:\n            self.msg.fail(\n                f'The type \"{type_string}\" doesn\\'t define a __format__, __str__ or __repr__ method',\n                context,\n                code=codes.HELPFUL_STRING,\n            )\n        return False\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    ) -> bool:\n        # TODO: try refactoring to combine this logic with % formatting.\n        failed = False\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                    failed = 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                failed = True\n        if spec.flags:\n            numeric_types = UnionType(\n                [\n                    self.named_type(\"builtins.int\"),\n                    self.named_type(\"builtins.float\"),\n                    self.named_type(\"builtins.complex\"),\n                ]\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                failed = True\n        return failed\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.exprchk.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.exprchk.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 check_builtins_type(self, typ: Type, context: Context) -> bool:\n        valid = UnionType(\n            [\n                self.named_type(\"builtins.bytes\"),\n                self.named_type(\"builtins.str\"),\n                self.named_type(\"builtins.int\"),\n                self.named_type(\"builtins.float\"),\n                self.named_type(\"builtins.complex\"),\n            ]\n        )\n        if not is_subtype(typ, valid):\n            self.msg.fail(\n                f'The type \"{typ.accept(TypeStrVisitor(options=self.chk.options))}\" doesn\\'t support format-specifiers',\n                context,\n                code=codes.STRING_FORMATTING,\n                notes=[\"Maybe you want to add '!s' to the conversion\"],\n            )\n            return False\n        return True\n\n    def check_datetime(self, typ: Type, spec: str, ctx: Context):\n        proper = get_proper_type(typ)\n        if not (isinstance(proper, Instance) and proper.type.has_base(\"datetime.date\")):\n            return\n        if proper.type.fullname not in {\n            \"datetime.date\",\n            \"datetime.datetime\",\n        } and custom_special_method(proper, \"__format__\", check_all=True):\n            return\n        p = False\n        colon = False\n        for char in spec:\n            if colon:\n                if char != \"z\":\n                    self.msg.fail(\n                        f\"Invalid format sequence '%:{char}', escape with '%%'\",\n                        ctx,\n                        code=codes.STRING_FORMATTING,\n                    )\n                elif self.chk.options.python_version < (3, 12):\n                    self.msg.fail(\n                        \"Format sequence '%:z' is new in version 3.12\",\n                        ctx,\n                        code=codes.STRING_FORMATTING,\n                    )\n                colon = False\n                continue\n            if char == \"%\" and not p:\n                p = True\n                continue\n            if p:\n                if char == \":\":\n                    colon = True\n                elif char not in \"aAwdbBmyYHIpMSfzZjUWcxX%GuV\":\n                    self.msg.fail(\n                        f\"Invalid format sequence '%{char}', escape with '%%'\",\n                        ctx,\n                        code=codes.STRING_FORMATTING,\n                    )\n            p = False\n        if p:\n            self.msg.fail(\n                \"Invalid trailing '%', escape with '%%'\", ctx, code=codes.STRING_FORMATTING\n            )\n        if colon:\n            self.msg.fail(\n                \"Invalid trailing '%:', escape with '%%'\", ctx, 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                    self.named_type(\"builtins.complex\"),\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\nfrom mypy.errorcodes import error_codes\n\nif sys.version_info >= (3, 11):\n    import tomllib\nelse:\n    import tomli as tomllib\n\nfrom collections.abc import Iterable, Mapping, MutableMapping, Sequence\nfrom typing import Any, Callable, Final, TextIO, Union, cast\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nfrom mypy import defaults\nfrom mypy.options import PER_MODULE_OPTIONS, Options\n\n_CONFIG_VALUE_TYPES: _TypeAlias = Union[\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\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 argparse.ArgumentTypeError(msg)\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], split_regex: str = \"[,]\") -> list[str]:\n    \"\"\"Split and trim a str or list of str into a list of str\"\"\"\n    if isinstance(v, str):\n        return [p.strip() for p in cast(list[str], re.split(split_regex, v))]\n\n    return [p.strip() for p in v]\n\n\ndef validate_codes(codes: list[str]) -> list[str]:\n    invalid_codes = set(codes) - set(error_codes.keys())\n    if invalid_codes:\n        raise argparse.ArgumentTypeError(\n            f\"Invalid error code(s): {', '.join(sorted(invalid_codes))}\"\n        )\n    return codes\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(paths.split(\",\"))\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: validate_codes([p.strip() for p in split_commas(s)]),\n    \"enable_error_code\": lambda s: validate_codes([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: validate_codes(try_split(s)),\n        \"enable_error_code\": lambda s: validate_codes(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_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    if filename is not None:\n        config_files: tuple[str, ...] = (filename,)\n    else:\n        config_files_iter: Iterable[str] = map(os.path.expanduser, defaults.CONFIG_FILES)\n        config_files = tuple(config_files_iter)\n\n    config_parser = configparser.RawConfigParser()\n\n    for config_file in config_files:\n        if not os.path.exists(config_file):\n            continue\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                    continue\n                toml_data = {\"mypy\": toml_data[\"mypy\"]}\n                parser: MutableMapping[str, Any] = destructure_overrides(toml_data)\n                config_types = toml_config_types\n            else:\n                config_parser.read(config_file)\n                parser = config_parser\n                config_types = ini_config_types\n        except (tomllib.TOMLDecodeError, configparser.Error, ConfigTOMLValueError) as err:\n            print(f\"{config_file}: {err}\", file=stderr)\n        else:\n            if config_file in defaults.SHARED_CONFIG_FILES and \"mypy\" not in parser:\n                continue\n            file_read = config_file\n            options.config_file = file_read\n            break\n    else:\n        return\n\n    os.environ[\"MYPY_CONFIG_FILE_DIR\"] = os.path.dirname(os.path.abspath(config_file))\n\n    if \"mypy\" not in parser:\n        if filename or file_read not in defaults.SHARED_CONFIG_FILES:\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 '{cast(str, 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        options_key = key\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, 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, key[3:]):\n                    options_key = key[3:]\n                    invert = True\n                elif key.startswith(\"allow\") and hasattr(template, \"dis\" + key):\n                    options_key = \"dis\" + key\n                    invert = True\n                elif key.startswith(\"disallow\") and hasattr(template, key[3:]):\n                    options_key = key[3:]\n                    invert = True\n                elif key.startswith(\"show_\") and hasattr(template, \"hide_\" + key[5:]):\n                    options_key = \"hide_\" + 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)\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 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\n    errors: list[tuple[int, str]] = []\n    sections = {}\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        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\n        sections.update(new_sections)\n\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, Union\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 = Union[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, cast\nfrom typing_extensions import TypeGuard\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    IntersectionType,\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    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    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 = []\n\n    incomplete_star_mapping = False\n    for i, actuals in enumerate(formal_to_actual):\n        for actual in actuals:\n            if actual is None and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):\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\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    if isinstance(template, IntersectionType):\n        template = mypy.typeops.make_simplified_intersection(template.items, keep_erased=True)\n    if isinstance(actual, IntersectionType):\n        actual = mypy.typeops.make_simplified_intersection(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        if not isinstance(get_proper_type(template.upper_bound), CallableType):\n            generic_bound = _infer_constraints(\n                template.upper_bound, actual, direction, skip_neg_op\n            )\n        else:\n            # HACK: Disregard CallableType because `(*Any, **Any) -> object`\n            #  will produce unwanted constraints\n            generic_bound = []\n        return generic_bound + [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, IntersectionType)) 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 unwraped ``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        # If some of items is not a complete type, disregard that.\n        items = simplify_away_incomplete_types(actual.items)\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            [infer_constraints_if_possible(template, a_item, direction) for a_item in items],\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=False,\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    if direction == SUBTYPE_OF and isinstance(actual, IntersectionType):\n        return any_constraints(\n            [\n                infer_constraints_if_possible(template, a_item, direction, preserve_typevars=True)\n                for a_item in actual.items\n            ],\n            eager=True,\n        )\n\n    if direction == SUPERTYPE_OF and isinstance(actual, IntersectionType):\n        items = simplify_away_incomplete_types(actual.items)\n        return any_constraints(\n            [infer_constraints(template, a_item, direction) for a_item in items], eager=True\n        )\n    if direction == SUBTYPE_OF and isinstance(template, IntersectionType):\n        return any_constraints(\n            [\n                infer_constraints_if_possible(t_item, actual, direction)\n                for t_item in template.items\n            ],\n            eager=False,\n        )\n    if direction == SUPERTYPE_OF and isinstance(template, IntersectionType):\n        return any_constraints(\n            [\n                infer_constraints_if_possible(t_item, actual, direction, preserve_typevars=True)\n                for t_item in template.items\n            ],\n            eager=False,\n        )\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, preserve_typevars=False\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        and not preserve_typevars\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                if option is not None:\n                    merged_option: list[Constraint] | None = [merge_with_any(c) for c in option]\n                else:\n                    merged_option = None\n                merged_options.append(merged_option)\n            return any_constraints(list(merged_options), 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    # 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    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 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\ndef simplify_away_incomplete_types(types: Iterable[Type]) -> list[Type]:\n    complete = [typ for typ in types if is_complete_type(typ)]\n    if complete:\n        return complete\n    else:\n        return list(types)\n\n\ndef is_complete_type(typ: Type) -> bool:\n    \"\"\"Is a type complete?\n\n    A complete doesn't have uninhabited type components or (when not in strict\n    optional mode) None components.\n    \"\"\"\n    return typ.accept(CompleteTypeVisitor())\n\n\nclass CompleteTypeVisitor(TypeQuery[bool]):\n    def __init__(self) -> None:\n        super().__init__(all)\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> bool:\n        return False\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 mypy.subtypes.is_subtype(actual, erase_typevars(call)):\n                        subres = infer_constraints(call, actual, self.direction)\n                        res.extend(subres)\n                    template.type.inferring.pop()\n        if isinstance(actual, CallableType) and actual.fallback is not None:\n            if actual.is_type_obj() and template.type.is_protocol:\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                    if self.direction == SUBTYPE_OF:\n                        subtype = template\n                    else:\n                        subtype = ret_type\n                    res.extend(\n                        self.infer_constraints_from_protocol_members(\n                            ret_type, template, subtype, template, class_obj=True\n                        )\n                    )\n            actual = actual.fallback\n        if isinstance(actual, TypeType) and template.type.is_protocol:\n            if isinstance(actual.item, Instance):\n                if self.direction == SUBTYPE_OF:\n                    subtype = template\n                else:\n                    subtype = actual.item\n                res.extend(\n                    self.infer_constraints_from_protocol_members(\n                        actual.item, template, subtype, template, class_obj=True\n                    )\n                )\n            if self.direction == SUPERTYPE_OF:\n                # Infer constraints for Type[T] via metaclass of T when it makes sense.\n                a_item = actual.item\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.as_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                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            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()\n        extra_tvars = False\n        if isinstance(self.actual, CallableType):\n            res: list[Constraint] = []\n            cactual = self.actual.with_unpacked_kwargs()\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.type_guard\n                cactual_ret_type = cactual.type_guard.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 any(tv.id.is_self() for tv in cactual.variables)\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            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_intersection_type(self, template: IntersectionType) -> list[Constraint]:\n        return []\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        for t in 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    IntersectionType,\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        dup.metadata = t.metadata.copy()\n        dup.invalid = t.invalid\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_intersection_type(self, t: IntersectionType) -> ProperType:\n        return self.copy_common(t, IntersectionType(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)))\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, 9)\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, 8)  # Keep in sync with typeshed's python support\n\n\ndef find_pyproject() -> str:\n    \"\"\"Search for file pyproject.toml in the parent directories recursively.\n\n    It resolves symlinks, so if there is any symlink up in the tree, it does not respect them\n\n    If the file is not found until the root of FS or repository, PYPROJECT_FILE is used\n    \"\"\"\n\n    def is_root(current_dir: str) -> bool:\n        parent = os.path.join(current_dir, os.path.pardir)\n        return os.path.samefile(current_dir, parent) or any(\n            os.path.isdir(os.path.join(current_dir, cvs_root)) for cvs_root in (\".git\", \".hg\")\n        )\n\n    # Preserve the original behavior, returning PYPROJECT_FILE if exists\n    if os.path.isfile(PYPROJECT_FILE) or is_root(os.path.curdir):\n        return PYPROJECT_FILE\n\n    # And iterate over the tree\n    current_dir = os.path.pardir\n    while not is_root(current_dir):\n        config_file = os.path.join(current_dir, PYPROJECT_FILE)\n        if os.path.isfile(config_file):\n            return config_file\n        parent = os.path.join(current_dir, os.path.pardir)\n        current_dir = parent\n\n    return PYPROJECT_FILE\n\n\nCACHE_DIR: Final = \".mypy_cache\"\nBASELINE_FILE: Final = \".mypy/baseline.json\"\nCONFIG_FILE: Final = [\"mypy.ini\", \".mypy.ini\"]\nPYPROJECT_FILE: Final = \"pyproject.toml\"\nPYPROJECT_CONFIG_FILES: Final = [find_pyproject()]\nSHARED_CONFIG_FILES: Final = [\"setup.cfg\"]\nUSER_CONFIG_FILES: Final = [\"~/.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\"))\n\nCONFIG_FILES: Final = (\n    CONFIG_FILE + PYPROJECT_CONFIG_FILES + SHARED_CONFIG_FILES + USER_CONFIG_FILES\n)\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"
  },
  {
    "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 base64\nimport json\nimport os\nimport pickle\nimport sys\nimport time\nimport traceback\nfrom argparse import RawTextHelpFormatter\nfrom collections.abc import Mapping\nfrom typing import Any, Callable, NoReturn\n\nfrom mypy.dmypy_os import alive, kill\nfrom mypy.dmypy_util import DEFAULT_STATUS_FILE, receive, send\nfrom mypy.ipc import IPCClient, IPCException\nfrom mypy.util import check_python_version, get_terminal_width, should_force_color\nfrom mypy.version import __based_version__, __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) -> None:\n        super().__init__(prog=prog, max_help_position=30)\n\n\nparser = argparse.ArgumentParser(\n    prog=\"dmypy\",\n    description=\"Client for mypy daemon mode\",\n    fromfile_prefix_chars=\"@\",\n    formatter_class=RawTextHelpFormatter,\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\", \"--version\", action=\"store_true\", 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)\np.add_argument(\"--legacy\", action=\"store_true\", help=argparse.SUPPRESS)\n\"\"\"This is just here for running tests\"\"\"\nhelp_parser = p = subparsers.add_parser(\"help\")\n\ndel p\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 main(argv: list[str]) -> None:\n    \"\"\"The code is top-down.\"\"\"\n    check_python_version(\"dmypy\")\n    args = parser.parse_args(argv)\n    if args.version:\n        if \"VSCODE_PID\" in os.environ:\n            # vscode is looking for upstreams output\n            print(f\"dmypy {__version__}\")\n        else:\n            print(f\"Basedmypy-Daemon {__based_version__}\\nBased on dmypy {__version__}\")\n        return\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=__based_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=__based_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 \"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    import mypy.options\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.legacy:\n        mypy.options._based = False\n\n    if args.options_data:\n        from mypy.options import Options\n\n        options_dict = pickle.loads(base64.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    if args.legacy:\n        if not os.getenv(\"__MYPY_UNDER_TEST__\"):\n            mypy.options._based = True\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 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: Any = json.load(f)\n        except Exception as e:\n            raise BadStatus(\"Malformed status file (not JSON)\") from e\n    if not isinstance(data, dict):\n        raise BadStatus(\"Invalid status file (not a dict)\")\n    return data\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 typing import Any, Callable\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  # type: ignore[explicit-any, unused-ignore]\n\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 base64\nimport io\nimport json\nimport os\nimport pickle\nimport subprocess\nimport sys\nimport time\nimport traceback\nfrom collections.abc import Sequence, Set as AbstractSet\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom typing import Any, Callable, Final\nfrom typing_extensions import TypeAlias as _TypeAlias\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, getattr\nfrom mypy.version import __based_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=\"{base64.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        if not mypy.options._based:\n            command.append(\"--legacy\")\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                    if not (sys.stdout.isatty() or sys.stderr.isatty()):\n                        self.options.color_output = False  # needed so that initialize_unix_colors doesn't try to get the `fileno` of the WriteToConn\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 __based_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        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            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                for dep in state.dependencies:\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\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  # type: ignore[any, unused-ignore]\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  # type: ignore[any, unused-ignore]\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 Container\nfrom typing import Callable, 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    IntersectionType,\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_intersection_type(self, t: IntersectionType) -> ProperType:\n        erased_items = [erase_type(item) for item in t.items]\n        from mypy.typeops import make_simplified_intersection\n\n        return make_simplified_intersection(erased_items)\n\n    def visit_type_type(self, t: TypeType) -> ProperType:\n        return TypeType.make_normalized(t.item.accept(self), line=t.line)\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    def erase_id(id: TypeVarId) -> bool:\n        if ids_to_erase is None:\n            return True\n        return id in ids_to_erase\n\n    return t.accept(TypeVarEraser(erase_id, AnyType(TypeOfAny.special_form)))\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(lambda id: id.is_meta_var(), target_type))\n\n\nclass TypeVarEraser(TypeTranslator):\n    \"\"\"Implementation of type erasure\"\"\"\n\n    def __init__(self, erase_id: Callable[[TypeVarId], bool], 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(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_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n        if 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        if 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"
  },
  {
    "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                \"message\": error.message,\n                \"hint\": None if len(error.hints) == 0 else \"\\n\".join(error.hints),\n                \"code\": None if error.errorcode is None else error.errorcode.code,\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 __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] = 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] = ErrorCode(\n    \"valid-type\", \"Check that type (annotation) is valid\", \"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] = ErrorCode(\n    \"return\", \"Check that function always returns a value\", \"General\"\n)\nRETURN_VALUE: Final[ErrorCode] = ErrorCode(\n    \"return-value\", \"Check that return value is compatible with signature\", \"General\"\n)\nASSIGNMENT: Final[ErrorCode] = ErrorCode(\n    \"assignment\", \"Check that assigned value is compatible with target\", \"General\"\n)\nMETHOD_ASSIGN: Final[ErrorCode] = 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)\nHELPFUL_STRING: Final = ErrorCode(\n    \"helpful-string\", \"Check that string conversions are useful\", \"General\", default_enabled=False\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)\n# TODO: why do we need the explicit type here? Without it mypyc CI builds fail with\n# mypy/message_registry.py:37: error: Cannot determine type of \"EMPTY_BODY\"  [has-type]\nEMPTY_BODY: Final[ErrorCode] = 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] = 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)\nNO_UNTYPED_USAGE: Final = ErrorCode(\n    \"no-untyped-usage\",\n    \"Disallow using members without type annotations\",\n    \"General\",\n    default_enabled=False,\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 = ErrorCode(\n    \"annotation-unchecked\", \"Notify about type annotations in unchecked functions\", \"General\"\n)\nTYPEDDICT_READONLY_MUTATED = ErrorCode(\n    \"typeddict-readonly-mutated\", \"TypedDict's ReadOnly key is mutated\", \"General\"\n)\nPOSSIBLY_UNDEFINED: Final[ErrorCode] = 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] = 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] = ErrorCode(\n    \"truthy-function\",\n    \"Warn about function that always evaluate to true in boolean contexts\",\n    \"General\",\n)\nTRUTHY_ITERABLE: Final[ErrorCode] = 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)\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)\nUNSAFE_VARIANCE: Final[ErrorCode] = ErrorCode(\n    \"unsafe-variance\", \"Incorrect usages of variance\", \"General\"\n)\nREDUNDANT_SELF_TYPE = 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] = 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] = ErrorCode(\n    \"mutable-override\",\n    \"Reject covariant overrides for mutable attributes\",\n    \"General\",\n    default_enabled=False,\n)\n\nNO_ANY_EXPR: Final = ErrorCode(\"no-any-expr\", \"An expression contains Any\", \"General\")\nNO_ANY_EXPLICIT: Final = ErrorCode(\"no-any-explicit\", \"Usage of the Any type\", \"General\")\nNO_SUBCLASS_ANY: Final = ErrorCode(\"no-subclass-any\", \"Usage of Any as a class base\", \"General\")\nNO_ANY_DECORATED: Final = ErrorCode(\n    \"no-any-decorated\", \"Decorated function contains Any\", \"General\"\n)\n\nANY_EXPR: Final = ErrorCode(\"any\", \"An expression contains Any\", \"General\")\nSUBCLASS_ANY: Final = ErrorCode(\"subclass-any\", \"Usage of Any as a class base\", \"General\")\nDECORATED_ANY: Final = ErrorCode(\"decorated-any\", \"Decorated function contains Any\", \"General\")\nTYPEGUARD_SUBTYPE: Final = ErrorCode(\n    \"typeguard-subtype\",\n    \"A typeguard's type must be assignable to its parameter's type\",\n    \"General\",\n    sub_code_of=ASSIGNMENT,\n)\nTYPEGUARD_LIMITATION: Final[ErrorCode] = ErrorCode(\n    \"typeguard-limitation\", \"mypy limitation\", \"General\"\n)\nBAD_CAST: Final[ErrorCode] = ErrorCode(\n    \"bad-cast\", \"cast of non-overlapping types\", \"General\", default_enabled=False\n)\nCALLABLE_FUNCTIONTYPE: Final[ErrorCode] = ErrorCode(\n    \"callable-functiontype\",\n    \"usages of Callable and FunctionType\",\n    \"General\",\n    default_enabled=False,\n)\nPOSSIBLE_FUNCTION: Final[ErrorCode] = ErrorCode(\n    \"possible-function\", \"possible FunctionType on class\", \"General\", default_enabled=False\n)\nUNHANDLED_SCENARIO: Final[ErrorCode] = ErrorCode(\n    \"unhandled-scenario\",\n    \"an unknown error occurred. raise an issue\",\n    \"General\",\n    default_enabled=False,\n)\n\nREGEX: Final = ErrorCode(\"regex\", \"Regex related errors\", \"General\")\nTYPE_CHECK_ONLY: Final[ErrorCode] = ErrorCode(\n    \"type-check-only\", \"Value doesn't exist at runtime\", \"General\"\n)\nREVEAL: Final = ErrorCode(\"reveal\", \"Reveal types at check time\", \"General\")\n\n# Syntax errors are often blocking.\nSYNTAX: Final[ErrorCode] = ErrorCode(\"syntax\", \"Report syntax errors\", \"General\")\n\n# This is an internal marker code for a whole-file ignore. It is not intended to\n# be user-visible.\nFILE: Final = ErrorCode(\"file\", \"Internal marker for a whole file being ignored\", \"General\")\ndel error_codes[FILE.code]\n\n# This is a catch-all for remaining uncategorized errors.\nMISC: Final[ErrorCode] = ErrorCode(\"misc\", \"Miscellaneous other checks\", \"General\")\n\nOVERLOAD_CANNOT_MATCH: Final[ErrorCode] = ErrorCode(\n    \"overload-cannot-match\",\n    \"Warn if an @overload signature can never be matched\",\n    \"General\",\n    sub_code_of=MISC,\n)\n\n\nOVERLOAD_OVERLAP: Final[ErrorCode] = 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 = ErrorCode(\n    \"prop-decorator\",\n    \"Decorators on top of @property are not supported\",\n    \"General\",\n    sub_code_of=MISC,\n)\n\nNARROWED_TYPE_NOT_SUBTYPE: Final[ErrorCode] = 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 re\nimport sys\nimport traceback\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom copy import deepcopy\nfrom typing import Callable, Final, NoReturn, Optional, TextIO, TypeVar, cast\nfrom typing_extensions import Literal, TypeAlias as _TypeAlias, TypedDict\n\nfrom mypy import errorcodes as codes\nfrom mypy.error_formatter import ErrorFormatter\nfrom mypy.errorcodes import (\n    IMPORT,\n    IMPORT_NOT_FOUND,\n    IMPORT_UNTYPED,\n    REVEAL,\n    ErrorCode,\n    mypy_error_codes,\n)\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.options import Options\nfrom mypy.scope import Scope\nfrom mypy.util import DEFAULT_SOURCE_OFFSET, is_typeshed_file\nfrom mypy.version import __based_version__ as basedmypy_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, codes.DEPRECATED}\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    codes.REVEAL,\n}\n\nallowed_duplicates: Final = [\"@overload\", \"Got:\", \"Expected:\"]\n\nBASE_RTD_URL: Final = \"https://kotlinisland.github.io/basedmypy/_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 = {\n    codes.LITERAL_REQ: codes.MISC,\n    codes.TYPE_ABSTRACT: codes.MISC,\n    codes.NO_ANY_EXPR: codes.MISC,\n    codes.NO_ANY_EXPLICIT: codes.MISC,\n    codes.NO_SUBCLASS_ANY: codes.MISC,\n    codes.NO_ANY_DECORATED: codes.MISC,\n    codes.ANY_EXPR: codes.NO_ANY_EXPR,\n    codes.EXPLICIT_ANY: codes.NO_ANY_EXPLICIT,\n    codes.SUBCLASS_ANY: codes.SUBCLASS_ANY,\n    codes.DECORATED_ANY: codes.NO_ANY_DECORATED,\n}\n\n\nclass ErrorInfo:\n    \"\"\"Representation of a single error message.\"\"\"\n\n    def __repr__(self) -> str:\n        return f\"{self.line}:{self.column}: {self.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\n    # The path to source file that was the source of this error.\n    file = \"\"\n\n    # The fully-qualified id of the source module for this error.\n    module: str | None = None\n\n    # The name of the type in which this error is located at.\n    type: str | None = \"\"  # Unqualified, may be None\n\n    # The name of the function or member in which this error is located at.\n    function_or_member: str | None = \"\"  # Unqualified, may be None\n\n    # The line number related to this error within file.\n    line = 0  # -1 if unknown\n\n    # The column number related to this error with file.\n    column = 0  # -1 if unknown\n\n    # The end line number related to this error within file.\n    end_line = 0  # -1 if unknown\n\n    # The end column number related to this error with file.\n    end_column = 0  # -1 if unknown\n\n    # Either 'error' or 'note'\n    severity = \"\"\n\n    # The error message.\n    message = \"\"\n\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\n    # Only report this particular messages once per program.\n    only_once = False\n\n    # Do not remove duplicate copies of this message (ignored if only_once is True).\n    allow_dups = False\n\n    # Actual origin of the error message as tuple (path, line number, end line number)\n    # If end line number is unknown, use line number.\n    origin: tuple[str, Iterable[int]]\n\n    # Fine-grained incremental target where this was reported\n    target: str | None = None\n\n    # If True, don't show this message in output, but still record the error (needed\n    # by mypy daemon)\n    hidden = False\n\n    # Any note messages that are associated with this error\n    notes: list[ErrorInfo]\n\n    def __init__(\n        self,\n        import_ctx: list[tuple[str, int]],\n        *,\n        file: str,\n        module: str | None,\n        typ: str | None,\n        function_or_member: 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        allow_dups: bool,\n        origin: tuple[str, Iterable[int]] | None = None,\n        target: str | None = None,\n        priority: int = 0,\n    ) -> None:\n        self.import_ctx = import_ctx\n        self.file = file\n        self.module = module\n        self.type = typ\n        self.function_or_member = function_or_member\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.allow_dups = allow_dups\n        self.origin = origin or (file, [line])\n        self.target = target\n        self.notes = []\n        self.priority = priority\n\n\n# Type used internally to represent errors:\n#   (path, line, column, end_line, end_column, severity, message, allow_dups, code, target, src)\nErrorTuple: _TypeAlias = tuple[\n    Optional[str], int, int, int, int, str, str, bool, Optional[ErrorCode], Optional[str], str\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    def __init__(\n        self,\n        errors: Errors,\n        *,\n        filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,\n        save_filtered_errors: bool = False,\n    ) -> None:\n        self.errors = errors\n        self._has_new_errors = False\n        self._filter = filter_errors\n        self._filtered: list[ErrorInfo] | None = [] if save_filtered_errors else None\n\n    def __enter__(self) -> ErrorWatcher:\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            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 StoredBaselineError(TypedDict):\n    \"\"\"Structure of an error while stored in a baseline file\"\"\"\n\n    code: str | None\n    column: int\n    message: str\n    offset: int\n    target: str | None\n    src: str\n\n\nclass BaselineError(TypedDict):\n    code: str | None\n    column: int\n    line: int\n    message: str\n    target: str | None\n    src: str\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    # Set to True to show \"In function \"foo\":\" messages.\n    show_error_context: bool = False\n\n    # Set to True to show column numbers in error messages.\n    show_column_numbers: bool = False\n\n    # Set to True to show end line and end column in error messages.\n    # This implies `show_column_numbers`.\n    show_error_end: bool = False\n\n    # Set to True to show absolute file paths in error messages.\n    show_absolute_path: bool = False\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    _watchers: list[ErrorWatcher] = []\n\n    # Error baseline\n    original_baseline: dict[str, list[StoredBaselineError]]\n    baseline: dict[str, list[BaselineError]] = {}\n    filtered_baseline = False\n    \"\"\"False means 'we didn't find any errors' or 'We filtered errors and there were no errors', True means 'The build had errors'\"\"\"\n    # baseline metadata\n    baseline_targets: list[str]\n    # All detected errors before baseline filter\n    all_errors: dict[str, list[ErrorInfo] | Literal[\"fresh\"]]\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.all_errors = {}\n        self.original_baseline = {}\n        self.baseline_errors: list[ErrorTuple] = []\n        self.baseline_targets = []\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\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 common_path(self, file: str) -> str:\n        \"\"\"Convert path to a cross platform standard for use with baseline\"\"\"\n        file = os.path.normpath(file)\n        return remove_path_prefix(file, self.ignore_prefix).replace(\"\\\\\", \"/\")\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        file: str | None = None,\n        only_once: bool = False,\n        allow_dups: 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        notes: list[str] | None = None,\n    ) -> None:\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            file: if non-None, override current file as context\n            only_once: if True, only report this exact message once per build\n            allow_dups: if True, allow duplicate copies of this message (ignored if only_once)\n            origin_span: if non-None, override current context as origin\n                         (type: ignores have effect here)\n            end_line: if non-None, override current context as end\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        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\n        if file is None:\n            file = self.file\n        if offset:\n            message = \" \" * offset + message\n\n        if origin_span is None:\n            origin_span = [line]\n\n        if end_line is None:\n            end_line = line\n\n        code = code or (codes.MISC if not blocker else None)\n\n        info = ErrorInfo(\n            import_ctx=self.import_context(),\n            file=file,\n            module=self.current_module(),\n            typ=type,\n            function_or_member=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            allow_dups=allow_dups,\n            origin=(self.file, origin_span),\n            target=self.current_target(),\n        )\n        self.add_error_info(info)\n        for msg in notes or ():\n            note = ErrorInfo(\n                import_ctx=info.import_ctx,\n                file=info.file,\n                module=info.module,\n                typ=info.type,\n                function_or_member=info.function_or_member,\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=msg,\n                code=info.code,\n                blocker=info.blocker,\n                only_once=info.only_once,\n                allow_dups=info.allow_dups,\n                origin=info.origin,\n                target=info.target,\n            )\n            self.add_error_info(note)\n            info.notes.append(note)\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 _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        i = len(self._watchers)\n        while i > 0:\n            i -= 1\n            w = self._watchers[i]\n            if w.on_error(file, info):\n                return True\n        return False\n\n    def add_error_info(self, info: ErrorInfo) -> None:\n        file, lines = info.origin\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                        # Annotation requests us to ignore all errors on this line.\n                        self.used_ignored_lines[file][scope_line].append(\n                            (info.code or codes.MISC).code\n                        )\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(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 and info.code != REVEAL:\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            note = ErrorInfo(\n                import_ctx=info.import_ctx,\n                file=info.file,\n                module=info.module,\n                typ=info.type,\n                function_or_member=info.function_or_member,\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=msg,\n                code=None,\n                blocker=False,\n                only_once=False,\n                allow_dups=False,\n            )\n            info.notes.append(note)\n            self._add_error_info(file, note)\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 not self.options.ide and message in self.only_once_messages:\n                return\n            info_ = info\n            self.only_once_messages.add(message)\n            info = ErrorInfo(\n                import_ctx=info.import_ctx,\n                file=info.file,\n                module=info.module,\n                typ=info.type,\n                function_or_member=info.function_or_member,\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=info.code,\n                blocker=False,\n                only_once=True,\n                allow_dups=False,\n                priority=20,\n            )\n            info_.notes.append(info)\n            self._add_error_info(file, info)\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, 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        new_info = ErrorInfo(\n            import_ctx=info.import_ctx,\n            file=info.file,\n            module=info.module,\n            typ=None,\n            function_or_member=None,\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=None,\n            blocker=False,\n            only_once=True,\n            allow_dups=False,\n            origin=info.origin,\n            target=info.target,\n        )\n        self._add_error_info(info.origin[0], new_info)\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) -> None:\n        if (\n            is_typeshed_file(self.options.abs_custom_typeshed_dir if self.options else None, file)\n            or file in self.ignored_files\n        ):\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 = used_ignored_lines[line]\n            unused_ignored_codes = set(ignored_codes) - set(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(sorted(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\n            # Don't use report since add_error_info will ignore the error!\n            info = ErrorInfo(\n                import_ctx=self.import_context(),\n                file=file,\n                module=self.current_module(),\n                typ=None,\n                function_or_member=None,\n                line=line,\n                column=-1,\n                end_line=line,\n                end_column=-1,\n                severity=\"error\",\n                message=message,\n                code=codes.UNUSED_IGNORE,\n                blocker=False,\n                only_once=False,\n                allow_dups=False,\n            )\n            self._add_error_info(file, info)\n\n    def generate_ignore_without_code_errors(\n        self, file: str, is_warning_unused_ignores: bool\n    ) -> None:\n        if (\n            is_typeshed_file(self.options.abs_custom_typeshed_dir if self.options else None, file)\n            or file in self.ignored_files\n        ):\n            return\n\n        used_ignored_lines = self.used_ignored_lines[file]\n\n        # If the whole file is ignored, ignore it.\n        if used_ignored_lines:\n            _, used_codes = min(used_ignored_lines.items())\n            if codes.FILE.code in used_codes:\n                return\n\n        for line, ignored_codes in self.ignored_lines[file].items():\n            if ignored_codes:\n                continue\n\n            # If the ignore is itself unused and that would be warned about, let\n            # 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            info = ErrorInfo(\n                import_ctx=self.import_context(),\n                file=file,\n                module=self.current_module(),\n                typ=None,\n                function_or_member=None,\n                line=line,\n                column=-1,\n                end_line=line,\n                end_column=-1,\n                severity=\"error\",\n                message=message,\n                code=codes.IGNORE_WITHOUT_CODE,\n                blocker=False,\n                only_once=False,\n                allow_dups=False,\n            )\n            self._add_error_info(file, info)\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        for _watcher in self._watchers:\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(\n        self, error_tuples: list[ErrorTuple], source_lines: list[str] | None, path: str\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 (\n            file,\n            line,\n            column,\n            end_line,\n            end_column,\n            severity,\n            message,\n            allow_dups,\n            code,\n            _,\n            _,\n        ) 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.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 len(source_lines) >= line > 0:\n                    source_line = source_lines[line - 1]\n                    source_line_expanded = source_line.expandtabs()\n                    if column < 0:\n                        # Something went wrong, take first non-empty column.\n                        column = len(source_line) - len(source_line.lstrip())\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                    a.append(\" \" * (DEFAULT_SOURCE_OFFSET + column) + marker)\n        return a\n\n    def filter_baseline_pre(self, path: str):\n        \"\"\"remove baselined errors from `error_info_map` and put them into `all_errors`\"\"\"\n        if path not in self.error_info_map:\n            return\n        source_lines = self.read_source and self.read_source(path)\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.sort_messages(error_info)\n        filtered = self.filter_baseline(error_info, path, source_lines)\n        if filtered:\n            self.error_info_map[path] = filtered\n        else:\n            del self.error_info_map[path]\n\n    def file_messages(\n        self, path: str, formatter: ErrorFormatter | None = None, *, do_baseline=False\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\n        if do_baseline:\n            self.filter_baseline_pre(path)\n        if path not in self.error_info_map:\n            return []\n        source_lines = self.read_source and self.read_source(path)\n        error_info = self.error_info_map[path]\n        error_tuples = self.render_messages(error_info, source_lines, self.simplify_path(path))\n        error_tuples = self.remove_duplicates(error_tuples)\n        self.filtered_baseline = self.filtered_baseline or bool(error_tuples)\n\n        if formatter is not None:\n            errors = create_errors(error_tuples)\n            return [formatter.report_error(err) for err in errors]\n\n        self.flushed_files.add(path)\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(error_tuples, source_lines, path)\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.copy().keys():  # baseline filter will mutate it\n            if path not in self.flushed_files:\n                msgs.extend(self.file_messages(path, do_baseline=True))\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(\n        self,\n        errors: list[ErrorInfo],\n        source_lines: list[str] | None = None,\n        current_file: str | None = None,\n    ) -> list[ErrorTuple]:\n        \"\"\"Translate the messages into a sequence of tuples.\n\n        Each tuple is of form (path, line, col, severity, message, allow_dups, 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        result: list[ErrorTuple] = []\n        prev_import_context: list[tuple[str, int]] = []\n        prev_function_or_member: 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(\n                        (\n                            None,\n                            -1,\n                            -1,\n                            -1,\n                            -1,\n                            \"note\",\n                            fmt.format(path, line),\n                            e.allow_dups,\n                            None,\n                            None,\n                            \"\",\n                        )\n                    )\n                    i -= 1\n\n            file = self.simplify_path(e.file)\n\n            # Report context within a source file.\n            if not self.options.show_error_context:\n                pass\n            elif e.function_or_member != prev_function_or_member or e.type != prev_type:\n                if e.function_or_member is None:\n                    if e.type is None:\n                        result.append(\n                            (\n                                file,\n                                -1,\n                                -1,\n                                -1,\n                                -1,\n                                \"note\",\n                                \"At top level:\",\n                                e.allow_dups,\n                                None,\n                                None,\n                                \"\",\n                            )\n                        )\n                    else:\n                        result.append(\n                            (\n                                file,\n                                -1,\n                                -1,\n                                -1,\n                                -1,\n                                \"note\",\n                                f'In class \"{e.type}\":',\n                                e.allow_dups,\n                                None,\n                                None,\n                                \"\",\n                            )\n                        )\n                else:\n                    if e.type is None:\n                        result.append(\n                            (\n                                file,\n                                -1,\n                                -1,\n                                -1,\n                                -1,\n                                \"note\",\n                                f'In function \"{e.function_or_member}\":',\n                                e.allow_dups,\n                                None,\n                                None,\n                                \"\",\n                            )\n                        )\n                    else:\n                        result.append(\n                            (\n                                file,\n                                -1,\n                                -1,\n                                -1,\n                                -1,\n                                \"note\",\n                                'In member \"{}\" of class \"{}\":'.format(\n                                    e.function_or_member, e.type\n                                ),\n                                e.allow_dups,\n                                None,\n                                None,\n                                \"\",\n                            )\n                        )\n            elif e.type != prev_type:\n                if e.type is None:\n                    result.append(\n                        (\n                            file,\n                            -1,\n                            -1,\n                            -1,\n                            -1,\n                            \"note\",\n                            \"At top level:\",\n                            e.allow_dups,\n                            None,\n                            None,\n                            \"\",\n                        )\n                    )\n                else:\n                    result.append(\n                        (\n                            file,\n                            -1,\n                            -1,\n                            -1,\n                            -1,\n                            \"note\",\n                            f'In class \"{e.type}\":',\n                            e.allow_dups,\n                            None,\n                            None,\n                            \"\",\n                        )\n                    )\n            src = (\n                file == current_file\n                and source_lines\n                and len(source_lines) >= e.line > 0\n                and source_lines[e.line - 1]\n            ) or \"\"\n            # when there is no column, but we still want an ide to show an error\n            if e.column == -1 and self.options.show_error_end:\n                if src:\n                    e.column = src.find(src.strip())\n                    e.end_column = len(src)\n                else:\n                    e.column = 1\n            src = src.strip()\n            if isinstance(e.message, ErrorMessage):\n                result.append(\n                    (\n                        file,\n                        e.line,\n                        e.column,\n                        e.end_line,\n                        e.end_column,\n                        e.severity,\n                        e.message.value,\n                        e.allow_dups,\n                        e.code,\n                        e.target,\n                        src,\n                    )\n                )\n            else:\n                result.append(\n                    (\n                        file,\n                        e.line,\n                        e.column,\n                        e.end_line,\n                        e.end_column,\n                        e.severity,\n                        e.message,\n                        e.allow_dups,\n                        e.code,\n                        e.target,\n                        src,\n                    )\n                )\n\n            prev_import_context = e.import_ctx\n            prev_function_or_member = e.function_or_member\n            prev_type = e.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 (\n                i + 1 < len(errors)\n                and errors[i + 1].import_ctx == errors[i].import_ctx\n                and errors[i + 1].file == errors[i].file\n            ):\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[ErrorTuple]) -> list[ErrorTuple]:\n        \"\"\"Remove duplicates from a sorted error list.\"\"\"\n        res: list[ErrorTuple] = []\n        i = 0\n        while i < len(errors):\n            dup = False\n            # Use slightly special formatting for member conflicts reporting.\n            conflicts_notes = False\n            j = i - 1\n            # Find duplicates, unless duplicates are allowed.\n            if not errors[i][7]:\n                while j >= 0 and errors[j][0] == errors[i][0]:\n                    if errors[j][6].strip() == \"Got:\":\n                        conflicts_notes = True\n                    j -= 1\n                j = i - 1\n                while (\n                    j >= 0\n                    and errors[j][0] == errors[i][0]\n                    and errors[j][1] == errors[i][1]\n                    and errors[j][2] == errors[i][2]\n                ):\n                    if (\n                        errors[j][5] == errors[i][5]\n                        and\n                        # Allow duplicate notes in overload conflicts reporting.\n                        not (\n                            (errors[i][5] == \"note\" and errors[i][6].strip() in allowed_duplicates)\n                            or (errors[i][6].strip().startswith(\"def \") and conflicts_notes)\n                        )\n                        and errors[j][6] == errors[i][6]\n                    ):  # ignore column\n                        dup = True\n                        break\n                    j -= 1\n            if not dup:\n                res.append(errors[i])\n            i += 1\n        return res\n\n    def initialize_baseline(\n        self, errors: dict[str, list[StoredBaselineError]], targets: list[str]\n    ) -> None:\n        \"\"\"Initialize the baseline properties\"\"\"\n        self.original_baseline = deepcopy(errors)\n        for file in errors.values():\n            previous = 0\n            for error in file:\n                try:\n                    previous = error[\"line\"] = error[\"offset\"] + previous  # type: ignore[typeddict-unknown-key]\n                except KeyError as err:\n                    raise TypeError(\"baseline\") from err\n        baseline_errors = cast(dict[str, list[BaselineError]], errors)  # type: ignore[bad-cast]\n        self.baseline = baseline_errors\n        self.baseline_targets = targets\n\n    def prepare_baseline_errors(self) -> dict[str, list[StoredBaselineError]]:\n        \"\"\"Create a dict representing the error portion of an error baseline file\"\"\"\n\n        def remove_duplicates(errors: list[ErrorInfo]) -> list[ErrorInfo]:\n            unduplicated_result = []\n            i = 0\n            while i < len(errors):\n                dup = False\n                j = i - 1\n                if not errors[i].allow_dups:\n                    while j >= 0:\n                        if (\n                            errors[i].line == errors[j].line\n                            and errors[i].column == errors[j].column\n                            and errors[i].message == errors[j].message\n                        ):\n                            dup = True\n                            break\n                        j -= 1\n                if not dup:\n                    unduplicated_result.append(errors[i])\n                i += 1\n            return unduplicated_result\n\n        result = {\n            self.common_path(file): (\n                [\n                    {\n                        \"code\": error.code.code if error.code else None,\n                        \"column\": error.column,\n                        \"line\": error.line,\n                        \"message\": error.message,\n                        \"target\": error.target,\n                        \"src\": self.read_source\n                        and error.file == file\n                        and cast(list[str], self.read_source(file))[error.line - 1].strip(),\n                    }\n                    for error in remove_duplicates(errors)\n                    # don't store reveal errors\n                    if error.code != codes.REVEAL\n                ]\n            )\n            for file, errors in self.all_errors.items()\n            if errors != \"fresh\"\n        }\n        for file in result.values():\n            previous = 0\n            for error in file:\n                error[\"offset\"] = cast(int, error[\"line\"]) - previous\n                previous = cast(int, error[\"line\"])\n                del error[\"line\"]\n        final_result: dict[str, list[StoredBaselineError]] = cast(\n            dict[str, list[StoredBaselineError]], result\n        )\n        for file_name, errors in self.all_errors.items():\n            if errors == \"fresh\":\n                key = self.common_path(file_name)\n                final_result[key] = self.original_baseline[key]\n        return final_result\n\n    def filter_baseline(\n        self, errors: list[ErrorInfo], path: str, source_lines: list[str] | None\n    ) -> list[ErrorInfo]:\n        \"\"\"Remove baseline errors and store the unmatched errors in all_errors\"\"\"\n        baseline_errors = self.baseline.get(self.common_path(path))\n        self.all_errors[path] = errors\n        if not baseline_errors:\n            return errors\n        baseline_errors = list(baseline_errors)\n        new_errors = []\n        previous_matches: list[ErrorInfo] = []\n        ignored_notes = []\n        # first pass for exact matches (line, message, src)\n        for error in errors:\n            if previous_matches:\n                if (\n                    error.line != previous_matches[0].line\n                    or error.column != previous_matches[0].column\n                ):\n                    previous_matches = []\n                else:\n                    cont = False\n                    for previous_match in previous_matches:\n                        if previous_match.message == error.message:\n                            cont = True\n                            break\n                    if cont:\n                        continue\n\n            if error.code == codes.REVEAL:\n                new_errors.append(error)\n                continue\n            if error in ignored_notes:\n                continue\n            source = error.file == path and source_lines and source_lines[error.line - 1].strip()\n            message = clean_baseline_message(error.message)\n            for i, baseline_error in enumerate(baseline_errors):\n                if (\n                    error.line == baseline_error[\"line\"]\n                    and message == clean_baseline_message(baseline_error[\"message\"])\n                    and source == baseline_error[\"src\"]\n                ):\n                    ignored_notes = error.notes\n                    del baseline_errors[i]\n                    previous_matches.append(error)\n                    break\n            else:\n                new_errors.append(error)\n        # second pass for rough matches (line, code) or (line < 100, message, src)\n        new_errors, temp = [], new_errors\n        for error in temp:\n            if previous_matches:\n                if (\n                    error.line != previous_matches[0].line\n                    or error.column != previous_matches[0].column\n                ):\n                    previous_matches = []\n                else:\n                    cont = False\n                    for previous_match in previous_matches:\n                        if previous_match.message == error.message:\n                            cont = True\n                            break\n                    if cont:\n                        continue\n            if error.code == codes.REVEAL:\n                new_errors.append(error)\n                continue\n            if error in ignored_notes:\n                continue\n            source = error.file == path and source_lines and source_lines[error.line - 1].strip()\n            message = clean_baseline_message(error.message)\n            for i, baseline_error in enumerate(baseline_errors):\n                if (\n                    error.line == baseline_error[\"line\"]\n                    and (error.code and error.code.code) == baseline_error[\"code\"]\n                    or message == clean_baseline_message(baseline_error[\"message\"])\n                    and abs(error.line - baseline_error[\"line\"]) < 100\n                    and source == baseline_error[\"src\"]\n                ):\n                    ignored_notes = error.notes\n                    del baseline_errors[i]\n                    previous_matches.append(error)\n                    break\n            else:\n                new_errors.append(error)\n        return new_errors\n\n\ndef clean_baseline_message(message: str) -> str:\n    return re.sub(r\"line \\d+\", \"\", message)\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,\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    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 basedmypy master on GitHub:\\n\"\n        \"https://kotlinisland.github.io/basedmypy/common_issues.html\"\n        \"#using-a-development-mypy-build\",\n        file=stderr,\n    )\n    if options.show_traceback:\n        print(\n            \"Please report a bug at https://github.com/KotlinIsland/basedmypy/issues\", file=stderr\n        )\n    else:\n        print(\n            \"If this issue continues with basedmypy master, \"\n            \"please report a bug at https://github.com/KotlinIsland/basedmypy/issues\",\n            file=stderr,\n        )\n    print(f\"version: {basedmypy_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        message: str,\n        errorcode: ErrorCode | None,\n        severity: Literal[\"error\", \"note\"],\n    ) -> None:\n        self.file_path = file_path\n        self.line = line\n        self.column = 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, _, _, 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(file_path, line, column, message, errorcode, severity=\"note\")\n                errors.append(error)\n                continue\n\n            error.hints.append(message)\n\n        else:\n            error = MypyError(file_path, line, column, message, errorcode, severity=\"error\")\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_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_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, Sequence\nfrom typing import Final, TypeVar, cast, overload\n\nfrom mypy.nodes import ARG_STAR, 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    IntersectionType,\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    TypeGuardType,\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 cast(F, callee)\n        tvs = []\n        tvmap: dict[TypeVarId, Type] = {}\n        for v in callee.variables:\n            tv = v.new_unification_variable(v)\n            tv.upper_bound = expand_type(tv.upper_bound, tvmap)\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] = {}\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        args = self.expand_types_with_unpack(list(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                    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 (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 = repl.accept(self)\n            if isinstance(repl, TypeVarType):\n                repl.default = repl.default.accept(self)\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 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        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    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 isinstance(repl, UnionType) and all(\n            isinstance(get_proper_type(item), TupleType) for item in repl.items\n        ):\n            # TODO: this is incomplete\n            return [UnpackType(typ=t.type.tuple_fallback)]\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, Instance):\n            # we have something like Unpack[Tuple[Any, ...]]\n            new_unpack = UnpackType(var_arg.type.accept(self))\n        elif 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        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 and cast(TypeGuardType, t.type_guard.accept(self)),\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 and cast(TypeGuardType, t.type_guard.accept(self)),\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_types_with_unpack(self, typs: Sequence[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 visit_tuple_type(self, t: TupleType) -> Type:\n        items = self.expand_types_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                    assert unpacked.type.fullname == \"builtins.tuple\"\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_intersection_type(self, t: IntersectionType) -> Type:\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_intersection()\n        # can cause recursion, so we just remove strict duplicates.\n        simplified = IntersectionType.make_intersection(\n            flatten_nested_unions(expanded, type_type=IntersectionType), 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        return get_proper_type(simplified)\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)\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        args = self.expand_types_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 visit_typeguard_type(self, t: TypeGuardType) -> Type:\n        return TypeGuardType(t.target, t.type_guard.accept(self))\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/exprtotype.py",
    "content": "\"\"\"Translate an Expression to a Type value.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing 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    CallableArgument,\n    EllipsisType,\n    Instance,\n    IntersectionType,\n    ProperType,\n    RawExpressionType,\n    Type,\n    TypedDictType,\n    TypeList,\n    UnboundType,\n    UnionType,\n    UnpackType,\n    UntypedType,\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(\n                True,\n                \"builtins.bool\",\n                line=expr.line,\n                column=expr.column,\n                expression=not allow_new_syntax,\n            )\n        elif name == \"False\":\n            return RawExpressionType(\n                False,\n                \"builtins.bool\",\n                line=expr.line,\n                column=expr.column,\n                expression=not allow_new_syntax,\n            )\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, expression=True)\n        else:\n            raise TypeTranslationError()\n    elif isinstance(expr, IndexExpr):\n        base = expr_to_unanalyzed_type(expr.base, options, allow_new_syntax, expr)\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(args[0], options, allow_new_syntax, expr)\n            base.args = tuple(\n                expr_to_unanalyzed_type(arg, options, allow_new_syntax, expr, allow_unpack=True)\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 isinstance(expr, OpExpr) and expr.op == \"|\":\n        return UnionType(\n            [\n                expr_to_unanalyzed_type(expr.left, options, allow_new_syntax),\n                expr_to_unanalyzed_type(expr.right, options, allow_new_syntax),\n            ],\n            is_evaluated=not allow_new_syntax,\n            uses_pep604_syntax=True,\n            line=expr.line,\n            column=expr.column,\n        )\n    elif isinstance(expr, OpExpr) and expr.op == \"&\":\n        return IntersectionType(\n            [\n                expr_to_unanalyzed_type(expr.left, options, allow_new_syntax),\n                expr_to_unanalyzed_type(expr.right, options, allow_new_syntax),\n            ],\n            is_evaluated=not allow_new_syntax,\n            uses_based_syntax=True,\n            line=expr.line,\n            column=expr.column,\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 = UntypedType()\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(arg, options, allow_new_syntax, expr)\n                    continue\n                else:\n                    raise TypeTranslationError()\n            elif i == 0:\n                typ = expr_to_unanalyzed_type(arg, options, allow_new_syntax, expr)\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(t, options, allow_new_syntax, expr, allow_unpack=True)\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(expr.expr, options, allow_new_syntax)\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(\n            expr.value,\n            \"builtins.int\",\n            line=expr.line,\n            column=expr.column,\n            expression=not allow_new_syntax,\n        )\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(expr.expr, options, allow_new_syntax), 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(value, options, allow_new_syntax, expr)\n                    )\n                    continue\n                raise TypeTranslationError()\n            items[item_name.value] = expr_to_unanalyzed_type(\n                value, options, allow_new_syntax, expr\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 Sequence\nfrom typing import Any, Callable, Final, Literal, Optional, TypeVar, Union, 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    FakeInfo,\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    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasStmt,\n    TypeParam,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n    check_arg_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    IntersectionType,\n    ProperType,\n    RawExpressionType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeGuardType,\n    TypeList,\n    TypeOfAny,\n    UnboundType,\n    UnionType,\n    UnpackType,\n    UntypedType,\n)\nfrom mypy.util import bytes_to_human_readable_repr, getattr, 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\n\n# TODO: Index, ExtSlice are deprecated in 3.9.\nfrom ast import AST, Attribute, Call, FunctionType, Index, 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    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\nNamedExpr = ast3.NamedExpr\nConstant = ast3.Constant\nCompare = ast3.Compare\n\nif sys.version_info >= (3, 10):\n    Match = ast3.Match\n    MatchValue = ast3.MatchValue\n    MatchSingleton = ast3.MatchSingleton\n    MatchSequence = ast3.MatchSequence\n    MatchStar = ast3.MatchStar\n    MatchMapping = ast3.MatchMapping\n    MatchClass = ast3.MatchClass\n    MatchAs = ast3.MatchAs\n    MatchOr = ast3.MatchOr\n    AstNode = Union[ast3.expr, ast3.stmt, ast3.pattern, ast3.ExceptHandler]\nelse:\n    Match = Any\n    MatchValue = Any\n    MatchSingleton = Any\n    MatchSequence = Any\n    MatchStar = Any\n    MatchMapping = Any\n    MatchClass = Any\n    MatchAs = Any\n    MatchOr = Any\n    AstNode = Union[ast3.expr, ast3.stmt, 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\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 deprecation warnings about \\u\n        with warnings.catch_warnings():\n            warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\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    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            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 [code.strip() for code in m.group(1).split(\",\")]\n\n\ndef parse_type_comment(\n    type_comment: str, line: int, column: int, errors: Errors | None, *, _mode=\"\"\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    function = False\n    if type_comment.startswith(\"def \"):\n        function = True\n        type_comment = type_comment[4:]\n    mode = (\n        \"func_type\" if type_comment and type_comment[0] == \"(\" and \"->\" in type_comment else \"eval\"\n    )\n    try:\n        typ = ast3_parse(type_comment, \"<type_comment>\", _mode or mode)\n    except SyntaxError:\n        if not _mode and mode == \"func_type\":\n            # See testCallableSyntaxBreak\n            return parse_type_comment(type_comment, line, column, errors, _mode=\"eval\")\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        if isinstance(typ, ast3.FunctionType):\n            converter = TypeConverter(\n                errors, line=line, override_column=column, is_evaluated=False\n            )\n            from mypy.typeanal import CALLABLE_NAME\n\n            return ignored, CallableType(\n                converter.translate_expr_list(typ.argtypes),\n                [ArgKind.ARG_POS for arg in typ.argtypes],\n                [None for arg in typ.argtypes],\n                converter.visit(typ.returns),\n                Instance(FakeInfo(\"builtins.function\" if function else CALLABLE_NAME), [], -1),\n            )\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(\n            expr_string.strip().replace(\"\\n\", \" \"), line=line, column=column, errors=None\n        )\n        if (\n            isinstance(node, (UnboundType, UnionType, IntersectionType, TypeGuardType))\n            and node.original_str_expr is None\n        ):\n            node.original_str_expr = expr_string\n            node.original_str_fallback = expr_fallback_name\n            return node\n        if isinstance(node, CallableType):\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\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 = True) -> 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        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 = getattr(n, \"end_lineno\", None)\n        node.end_column = getattr(n, \"end_col_offset\", None)\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 min(self.type_ignores) < self.get_lineno(stmts[0])\n        ):\n            ignores = self.type_ignores[min(self.type_ignores)]\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=min(self.type_ignores),\n                    column=0,\n                    blocker=False,\n                )\n            self.errors.used_ignored_lines[self.errors.file][min(self.type_ignores)].append(\n                codes.FILE.code\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\",\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 = getattr(last, \"end_lineno\", None)\n        b.end_column = getattr(last, \"end_col_offset\", None)\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        seen_unconditional_func_def = False\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) and seen_unconditional_func_def is False:\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                    seen_unconditional_func_def = True\n            elif (\n                current_overload_name is not None\n                and isinstance(stmt, IfStmt)\n                and if_overload_name == 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(Union[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                seen_unconditional_func_def = False\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                            Union[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(\n            Union[Decorator, FuncDef, OverloadedFuncDef], stmt.body[0].body[-1]\n        ).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        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        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 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], 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(message_registry.DUPLICATE_TYPE_SIGNATURES, lineno, n.col_offset)\n                    arg_types = [\n                        a.type_annotation if a.type_annotation is not None else UntypedType()\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(message_registry.DUPLICATE_TYPE_SIGNATURES, lineno, n.col_offset)\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[Optional[Type]], 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)\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(message_registry.ELLIPSIS_WITH_OTHER_TYPEARGS, lineno, n.col_offset)\n            elif len(arg_types) > len(arg_kinds):\n                self.fail(\n                    message_registry.TYPE_SIGNATURE_TOO_MANY_ARGS,\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_ARGS,\n                    lineno,\n                    n.col_offset,\n                    blocker=False,\n                )\n            else:\n                func_type = CallableType(\n                    [a if a is not None else UntypedType() for a in arg_types],\n                    arg_kinds,\n                    arg_names,\n                    return_type if return_type is not None else UntypedType(),\n                    Instance(FakeInfo(\"builtins.function\"), [], -1),\n                )\n\n        # End position is always the same.\n        end_line = getattr(n, \"end_lineno\", None)\n        end_column = getattr(n, \"end_col_offset\", None)\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 = getattr(args, \"posonlyargs\", cast(list[ast3.arg], []))\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_arg_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(message_registry.DUPLICATE_TYPE_SIGNATURES, arg.lineno, arg.col_offset)\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        argument = Argument(Var(arg.arg, arg_type), arg_type, self.visit(default), kind, pos_only)\n        argument.set_line(\n            arg.lineno,\n            arg.col_offset,\n            getattr(arg, \"end_lineno\", None),\n            getattr(arg, \"end_col_offset\", None),\n        )\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)\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 = getattr(n, \"end_lineno\", None)\n        cdef.end_column = getattr(n, \"end_col_offset\", None)\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            )\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            )\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            )\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: 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)))  # type: ignore[bad-cast]\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)))  # type: ignore[bad-cast]\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[Optional[str]]\", [None] * len(args)) + keyword_names,\n        )\n        return self.set_line(e, n)\n\n    # Constant(object value) -- a constant, in Python 3.8.\n    def visit_Constant(self, n: 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        if not strs_to_join.items:\n            return self.set_line(StrExpr(\"\"), n)\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    # 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 ---\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    # ExtSlice(slice* dims)\n    def visit_ExtSlice(self, n: ast3.ExtSlice) -> TupleExpr:\n        # cast for mypyc's benefit on Python 3.9\n        return TupleExpr(self.translate_expr_list(cast(Any, n).dims))\n\n    # Index(expr value)\n    def visit_Index(self, n: Index) -> Node:\n        # cast for mypyc's benefit on Python 3.9\n        value = self.visit(cast(Any, n).value)\n        assert isinstance(value, Node)\n        return value\n\n    # Match(expr subject, match_case* cases) # python 3.10 and later\n    def visit_Match(self, n: 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: MatchValue) -> ValuePattern:\n        node = ValuePattern(self.visit(n.value))\n        return self.set_line(node, n)\n\n    def visit_MatchSingleton(self, n: MatchSingleton) -> SingletonPattern:\n        node = SingletonPattern(n.value)\n        return self.set_line(node, n)\n\n    def visit_MatchSequence(self, n: 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: 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: 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 = NameExpr(n.rest)\n\n        node = MappingPattern(keys, values, rest)\n        return self.set_line(node, n)\n\n    def visit_MatchClass(self, n: 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: 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: 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(message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION, n.lineno, n.col_offset)\n        if isinstance(incorrect_expr, ast3.NamedExpr):\n            self.fail(message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION, n.lineno, n.col_offset)\n        if isinstance(incorrect_expr, ast3.Await):\n            self.fail(message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION, n.lineno, n.col_offset)\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, Constant) and isinstance(n.value, str):\n            return n.value.strip()\n        elif isinstance(n, 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, ast3.BitAnd)):\n            return self.invalid_type(n)\n        left = self.visit(n.left)\n        right = self.visit(n.right)\n        if isinstance(n.op, ast3.BitAnd):\n            return IntersectionType(\n                [left, right],\n                line=self.line,\n                column=self.convert_column(n.col_offset),\n                is_evaluated=self.is_evaluated,\n                uses_based_syntax=True,\n            )\n\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_Compare(self, n: Compare) -> Type:\n        if len(n.ops) != 1 or not isinstance(n.ops[0], ast3.Is):\n            return self.invalid_type(n)\n        if isinstance(n.left, ast3.Name):\n            target = n.left.id\n        else:\n            return self.invalid_type(n)\n        return TypeGuardType(target, self.visit(n.comparators[0]), is_evaluated=self.is_evaluated)\n\n    def visit_IfExp(self, n: ast3.IfExp) -> Type:\n        condition = self.visit(n.test)\n        true: Type | None = self.visit(n.body)\n        if isinstance(true, RawExpressionType) and isinstance(true.literal_value, str):\n            # if just the true branch part is quoted\n            _, true = parse_type_comment(\n                true.literal_value, line=true.line, column=true.column, errors=None\n            )\n        assert isinstance(true, ProperType)\n        false: Type = self.visit(n.orelse)\n        assert isinstance(false, ProperType)\n        result = None\n        if not (isinstance(condition, RawExpressionType) and condition.literal_value is True):\n            result = self.invalid_type(n.test, note='The condition can only be \"True\"')\n        if not isinstance(true, TypeGuardType):\n            result = self.invalid_type(n.body, note=\"The true branch can only be a type-guard\")\n        if not (isinstance(false, RawExpressionType) and false.literal_value in {False, \"False\"}):\n            result = self.invalid_type(n.orelse, note='The false branch can only be \"False\"')\n        if result:\n            return result\n        assert isinstance(true, TypeGuardType)\n        true.only_true = True\n        true.is_evaluated = self.is_evaluated\n        return true\n\n    def visit_Constant(self, n: 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        return self.invalid_type(n)\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_Index(self, n: ast3.Index) -> Type:\n        # cast for mypyc's benefit on Python 3.9\n        value = self.visit(cast(Any, n).value)\n        assert isinstance(value, Type)\n        return value\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)  # Python 3.9 and later\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            return UnboundType(\n                value.name,\n                params,\n                line=self.line,\n                column=value.column,\n                empty_tuple_index=empty_tuple_index,\n            )\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)\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:\n            self.found = True\n\n\nclass FindYield(TraverserVisitor):\n    \"\"\"Check if an AST contains yields or yield 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/fastparse2.py",
    "content": ""
  },
  {
    "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 PYTHON_EXTENSIONS, BuildSource, matches_exclude, mypy_path\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.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\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        if name.endswith(\"-stubs\"):\n            name = name[:-6]  # 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(f\"{name} is not a valid Python package name\")\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    IntersectionType,\n    LiteralType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\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.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\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\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\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\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        for arg in ct.bound_args:\n            if arg:\n                arg.accept(self)\n        if ct.type_guard is not None:\n            ct.type_guard.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\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_intersection_type(self, it: IntersectionType):\n        for item in it.items:\n            item.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, 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        drive, path = os.path.splitdrive(path)  # Ignore Windows drive name\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 Iterable, 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\ndef topsort(data: dict[T, set[T]]) -> Iterable[set[T]]:\n    \"\"\"Topological sort.\n\n    Args:\n      data: A map from vertices to all vertices that it has an edge\n            connecting it to.  NOTE: This data structure\n            is modified in place -- for normalization purposes,\n            self-dependencies are removed and entries representing\n            orphans are added.\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      This is normalized to:\n\n        {A: {B, C}, B: {D}, C: {D}, D: {}}\n\n      The algorithm will yield the following values:\n\n        {D}\n        {B, C}\n        {A}\n\n    From https://code.activestate.com/recipes/577413/.\n    \"\"\"\n    # TODO: Use a faster algorithm?\n    for k, v in data.items():\n        v.discard(k)  # Ignore self dependencies.\n    for item in set.union(*data.values()) - set(data.keys()):\n        data[item] = set()\n    while True:\n        ready = {item for item, dep in data.items() if not dep}\n        if not ready:\n            break\n        yield ready\n        data = {item: (dep - ready) for item, dep in data.items() if item not in ready}\n    assert not data, f\"A cyclic dependency exists amongst {data!r}\"\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\nfrom mypy.util import split_module_names\n\n\ndef extract_module_names(type_name: str | None) -> list[str]:\n    \"\"\"Returns the module names of a fully qualified type name.\"\"\"\n    if type_name is not None:\n        # Discard the first one, which is just the qualified name of the type\n        possible_module_names = split_module_names(type_name)\n        return possible_module_names[1:]\n    else:\n        return []\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 type aliases\n        self.seen_aliases: set[types.TypeAliasType] = set()\n        # Used to avoid redundant work\n        self.seen_fullnames: set[str] = set()\n\n    def find_modules(self, typs: Iterable[types.Type]) -> set[str]:\n        self.modules = set()\n        self.seen_fullnames = set()\n        self.seen_aliases = set()\n        self._visit(typs)\n        return self.modules\n\n    def _visit(self, typ_or_typs: types.Type | Iterable[types.Type]) -> None:\n        typs = [typ_or_typs] if isinstance(typ_or_typs, types.Type) else typ_or_typs\n        for typ in typs:\n            if isinstance(typ, types.TypeAliasType):\n                # Avoid infinite recursion for recursive type aliases.\n                if typ in self.seen_aliases:\n                    continue\n                self.seen_aliases.add(typ)\n            typ.accept(self)\n\n    def _visit_module_name(self, module_name: str) -> None:\n        if module_name not in self.modules:\n            self.modules.update(split_module_names(module_name))\n\n    def visit_unbound_type(self, t: types.UnboundType) -> None:\n        self._visit(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(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\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(t.arg_types)\n\n    def visit_instance(self, t: types.Instance) -> None:\n        self._visit(t.args)\n        if t.type:\n            # Uses of a class depend on everything in the MRO,\n            # as changes to classes in the MRO can add types to methods,\n            # change property types, change the MRO itself, etc.\n            for s in t.type.mro:\n                self._visit_module_name(s.module_name)\n            if t.type.metaclass_type is not None:\n                self._visit_module_name(t.type.metaclass_type.type.module_name)\n\n    def visit_callable_type(self, t: types.CallableType) -> None:\n        self._visit(t.arg_types)\n        self._visit(t.ret_type)\n        if t.definition is not None:\n            fullname = t.definition.fullname\n            if fullname not in self.seen_fullnames:\n                self.modules.update(extract_module_names(t.definition.fullname))\n                self.seen_fullnames.add(fullname)\n\n    def visit_overloaded(self, t: types.Overloaded) -> None:\n        self._visit(t.items)\n        self._visit(t.fallback)\n\n    def visit_tuple_type(self, t: types.TupleType) -> None:\n        self._visit(t.items)\n        self._visit(t.partial_fallback)\n\n    def visit_typeddict_type(self, t: types.TypedDictType) -> None:\n        self._visit(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(t.items)\n\n    def visit_intersection_type(self, t: types.IntersectionType):\n        self._visit(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        self._visit(types.get_proper_type(t))\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 functools import cmp_to_key\nfrom typing import Callable\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 re-used 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 base64\nimport codecs\nimport os\nimport shutil\nimport sys\nimport tempfile\nfrom types import TracebackType\nfrom typing import Callable, Final\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\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 encoding the messages\n    in an alphabet that does not contain spaces, then adding a space for\n    separation. The last framed message is also followed by a space.\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.buffer = bytearray()\n\n    def frame_from_buffer(self) -> bytearray | None:\n        \"\"\"Return a full frame from the bytes we have in the buffer.\"\"\"\n        space_pos = self.buffer.find(b\" \")\n        if space_pos == -1:\n            return None\n        # We have a full frame\n        bdata = self.buffer[:space_pos]\n        self.buffer = self.buffer[space_pos + 1 :]\n        return bdata\n\n    def read(self, size: int = 100000) -> str:\n        \"\"\"Read bytes from an IPC connection until we have a full frame.\"\"\"\n        bdata: bytearray | None = bytearray()\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 \"\"\n        return codecs.decode(bdata, \"base64\").decode(\"utf8\")\n\n    def write(self, data: str) -> None:\n        \"\"\"Write to an IPC connection.\"\"\"\n\n        # Frame the data by urlencoding it and separating by space.\n        encoded_data = codecs.encode(data.encode(\"utf8\"), \"base64\") + b\" \"\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(\n                name, base64.urlsafe_b64encode(os.urandom(6)).decode()\n            )\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 socket.timeout 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        else:\n            name = self.sock.getsockname()\n            assert isinstance(name, str)\n            return name\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.options\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\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    IntersectionType,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    PlaceholderType,\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        best: ProperType | None = None\n        for base in t.type.bases:\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 join_simple(declaration: Type | None, s: Type, t: Type) -> ProperType:\n    \"\"\"Return a simple least upper bound given the declared type.\n\n    This function should be only used by binder, and should not recurse.\n    For all other uses, use `join_types()`.\n    \"\"\"\n    declaration = get_proper_type(declaration)\n    s = get_proper_type(s)\n    t = get_proper_type(t)\n    value = _union_join(s, t)\n    if not value:\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, AnyType):\n            return s\n\n        if isinstance(s, ErasedType):\n            return t\n\n        if is_proper_subtype(s, t, ignore_promotions=True):\n            return t\n\n        if is_proper_subtype(t, s, ignore_promotions=True):\n            return s\n\n        if isinstance(declaration, UnionType):\n            return mypy.typeops.make_simplified_union([s, 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        if isinstance(s, UnionType) and not isinstance(t, UnionType):\n            s, t = t, s\n\n        value = t.accept(TypeJoinVisitor(s))\n    if declaration is None or is_subtype(value, declaration):\n        return value\n\n    return declaration\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\ndef _union_join(l: ProperType, r: ProperType) -> ProperType | None:\n    if isinstance(l, PlaceholderType) or isinstance(r, PlaceholderType) or not mypy.options._based:\n        return None\n    # for performance reasons we can't always do a union\n    if isinstance(l, Instance):\n        if l == r:\n            # if it's the same, then no need to union\n            return l\n        # it always needs to be a union\n        return mypy.typeops.make_simplified_union([l, r])\n    if is_proper_subtype(l, r):\n        return r\n    elif is_proper_subtype(r, l):\n        return l\n    else:\n        return mypy.typeops.make_simplified_union([l, r])\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\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    r = _union_join(s, t)\n    if r:\n        return r\n    del r\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_intersection_type(self, t: IntersectionType) -> ProperType:\n        if is_proper_subtype(self.s, t):\n            return t\n        else:\n            return mypy.typeops.make_simplified_intersection([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) and self.s.id == t.id:\n            return self.s\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        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 len(t.arg_types) != len(self.s.arg_types):\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        else:\n            return self.default(self.s)\n\n    def visit_callable_type(self, t: CallableType) -> ProperType:\n        if isinstance(self.s, CallableType) and 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            # 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 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            return result\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 upack 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                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        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(join_types(t.item, self.s.item), line=t.line)\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, 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        # 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 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    #  Based: typing.Callable is the fallback for Callable, but there is also types.FunctionType\n    # There is an issue where `function` doesn't extend typing.Callable\n    #  Additionally, this only happens when union joins are disabled (unbased mode)\n    if t.fallback_name == s.fallback_name:\n        fallback = t.fallback\n    elif t.fallback_name == \"typing.Callable\":\n        fallback = t.fallback\n    elif s.fallback_name == \"typing.Callable\":\n        fallback = s.fallback\n    else:\n        joined = join_types(t.fallback, s.fallback)\n        assert isinstance(joined, Instance)\n        fallback = joined\n        if fallback.type.fullname == \"builtins.object\":\n            from mypy.typeanal import CALLABLE_TYPE\n\n            assert CALLABLE_TYPE\n            fallback = CALLABLE_TYPE\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_name in {\"builtins.function\", \"typing.Callable\"}:\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, Optional\nfrom typing_extensions import 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    TempNode,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\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\ndef literal(e: Expression) -> int:\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\nKey: _TypeAlias = tuple[Any, ...]\n\n\ndef subkeys(key: Key) -> Iterable[Key]:\n    return [elt for elt in key if isinstance(elt, tuple)]\n\n\ndef literal_hash(e: Expression) -> Key | None:\n    return e.accept(_hasher)\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[Optional[Key]]):\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_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_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    head = name\n    rest = []\n    # 1. 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        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    # 2. 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    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 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, cast\n\nimport mypy.options\nfrom mypy import build, defaults, state, util\nfrom mypy.config_parser import (\n    get_config_module_names,\n    parse_config_file,\n    parse_version,\n    validate_package_allow_list,\n)\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 __based_version__, __version__\n\nif TYPE_CHECKING:\n    from _typeshed import SupportsWrite\n\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(2600 if sys.platform == \"win32\" else 2**14)\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,\n        stderr,\n        options.hide_error_codes,\n        color=options.color_output,\n        hide_success=bool(options.output),\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 options.write_baseline and res:\n            new_errors = n_errors\n            n_files = len(res.manager.errors.all_errors)\n            total = []\n            n_errors = 0\n            # This is stupid, but it's just to remove the dupes from the unfiltered errors\n            for file, errors in res.manager.errors.all_errors.items():\n                if errors != \"fresh\":\n                    temp = res.manager.errors.render_messages(errors)\n                    total.extend(res.manager.errors.remove_duplicates(temp))\n                else:\n                    n_errors += len(res.manager.errors.original_baseline[file])\n            n_errors = len([error for error in total if error[5] == \"error\"])\n        else:\n            new_errors = -1\n        if n_errors:\n            summary = formatter.format_error(\n                n_errors,\n                n_files,\n                len(sources),\n                new_errors=new_errors,\n                blockers=blockers,\n                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.write_baseline:\n        stdout.write(\n            formatter.style(\n                f\"Baseline successfully written to {options.baseline_file}\\n\", \"green\", bold=True\n            )\n        )\n        stdout.flush()\n        code = 0\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 or (options.write_baseline and serious):\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    if (\n        options.warn_unused_configs\n        and options.unused_configs\n        and not options.incremental\n        and not options.non_interactive\n    ):\n        print(\n            \"Warning: unused section(s) in {}: {}\".format(\n                options.config_file,\n                get_config_module_names(\n                    options.config_file,\n                    [\n                        glob\n                        for glob in options.per_module_options.keys()\n                        if glob in options.unused_configs\n                    ],\n                ),\n            ),\n            file=stderr,\n        )\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) -> None:\n        super().__init__(prog=prog, max_help_position=28)\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        else:\n            # Assume we want argparse to manage wrapping, indenting, and\n            # formatting the text for us.\n            return argparse.HelpFormatter._fill_text(self, text, width, indent)\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 = \"\"\"\nBasedmypy is a program that will type check your Python code.\n\nBased? Based on what?\n\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://kotlinisland.github.io/basedmypy/getting_started.html\n\nFor more details on both running mypy and using the flags below, see:\n\n- https://kotlinisland.github.io/basedmypy/running_mypy.html\n- https://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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 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) -> 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    stdout = stdout or sys.stdout\n    stderr = stderr or sys.stderr\n\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    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\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    # Note: we have a style guide for formatting the mypy --help text. See\n    # https://github.com/python/mypy/wiki/Documentation-Conventions\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=(\n            f\"basedmypy {__based_version__} (compiled: {compilation_status})\\n\"\n            f\"Based on %(prog)s {__version__}\"\n        ),\n        help=\"Show program's version number and exit\",\n        stdout=stdout,\n    )\n\n    based_group = parser.add_argument_group(title=\"Based functionality arguments\")\n    based_group.add_argument(\n        \"--write-baseline\",\n        action=\"store_true\",\n        help=\"Create an error baseline from the result of this execution\",\n    )\n    based_group.add_argument(\n        \"--baseline-file\",\n        action=\"store\",\n        help=f\"Use baseline info in the given file (defaults to '{defaults.BASELINE_FILE}')\",\n    )\n    add_invertible_flag(\n        \"--no-auto-baseline\",\n        default=True,\n        group=based_group,\n        dest=\"auto_baseline\",\n        help=\"Don't update the baseline automatically.\",\n    )\n    add_invertible_flag(\n        \"--no-strict\",\n        default=True,\n        dest=\"special-opts:strict\",\n        help=\"Remove based strictness (inverse: --strict)\",\n        group=based_group,\n    )\n    add_invertible_flag(\n        \"--no-default-return\",\n        default=True,\n        dest=\"default_return\",\n        help=\"Assume implicit default return type of None\",\n        group=based_group,\n    )\n    add_invertible_flag(\n        \"--show-any-from-error\",\n        default=True,\n        dest=\"hide_any_from_error\",\n        help=\"Include Any type from errors in no-any-expr messages.\",\n        group=based_group,\n    )\n    add_invertible_flag(\n        \"--no-infer-function-types\",\n        group=based_group,\n        dest=\"infer_function_types\",\n        default=True,\n        help=\"Don't infer the type annotations of functions.\",\n    )\n    add_invertible_flag(\n        \"--incomplete-is-typed\",\n        group=based_group,\n        default=True,\n        help=\"Partially typed/incomplete functions in this module are considered typed\"\n        \" for untyped call errors.\",\n    )\n    add_invertible_flag(\n        \"--no-bare-literals\",\n        default=True,\n        dest=\"bare_literals\",\n        help=\"Disallow bare literals.\",\n        group=based_group,\n    )\n    add_invertible_flag(\n        \"--ignore-missing-py-typed\",\n        default=False,\n        help=\"Use types from a package, even if it doesn't have a py.typed. \"\n        \"You probably want to set this on a module override\",\n        group=based_group,\n    )\n    add_invertible_flag(\n        \"--ide\", default=False, help=\"Best default for IDE integration.\", group=based_group\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_FILES)})\"\n        ),\n    )\n    add_invertible_flag(\n        \"--no-warn-unused-configs\",\n        default=True,\n        dest=\"warn_unused_configs\",\n        help=\"Don't 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=\"Allow dynamic typing\",\n        description=\"Allow the use of the dynamic 'Any' type under certain conditions.\",\n    )\n    add_invertible_flag(\n        \"--allow-any-expr\",\n        default=True,\n        dest=\"disallow_any_expr\",\n        help=\"Allow expressions that have type Any\",\n        group=disallow_any_group,\n    )\n    add_invertible_flag(\n        \"--allow-any-decorated\",\n        default=True,\n        dest=\"disallow_any_decorated\",\n        help=\"Allow functions that have Any in their signature after decorator transformation\",\n        group=disallow_any_group,\n    )\n    add_invertible_flag(\n        \"--allow-any-explicit\",\n        default=True,\n        dest=\"disallow_any_explicit\",\n        help=\"Allow explicit Any in type positions\",\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        \"--allow-any-generics\",\n        default=True,\n        dest=\"disallow_any_generics\",\n        help=\"Allow usage of generic types that do not specify explicit type parameters\",\n        group=disallow_any_group,\n    )\n    add_invertible_flag(\n        \"--allow-subclassing-any\",\n        default=True,\n        dest=\"disallow_subclassing_any\",\n        help=\"Allow 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        \"--allow-untyped-calls\",\n        default=True,\n        dest=\"disallow_untyped_calls\",\n        help=\"Allow 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        \"--allow-untyped-defs\",\n        default=True,\n        dest=\"disallow_untyped_defs\",\n        help=\"Allow defining functions without type annotations\"\n        \" or with incomplete type annotations\",\n        group=untyped_group,\n    )\n    add_invertible_flag(\n        \"--allow-incomplete-defs\",\n        default=True,\n        dest=\"disallow_incomplete_defs\",\n        help=\"Allow defining functions with incomplete type annotations \"\n        \"(while still disallowing entirely unannotated definitions)\",\n        group=untyped_group,\n    )\n    add_invertible_flag(\n        \"--no-check-untyped-defs\",\n        default=True,\n        dest=\"check_untyped_defs\",\n        help=\"Don't type check the interior of functions without type annotations\",\n        group=untyped_group,\n    )\n    add_invertible_flag(\n        \"--allow-untyped-decorators\",\n        default=True,\n        dest=\"disallow_untyped_decorators\",\n        help=\"Allow 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://kotlinisland.github.io/basedmypy/kinds_of_types.html#no-strict-optional\",\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    add_invertible_flag(\n        \"--force-uppercase-builtins\", default=False, help=argparse.SUPPRESS, group=none_group\n    )\n\n    add_invertible_flag(\n        \"--force-union-syntax\", default=False, help=argparse.SUPPRESS, group=none_group\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        \"--no-warn-redundant-casts\",\n        default=True,\n        dest=\"warn_redundant_casts\",\n        help=\"Do not warn about casting an expression to its inferred type\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--no-warn-unused-ignores\",\n        default=True,\n        dest=\"warn_unused_ignores\",\n        help=\"Do not 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        \"--no-warn-return-any\",\n        default=True,\n        dest=\"warn_return_any\",\n        help=\"Do not warn about returning values of type Any from non-Any typed functions\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--no-warn-unreachable\",\n        default=True,\n        dest=\"warn_unreachable\",\n        help=\"Do not 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        help=\"Report importing or using deprecated features as notes instead of errors\",\n        group=lint_group,\n    )\n\n    strictness_group = parser.add_argument_group(title=\"Miscellaneous strictness flags\")\n\n    add_invertible_flag(\n        \"--allow-untyped-globals\",\n        default=False,\n        help=\"Suppress toplevel errors caused by missing annotations\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--disallow-redefinition\",\n        default=True,\n        dest=\"allow_redefinition\",\n        help=\"Disallow unconditional variable redefinition with a new type\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--implicit-reexport\",\n        default=False,\n        help=\"Export all imports, not just aliased ones\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--no-strict-equality\",\n        default=True,\n        dest=\"strict_equality\",\n        help=\"Allow equality, identity, and container checks for non-overlapping types\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--strict-bytes\",\n        default=False,\n        strict_flag=False,\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        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    # --nonlocal-partial-types allows partial types spanning module top level and a function\n    # (implicitly defined in fine-grained incremental mode)\n    add_invertible_flag(\n        \"--nonlocal-partial-types\",\n        default=True,\n        dest=\"local_partial_types\",\n        help=\"Enable partial types in different scopes\",\n        group=strictness_group,\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        \"--hide-error-context\",\n        default=True,\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        \"--hide-error-code-links\",\n        dest=\"show_error_code_links\",\n        default=True,\n        help=\"Hide links to error code documentation\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--no-pretty\",\n        default=True,\n        dest=\"pretty\",\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        \"kotlinisland.github.io/basedmypy/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    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\",\n        action=\"store_true\",\n        help=\"Disable new experimental type inference algorithm\",\n    )\n    # Deprecated reverse variant of the above.\n    internals_group.add_argument(\n        \"--new-type-inference\", 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    # This undocumented feature makes callable subtypes with incorrect names count as valid (needed to check mypy itself)\n    internals_group.add_argument(\n        \"--work-not-properly-function-names\", action=\"store_true\", 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    other_group = parser.add_argument_group(title=\"Miscellaneous\")\n    other_group.add_argument(\"--quickstart-file\", help=argparse.SUPPRESS)\n    other_group.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\n    imports_group.add_argument(\n        \"--junit-format\",\n        choices=[\"global\", \"per_file\"],\n        default=\"global\",\n        help=\"If --junit-xml is set, specifies format. global: single test with all errors; per_file: one test entry per file with failures\",\n    )\n    other_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    other_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        help=\"Install detected missing library stub packages using pip\",\n        group=other_group,\n    )\n    add_invertible_flag(\n        \"--non-interactive\",\n        default=False,\n        help=(\n            \"Install stubs without asking for confirmation and hide \"\n            + \"errors, with --install-types\"\n        ),\n        group=other_group,\n        inverse=\"--interactive\",\n    )\n\n    if server_options:\n        # TODO: This flag is superfluous; remove after a short transition (2018-03-16)\n        other_group.add_argument(\n            \"--experimental\",\n            action=\"store_true\",\n            dest=\"fine_grained_incremental\",\n            help=\"Enable fine-grained incremental mode\",\n        )\n        other_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    # --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        \"--enable-bytearray-promotion\",\n        action=\"store_false\",\n        dest=\"disable_bytearray_promotion\",\n        help=argparse.SUPPRESS,\n    )\n    parser.add_argument(\n        \"--disable-bytearray-promotion\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n    parser.add_argument(\n        \"--enable-memoryview-promotion\",\n        action=\"store_false\",\n        dest=\"disable_memoryview_promotion\",\n        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        \"kotlinisland.github.io/basedmypy/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    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\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    mypy.options._based = cast(bool, dummy.__dict__[\"special-opts:strict\"])\n    mypy.options._legacy = os.getenv(\"__MYPY_UNDER_TEST__\") == \"2\"\n    # for '__MYPY_UNDER_TEST__', 1 means test mode, 2 means legacy test mode\n\n    based_enabled_codes = (\n        {\n            \"no-untyped-usage\",\n            \"possibly-undefined\",\n            \"redundant-expr\",\n            \"truthy-bool\",\n            \"truthy-iterable\",\n            \"ignore-without-code\",\n            \"unused-awaitable\",\n            \"redundant-self\",\n            \"explicit-override\",\n            \"callable-functiontype\",\n            \"possible-function\",\n            \"bad-cast\",\n        }\n        if mypy.options._based\n        else set()\n    )\n\n    options = Options()\n    strict_option_set = False\n\n    if not dummy.__dict__[\"special-opts:strict\"]:\n        if not os.getenv(\"__MYPY_UNDER_TEST__\"):\n            mypy.options._based = True\n\n    def set_strict_flags() -> None:\n        pass\n\n    def set_ide_flags() -> None:\n        for dest, value in {\n            \"show_error_context\": False,\n            \"error_summary\": False,\n            \"pretty\": False,\n            \"show_error_end\": True,\n            \"color_output\": False,\n        }.items():\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 IDE flags before parsing (if IDE mode enabled), so other command\n    # line options can override.\n    if dummy.ide:\n        set_ide_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\n    options.process_error_codes(\n        error_callback=parser.error, based_enabled_codes=based_enabled_codes\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    if options.strict_bytes:\n        options.disable_bytearray_promotion = True\n        options.disable_memoryview_promotion = True\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.new_type_inference:\n        print(\n            \"Warning: --new-type-inference flag is deprecated;\"\n            \" new type inference algorithm is already enabled by default\"\n        )\n\n    if options.strict_concatenate and not strict_option_set:\n        print(\"Warning: --strict-concatenate is deprecated; use --extra-checks instead\")\n\n    # Store targets\n    options._targets = (\n        [f\"module:{el}\" for el in special_opts.modules]\n        + [f\"package:{el}\" for el in special_opts.packages]\n        + [f\"file:{el}\" for el in special_opts.files]\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        return targets, options\n    elif special_opts.command:\n        options.build_type = BuildType.PROGRAM_TEXT\n        targets = [BuildSource(None, None, \"\\n\".join(special_opts.command))]\n        return targets, options\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, UntypedType, 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 = UntypedType()\n        return [Instance(supertype, [any_type] * len(supertype.type_vars))]\n"
  },
  {
    "path": "mypy/meet.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nimport mypy.options\nfrom mypy import join\nfrom mypy.erasetype import erase_type\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT\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 (\n    is_recursive_pair,\n    make_simplified_intersection,\n    make_simplified_union,\n    tuple_fallback,\n)\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    IntersectionType,\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    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# 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, intersect=False) -> ProperType:\n    \"\"\"Return the greatest lower bound of two types.\"\"\"\n    if mypy.options._based and intersect:\n        # TODO: always intersect at meets\n        return make_simplified_intersection([s, t])\n\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):  # type: ignore[misc]\n    # A type guard forces the new type even if it doesn't overlap the old.\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        # We do this logic to preserve the original order of things\n        #  but if the new ones metadata is different to the declared one we take it\n        items = get_proper_types(narrowed.items if isinstance(narrowed, UnionType) else [narrowed])\n        if any(isinstance(item, Instance) and item.metadata for item in items):\n            return original_narrowed\n        items = get_proper_types(declared.items if isinstance(declared, UnionType) else [declared])\n        if any(isinstance(item, Instance) and item.metadata for item in items):\n            return original_narrowed\n        return original_declared\n    if isinstance(declared, UnionType):\n        return make_simplified_union(\n            [\n                narrow_declared_type(x, narrowed)\n                for x in declared.relevant_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                if (\n                    is_overlapping_types(x, narrowed, ignore_promotions=True)\n                    or is_subtype(narrowed, x, ignore_promotions=False)\n                )\n            ]\n        )\n    if is_enum_overlapping_union(declared, narrowed):\n        return original_narrowed\n    elif not is_overlapping_types(declared, narrowed, prohibit_none_typevar_overlap=True):\n        return IntersectionType([declared, narrowed])\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, IntersectionType):\n        return make_simplified_intersection(\n            [narrow_declared_type(declared, x) for x in narrowed.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(narrow_declared_type(declared.item, narrowed.item))\n    elif (\n        isinstance(declared, TypeType)\n        and isinstance(narrowed, Instance)\n        and narrowed.type.is_metaclass()\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    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, IntersectionType)):\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_overlapping_types(\n    left: Type,\n    right: Type,\n    ignore_promotions: bool = False,\n    prohibit_none_typevar_overlap: bool = False,\n    overlap_for_overloads: bool = False,\n    seen_types: set[tuple[Type, Type]] | None = None,\n    *,\n    check_variance=False,\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 'prohibit_none_typevar_overlap' is True, we disallow None from overlapping with\n    TypeVars (in both strict-optional and non-strict-optional mode).\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(  # type: ignore[misc]\n    #     right, TypeGuardedType\n    # ):\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    if (left, right) in seen_types:\n        return True\n    if isinstance(left, TypeAliasType) and isinstance(right, TypeAliasType):\n        seen_types.add((left, right))\n\n    left, right = get_proper_types((left, right))\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            prohibit_none_typevar_overlap=prohibit_none_typevar_overlap,\n            overlap_for_overloads=overlap_for_overloads,\n            seen_types=seen_types.copy(),\n        )\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    def is_none_object_overlap(t1: Type, t2: Type) -> bool:\n        t1, t2 = get_proper_types((t1, t2))\n        return (\n            isinstance(t1, NoneType)\n            and isinstance(t2, Instance)\n            and t2.type.fullname == \"builtins.object\"\n        )\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    def _is_subtype(left: Type, right: Type) -> bool:\n        if overlap_for_overloads:\n            return is_proper_subtype(left, right, ignore_promotions=ignore_promotions)\n        else:\n            return is_subtype(left, right, ignore_promotions=ignore_promotions)\n\n    if _is_subtype(left, right) or _is_subtype(right, left):\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_none_typevarlike_overlap(t1: Type, t2: Type) -> bool:\n        t1, t2 = get_proper_types((t1, t2))\n        return isinstance(t1, NoneType) and isinstance(t2, TypeVarLikeType)\n\n    if prohibit_none_typevar_overlap:\n        if is_none_typevarlike_overlap(left, right) or is_none_typevarlike_overlap(right, left):\n            return False\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    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    if isinstance(left, TypeType) or isinstance(right, TypeType):\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 _is_subtype(left, right) or _is_subtype(right, left):\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 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 not check_variance:\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            else:\n                for l_var, l_var_def, r_var, r_var_def in zip(\n                    left.args, left.type.defn.type_vars, right.args, right.type.defn.type_vars\n                ):\n                    if not isinstance(l_var_def, TypeVarType):\n                        # TODO: what about other kinds of TypeVarLikeTypes?\n                        return False\n                    if l_var_def.variance is INVARIANT:\n                        if not is_same_type(l_var, r_var):\n                            return False\n                    elif l_var_def.variance is COVARIANT:\n                        if not is_subtype(l_var, r_var):\n                            return False\n                    elif l_var_def.variance is CONTRAVARIANT:\n                        if not is_subtype(r_var, l_var):\n                            return False\n                return True\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),\n        erase_type(right),\n        ignore_promotions=ignore_promotions,\n        prohibit_none_typevar_overlap=True,\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    return all(is_overlapping(l, r) for l, r in zip(left.items, right.items))\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_intersection_type(self, t: IntersectionType) -> ProperType:\n        raise NotImplementedError(\n            \"This message should never appear, if you have encountered it, please raise an issue. Context: TypeMeetVisitor.visit_intersection_type\"\n        )\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            return self.s\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(typ, line=t.line)\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.as_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, getattr\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\n\n\nclass ErrorMessage(NamedTuple):\n    value: str\n    code: codes.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)\nINVALID_BARE_LITERAL: Final = ErrorMessage(\n    '\"{0}\" is a bare literal and cannot be used here, try Literal[{0}] 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    \"This usage of this contravariant type variable is unsafe as a return type.\",\n    codes.UNSAFE_VARIANCE,\n)\nFUNCTION_PARAMETER_CANNOT_BE_COVARIANT: Final = ErrorMessage(\n    \"This usage of this covariant type variable is unsafe as an input parameter.\",\n    codes.UNSAFE_VARIANCE,\n)\nUNSAFE_VARIANCE_NOTE = ErrorMessage(\n    \"If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\",\n    codes.UNSAFE_VARIANCE,\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)\nARGUMENT_TYPE_EXPECTED: Final = ErrorMessage(\n    \"Function is missing a type annotation for one or more arguments\", 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 parameters 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 {}'\nCANNOT_USE_TYPEVAR_AS_EXPRESSION: Final = 'Type variable \"{}.{}\" cannot be used as an expression'\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 argument 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_MAKE_DELETABLE_FINAL: Final = ErrorMessage(\"Deletable attribute cannot be final\")\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_TYPEVARS: Final = \"ClassVar cannot contain type variables\"\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)\")\n\n# Based\nTYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage(\"Type {} requires positional argument\")\nTYPE_GUARD_POS_LIMITATION: Final = ErrorMessage(\n    \"Type guard on star argument is not yet supported\", codes.TYPEGUARD_LIMITATION\n)\nTYPE_CHECK_ONLY: Final = ErrorMessage(\n    'Symbol \"{}\" is not accessible at runtime', codes.TYPE_CHECK_ONLY\n)\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_TYPEARGS: Final = ErrorMessage(\n    \"Ellipses cannot accompany other argument types in function type signature\", codes.SYNTAX\n)\nTYPE_SIGNATURE_TOO_MANY_ARGS: Final = ErrorMessage(\n    \"Type signature has too many arguments\", codes.SYNTAX\n)\nTYPE_SIGNATURE_TOO_FEW_ARGS: Final = ErrorMessage(\n    \"Type signature has too few arguments\", 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_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 Collection, Iterable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom textwrap import dedent\nfrom typing import Any, Callable, Final, cast\n\nimport mypy.options\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 ErrorInfo, Errors, ErrorWatcher\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    ClassDef,\n    Context,\n    Expression,\n    FuncDef,\n    IndexExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    ReturnStmt,\n    StrExpr,\n    SymbolNode,\n    SymbolTable,\n    TypeInfo,\n    Var,\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_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    IntersectionType,\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    \"basedtyping.Intersection\",\n    \"basedtyping.FunctionType\",\n    \"basedtyping.Untyped\",\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    ) -> ErrorWatcher:\n        return ErrorWatcher(\n            self.errors, filter_errors=filter_errors, save_filtered_errors=save_filtered_errors\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 cyles producing\n        complex error messages.\n        \"\"\"\n        return self.errors.prefer_simple_messages()\n\n    def report(\n        self,\n        msg: str,\n        context: Context | None,\n        severity: str,\n        *,\n        code: ErrorCode | None = None,\n        file: str | None = None,\n        origin: Context | None = None,\n        offset: int = 0,\n        allow_dups: bool = False,\n        secondary_context: Context | None = None,\n        notes: list[str] | None = None,\n    ) -> None:\n        \"\"\"Report an error or note (unless disabled).\n\n        Note that context controls where error is reported, while origin controls\n        where # type: ignore comments have effect.\n        \"\"\"\n\n        def span_from_context(ctx: Context) -> Iterable[int]:\n            \"\"\"This determines where a type: ignore for a given context has effect.\n\n            Current logic is a bit tricky, to keep as much backwards compatibility as\n            possible. We may reconsider this to always be a single line (or otherwise\n            simplify it) when we drop Python 3.7.\n\n            TODO: address this in follow up PR\n            \"\"\"\n            if isinstance(ctx, (ClassDef, FuncDef)):\n                return range(ctx.line, ctx.line + 1)\n            elif not isinstance(ctx, Expression):\n                return [ctx.line]\n            else:\n                return range(ctx.line, (ctx.end_line or ctx.line) + 1)\n\n        origin_span: Iterable[int] | None\n        if origin is not None:\n            origin_span = span_from_context(origin)\n        elif context is not None:\n            origin_span = span_from_context(context)\n        else:\n            origin_span = None\n\n        if secondary_context is not None:\n            assert origin_span is not None\n            origin_span = itertools.chain(origin_span, span_from_context(secondary_context))\n\n        self.errors.report(\n            context.line if context else -1,\n            context.column if context else -1,\n            msg,\n            severity=severity,\n            file=file,\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            code=code,\n            allow_dups=allow_dups,\n            notes=notes,\n        )\n\n    def fail(\n        self,\n        msg: str,\n        context: Context | None,\n        *,\n        code: ErrorCode | None = None,\n        file: str | None = None,\n        allow_dups: bool = False,\n        secondary_context: Context | None = None,\n        notes: list[str] | None = None,\n    ) -> None:\n        \"\"\"Report an error message (unless disabled).\"\"\"\n        self.report(\n            msg,\n            context,\n            \"error\",\n            code=code,\n            file=file,\n            allow_dups=allow_dups,\n            secondary_context=secondary_context,\n            notes=notes,\n        )\n\n    def note(\n        self,\n        msg: str,\n        context: Context,\n        file: str | None = None,\n        origin: Context | None = None,\n        offset: int = 0,\n        allow_dups: bool = False,\n        *,\n        code: ErrorCode | None = None,\n        secondary_context: Context | None = None,\n    ) -> None:\n        \"\"\"Report a note (unless disabled).\"\"\"\n        self.report(\n            msg,\n            context,\n            \"note\",\n            file=file,\n            origin=origin,\n            offset=offset,\n            allow_dups=allow_dups,\n            code=code,\n            secondary_context=secondary_context,\n        )\n\n    def note_multiline(\n        self,\n        messages: str,\n        context: Context,\n        file: str | None = None,\n        offset: int = 0,\n        allow_dups: bool = False,\n        code: ErrorCode | None = None,\n        *,\n        secondary_context: Context | None = None,\n    ) -> None:\n        \"\"\"Report as many notes as lines in the message (unless disabled).\"\"\"\n        for msg in messages.splitlines():\n            self.report(\n                msg,\n                context,\n                \"note\",\n                file=file,\n                offset=offset,\n                allow_dups=allow_dups,\n                code=code,\n                secondary_context=secondary_context,\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\n                in {\"typing.Callable\", \"typing._NamedCallable\", \"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    ) -> None:\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        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 partially_typed_function_call(self, callee: CallableType, context: CallExpr):\n        name = callable_name(callee) or (\n            context.callee.name\n            if isinstance(context.callee, (NameExpr, MemberExpr))\n            else \"(anonymous)\"\n        )\n        self.fail(\n            f\"Call to incomplete function {name} in typed context\",\n            context,\n            code=codes.NO_UNTYPED_CALL,\n            notes=[f'Type is \"{callee}\"'],\n        )\n\n    def untyped_indexed_assignment(self, context: IndexExpr):\n        # don't care about CallExpr because they are handled by partially_typed_function_call\n        if isinstance(context.base, (NameExpr, MemberExpr)):\n            message = f'Untyped indexed-assignment to \"{context.base.name}\" in typed context'\n            self.fail(message, context, code=codes.NO_UNTYPED_USAGE)\n\n    def untyped_name_usage(self, name: str | Expression, context: Context):\n        if isinstance(name, NameExpr):\n            name = name.name\n        elif not isinstance(name, str):\n            self.fail(\n                \"Usage of untyped name in typed context\", context, code=codes.NO_UNTYPED_USAGE\n            )\n            return\n        self.fail(\n            f'Usage of untyped name \"{name}\" in typed context',\n            context,\n            code=codes.NO_UNTYPED_USAGE,\n        )\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    ) -> ErrorCode | None:\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 callee.bound_args and callee.bound_args[0] is not None:\n                base = format_type(callee.bound_args[0], self.options)\n            else:\n                base = extract_type(name)\n\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                            self.unsupported_operand_types(\n                                op, arg_type, base, context, code=codes.OPERATOR\n                            )\n                        else:\n                            self.unsupported_operand_types(\n                                op, base, arg_type, context, code=codes.OPERATOR\n                            )\n                        return codes.OPERATOR\n\n            if name.startswith('\"__getitem__\" of'):\n                self.invalid_index_type(\n                    arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX\n                )\n                return codes.INDEX\n\n            if name.startswith('\"__setitem__\" of'):\n                if n == 1:\n                    self.invalid_index_type(\n                        arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX\n                    )\n                    return codes.INDEX\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                    self.fail(error_msg.value, context, code=error_msg.code)\n                    return error_msg.code\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 = list(expected_type.items)\n                else:\n                    expected_types = [expected_type]\n                for type in get_proper_types(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        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 code\n\n    def incompatible_argument_note(\n        self,\n        original_caller_type: ProperType,\n        callee_type: ProperType,\n        context: Context,\n        code: ErrorCode | None,\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, code=code\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, code=code\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=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=code)\n        self.maybe_note_concatenate_pos_args(original_caller_type, callee_type, context, code)\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    ) -> None:\n        index_str, expected_str = format_type_distinctly(\n            index_type, expected_type, options=self.options\n        )\n        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\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 = callee.def_extras.get(\"first_arg\")\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        module = find_defining_module(self.modules, callee)\n        if module and (not mypy.options._based or self.options.show_error_context):\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            self.note(\n                f\"{fname} defined here\",\n                callee.definition,\n                file=module.path,\n                origin=context,\n                code=codes.CALL_ARG,\n            )\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)\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 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        code = codes.OVERRIDE\n        target = self.override_target(name, name_in_super, supertype)\n        self.fail(f'Signature of \"{name}\" incompatible with {target}', context, code=code)\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        ALLOW_DUPS = True  # Allow duplicate notes, needed when signatures are duplicates\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(\n            \"Superclass:\", context, offset=ALIGN_OFFSET + OFFSET, allow_dups=ALLOW_DUPS, code=code\n        )\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                allow_dups=ALLOW_DUPS,\n                code=code,\n            )\n        else:\n            self.note(\n                original_str,\n                context,\n                offset=ALIGN_OFFSET + 2 * OFFSET,\n                allow_dups=ALLOW_DUPS,\n                code=code,\n            )\n\n        self.note(\n            \"Subclass:\", context, offset=ALIGN_OFFSET + OFFSET, allow_dups=ALLOW_DUPS, code=code\n        )\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                allow_dups=ALLOW_DUPS,\n                code=code,\n            )\n        else:\n            self.note(\n                override_str,\n                context,\n                offset=ALIGN_OFFSET + 2 * OFFSET,\n                allow_dups=ALLOW_DUPS,\n                code=code,\n            )\n\n    def pretty_callable_or_overload(\n        self,\n        tp: CallableType | Overloaded,\n        context: Context,\n        *,\n        offset: int = 0,\n        add_class_or_static_decorator: bool = False,\n        allow_dups: bool = False,\n        code: ErrorCode | None = None,\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, allow_dups=allow_dups, code=code)\n            self.note(\n                pretty_callable(tp, self.options),\n                context,\n                offset=offset,\n                allow_dups=allow_dups,\n                code=code,\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                allow_dups=allow_dups,\n                code=code,\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        secondary_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            secondary_context=secondary_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            self.note(\n                \"This violates the Liskov substitution principle\",\n                context,\n                code=codes.OVERRIDE,\n                secondary_context=secondary_context,\n            )\n            self.note(\n                \"See https://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\",\n                context,\n                code=codes.OVERRIDE,\n                secondary_context=secondary_context,\n            )\n\n        if name == \"__eq__\" and type_name:\n            multiline_msg = self.comparison_method_example_msg(class_name=type_name)\n            self.note_multiline(\n                multiline_msg, context, code=codes.OVERRIDE, secondary_context=secondary_context\n            )\n\n    def comparison_method_example_msg(self, class_name: str) -> str:\n        return dedent(\n            \"\"\"\\\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(\n                class_name=class_name\n            )\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://kotlinisland.github.io/basedmypy/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, n: int, context: Context\n    ) -> None:\n        callee_name = callable_name(callee_type)\n        if callee_name is not None and n > 0:\n            self.fail(f\"Cannot infer type argument {n} of {callee_name}\", context)\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(\"Keywords must be strings\", context)\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        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)\n            self.note(\"Redefinition:\", defn)\n            self.pretty_callable_or_overload(new_type, defn, offset=4)\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,\n        callee: CallableType,\n        typ: Type,\n        typevar_name: str,\n        context: Context,\n        *,\n        constrained=False,\n    ) -> None:\n        name = callable_name(callee)\n        self.fail(\n            message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(\n                typevar_name, name or \"function\", format_type(typ, self.options)\n            ),\n            context,\n            code=codes.TYPE_VAR,\n            notes=(\n                [\n                    f'\"{typevar_name}\" of {name or \"function\"} is a constrained type variable, it is not generic'\n                ]\n                if constrained\n                else None\n            ),\n        )\n\n    def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None:\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_arg_specific(self, index: int, context: Context) -> None:\n        self.fail(\n            (\n                f\"Overloaded function implementation does not accept all possible arguments \"\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, defined: Type | None = None) -> None:\n        visitor = TypeStrVisitor(options=self.options)\n        type_string = typ.accept(visitor)\n        defined_string = \"\"\n        if defined:\n            defined_string = defined.accept(visitor)\n            if defined_string.replace(\"partially defined: \", \"\") == type_string.replace(\n                \"Any (unannotated)\", \"?\"\n            ):\n                type_string = defined_string\n                defined_string = \"\"\n        message = f'Revealed type is \"{type_string}\"'\n        if defined_string:\n            message += f' (narrowed from \"{defined_string}\")'\n        self.note(message, context, code=codes.REVEAL)\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, code=codes.REVEAL)\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, python_version: tuple[int, int] | None = None\n    ) -> None:\n        hint = \"\"\n        pep604_supported = not python_version or python_version >= (3, 10)\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 python_version and isinstance(node, Var) and isinstance(node.type, PartialType):\n            type_dec = \"<type>\"\n            if not node.type.type:\n                # partial None\n                if pep604_supported:\n                    recommended_type = f\"{type_dec} | None\"\n                else:\n                    recommended_type = f\"Optional[{type_dec}]\"\n            elif node.type.type.fullname in reverse_builtin_aliases:\n                # partial types other than partial None\n                if mypy.options._based:\n                    alias = node.type.type.fullname\n                else:\n                    alias = reverse_builtin_aliases[node.type.type.fullname]\n                alias = alias.split(\".\")[-1]\n                if alias.lower() == \"dict\":\n                    type_dec = f\"{type_dec}, {type_dec}\"\n                if self.options.use_lowercase_names():\n                    alias = alias.lower()\n                recommended_type = f\"{alias}[{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 = f'Expression has type \"{typ.describe()}\"'\n        else:\n            message = f'Expression type contains \"Any\" (has type {format_type(typ, self.options)})'\n        self.fail(message, context, code=codes.ANY_EXPR)\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_extensions.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(\n                \"Function is untyped after decorator transformation\",\n                context,\n                code=codes.DECORATED_ANY,\n            )\n        else:\n            self.fail(\n                f'Type of decorated function contains type \"Any\" ({format_type(typ, self.options)})',\n                context,\n                code=codes.DECORATED_ANY,\n            )\n\n    def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None:\n        self.fail(f'Untyped decorator makes function \"{func_name}\" untyped', context)\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        if mypy.options._based:\n            template = \"Intersection of {} cannot exist: {}\"\n        else:\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        code: ErrorCode | None,\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            if not isinstance(subtype.partial_fallback, Instance):\n                return\n            subtype = subtype.partial_fallback\n        elif isinstance(subtype, TypedDictType):\n            if not isinstance(subtype.fallback, Instance):\n                return\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                    code=code,\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                    code=code,\n                )\n                self.note(\", \".join(missing), context, offset=OFFSET, code=code)\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(f\"Following member(s) of {type_name} have conflicts:\", context, code=code)\n            for name, got, exp in conflict_types[:MAX_ITEMS]:\n                exp = get_proper_type(exp)\n                got = get_proper_type(got)\n                if not isinstance(exp, (CallableType, Overloaded)) or not isinstance(\n                    got, (CallableType, Overloaded)\n                ):\n                    self.note(\n                        \"{}: expected {}, got {}\".format(\n                            name, *format_type_distinctly(exp, got, options=self.options)\n                        ),\n                        context,\n                        offset=OFFSET,\n                        code=code,\n                    )\n                else:\n                    self.note(\"Expected:\", context, offset=OFFSET, code=code)\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                            code=code,\n                        )\n                    else:\n                        assert isinstance(exp, Overloaded)\n                        self.pretty_overload(\n                            exp, context, 2 * OFFSET, code=code, skip_self=class_obj or is_module\n                        )\n                    self.note(\"Got:\", context, offset=OFFSET, code=code)\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                            code=code,\n                        )\n                    else:\n                        assert isinstance(got, Overloaded)\n                        self.pretty_overload(\n                            got, context, 2 * OFFSET, code=code, skip_self=class_obj or is_module\n                        )\n            self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=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                    code=code,\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                    code=code,\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                    code=code,\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                    code=code,\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                    code=code,\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                    code=code,\n                )\n        self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=code)\n\n    def pretty_overload(\n        self,\n        tp: Overloaded,\n        context: Context,\n        offset: int,\n        *,\n        add_class_or_static_decorator: bool = False,\n        allow_dups: bool = False,\n        code: ErrorCode | None = None,\n        skip_self: bool = False,\n    ) -> None:\n        for item in tp.items:\n            self.note(\"@overload\", context, offset=offset, allow_dups=allow_dups, code=code)\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, allow_dups=allow_dups, code=code)\n\n            self.note(\n                pretty_callable(item, self.options, skip_self=skip_self),\n                context,\n                offset=offset,\n                allow_dups=allow_dups,\n                code=code,\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 \"{}[{}, {}, ... <{} more items>]\".format(\n                \"tuple\" if self.options.use_lowercase_names() else \"Tuple\",\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_bare(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(lhs_t, rhs_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\ndef quote_type_string(type_string: str) -> str:\n    \"\"\"Quotes a type representation for use in messages.\"\"\"\n    no_quote_regex = r\"^<(tuple|union): \\d+ items>$\"\n    if (\n        type_string in [\"Module\", \"overloaded function\", \"<deleted>\"]\n        or type_string.startswith(\"Module \")\n        or re.match(no_quote_regex, type_string) is not None\n        or type_string.endswith(\"?\")\n    ):\n        # Messages are easier to read if these aren't quoted.  We use a\n        # regex to match strings with variable contents.\n        return type_string\n    return f'\"{type_string}\"'\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    star = False\n    slash = False\n    for arg_name, arg_type, arg_kind in zip(arg_names, arg_types, arg_kinds):\n        if mypy.options._based:\n            if not arg_name:\n                slash = True\n            elif slash:\n                arg_strings.append(\"/\")\n                slash = False\n            if arg_kind.is_named():\n                if not star:\n                    arg_strings.append(\"*\")\n                    star = True\n            if arg_kind is ARG_POS and not arg_name:\n                arg_strings.append(format(arg_type))\n                continue\n            elif arg_kind is ARG_POS:\n                arg_strings.append(f\"{arg_name}: {format(arg_type)}\")\n                continue\n            elif arg_kind is ARG_NAMED:\n                arg_strings.append(f\"{arg_name}: {format(arg_type)}\")\n                continue\n            elif arg_kind is ARG_OPT and not arg_name:\n                arg_strings.append(f\"{format(arg_type)}=...\")\n                continue\n            elif arg_kind is ARG_OPT:\n                arg_strings.append(f\"{arg_name}: {format(arg_type)}=...\")\n                continue\n            elif arg_kind is ARG_NAMED_OPT:\n                arg_strings.append(f\"{arg_name}: {format(arg_type)} = ...\")\n                continue\n            elif arg_kind is ARG_STAR:\n                arg_strings.append(\n                    f\"*{arg_name}: {format(arg_type)}\" if arg_name else f\"*{format(arg_type)}\"\n                )\n                continue\n            elif arg_kind is ARG_STAR2:\n                arg_strings.append(\n                    f\"**{arg_name}: {format(arg_type)}\" if arg_name else f\"**{format(arg_type)}\"\n                )\n                continue\n        if arg_kind == ARG_POS and arg_name is None or verbosity == 0 and arg_kind.is_positional():\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    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    disable_own_scope: Sequence[TypeVarLikeType] = (),\n) -> str:\n    \"\"\"\n    Convert a type to a relatively short string suitable for error messages.\n\n    Args:\n      verbosity: a coarse grained control on the verbosity of the type\n      fullnames: a set of names that should be printed in full\n      disable_own_scope: TypeVars to disable scope names\n    \"\"\"\n\n    def format(typ: Type) -> str:\n        return format_type_inner(\n            typ, verbosity, options, fullnames, disable_own_scope=disable_own_scope\n        )\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 itype.type.fullname in reverse_builtin_aliases and not options.use_lowercase_names():\n            alias = reverse_builtin_aliases[itype.type.fullname]\n            base_str = alias.split(\".\")[-1]\n        elif 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 not verbosity:\n                base_str = TypeStrVisitor.strip_builtins(base_str)\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' if options.use_lowercase_names() else '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        if mypy.options._based and typ.scopename and typ not in disable_own_scope:\n            return f\"{typ.name}@{typ.scopename}\"\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        if not mypy.options._based:\n            type_items = format_list(typ.items) or \"()\"\n            if options.use_lowercase_names():\n                s = f\"tuple[{type_items}]\"\n            else:\n                s = f\"Tuple[{type_items}]\"\n        else:\n            s = format_list(typ.items)\n            s = f\"({s},)\" if len(typ.items) == 1 else f\"({s})\"\n        return s\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        if mypy.options._based:\n            return format_literal_value(typ)\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        if mypy.options._based:\n            return \" | \".join(format(item) for item in typ.items)\n\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 (\n                    f\"{literal_str} | None\"\n                    if options.use_or_syntax()\n                    else f\"Optional[{literal_str}]\"\n                )\n            elif union_items:\n                return (\n                    f\"{literal_str} | {format_union(union_items)}\"\n                    if options.use_or_syntax()\n                    else f\"Union[{', '.join(format_union_items(union_items))}, {literal_str}]\"\n                )\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 (\n                    f\"{format(rest[0])} | None\"\n                    if options.use_or_syntax()\n                    else f\"Optional[{format(rest[0])}]\"\n                )\n            else:\n                s = (\n                    format_union(typ.items)\n                    if options.use_or_syntax()\n                    else f\"Union[{', '.join(format_union_items(typ.items))}]\"\n                )\n            return s\n    elif isinstance(typ, IntersectionType):\n        return \" & \".join(format(typ) for typ in typ.items)\n    elif isinstance(typ, NoneType):\n        return \"None\"\n    elif isinstance(typ, AnyType):\n        return typ.describe()\n    elif isinstance(typ, DeletedType):\n        return \"<deleted>\"\n    elif isinstance(typ, UninhabitedType):\n        return \"Never\"\n    elif isinstance(typ, TypeType):\n        type_name = \"type\" if options.use_lowercase_names() else \"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.fallback_name == \"types.BuiltinFunctionType\":\n                return format(\n                    func.fallback.copy_modified(\n                        args=[\n                            Parameters(func.arg_types, func.arg_kinds, func.arg_names),\n                            func.ret_type,\n                        ]\n                    )\n                )\n            if func.variables:\n                disable_own_scope = func.variables\n            if func.type_guard is not None:\n                if mypy.options._based:\n                    return_type = (\n                        f\"{func.type_guard.target_desc} is {format(func.type_guard.type_guard)}\"\n                    )\n                    if func.type_guard.only_true:\n                        return_type += \" if True else False\"\n                else:\n                    return_type = f\"TypeGuard[{format(func.type_guard.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\n            prefix = func.prefix\n            if func.is_ellipsis_args:\n                if not mypy.options._based:\n                    return f\"Callable[..., {return_type}]\"\n                return f\"{prefix}(...) -> {return_type}\"\n            param_spec = func.param_spec()\n            if param_spec is not None:\n                if not mypy.options._based:\n                    return f\"Callable[{format(param_spec)}, {return_type}]\"\n                return f\"{prefix}({param_spec.name}) -> {return_type}\"\n            args = format_callable_args(\n                func.arg_types, func.arg_kinds, func.arg_names, format, verbosity\n            )\n            if not mypy.options._based:\n                return f\"Callable[[{args}], {return_type}]\"\n            args = (\n                TypeStrVisitor(options=options).render_callable_type_params(func, format)\n                + f\"({args})\"\n            )\n            return f\"{prefix}{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    for verbosity in range(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    if tp.definition is not None and isinstance(tp.definition, SYMBOL_FUNCBASE_TYPES):\n        if tp.definition.is_class:\n            return \"@classmethod\"\n        if tp.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 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            type_str = f\"Unpack[{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    # If we got a \"special arg\" (i.e: self, cls, etc...), prepend it to the arg list\n    if (\n        isinstance(tp.definition, FuncDef)\n        and hasattr(tp.definition, \"arguments\")\n        and not tp.from_concatenate\n    ):\n        definition_arg_names = [arg.variable.name for arg in tp.definition.arguments]\n        if (\n            len(definition_arg_names) > len(tp.arg_names)\n            and definition_arg_names[0]\n            and not skip_self\n        ):\n            if s:\n                s = \", \" + s\n            s = definition_arg_names[0] + s\n        s = f\"{tp.definition.name}({s})\"\n    elif tp.name:\n        first_arg = tp.def_extras.get(\"first_arg\")\n        if first_arg:\n            if s:\n                s = \", \" + s\n            s = first_arg + s\n        s = f\"{tp.name.split()[0]}({s})\"  # skip \"of Class\" part\n    else:\n        s = f\"({s})\"\n\n    s += \" -> \"\n    if tp.type_guard is not None:\n        if mypy.options._based:\n            s += f\"{tp.type_guard.target_desc} is {format_type_bare(tp.type_guard.type_guard, options)}\"\n        else:\n            s += f\"TypeGuard[{format_type_bare(tp.type_guard.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 ' if not mypy.options._based else tp.prefix}{s}\"\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]]:\n    \"\"\"Find members that are defined in 'left' but have incompatible types.\n    Return them as a list of ('member', 'got', 'expected').\n    \"\"\"\n    assert right.type.is_protocol\n    conflicts: list[tuple[str, Type, Type]] = []\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, options=options)\n        if IS_SETTABLE in get_member_flags(member, right):\n            is_compat = is_compat and is_subtype(supertype, subtype, options=options)\n        if not is_compat:\n            conflicts.append((member, subtype, supertype))\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):\n            item = (member, get_member_flags(member, left), get_member_flags(member, right))\n            all_flags.append(item)\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://kotlinisland.github.io/basedmypy/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\" aren\\'t 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\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\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 os.path.normpath(name) != os.path.abspath(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\") as f:\n            return f.read()\n\n    def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:\n        assert os.path.normpath(name) != os.path.abspath(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\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) -> sqlite3.Connection:\n    import sqlite3.dbapi2\n\n    db = sqlite3.dbapi2.connect(db_file)\n    db.executescript(SCHEMA)\n    return db\n\n\nclass SqliteMetadataStore(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.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\"))\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"
  },
  {
    "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    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\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        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_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, Optional, Union, cast\nfrom typing_extensions import TypeAlias as _TypeAlias\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], Optional[tuple[int, int]]]]\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://kotlinisland.github.io/basedmypy/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. To work around this error, see the 'ignore_missing_py_typed' option\"\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 = Union[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            self.results[id] = self._find_module(id, use_typeshed)\n            if (\n                not (fast_path or (self.options is not None and self.options.fast_module_lookup))\n                and self.results[id] is ModuleNotFoundReason.NOT_FOUND\n                and self._can_find_module_in_parent_dir(id)\n            ):\n                self.results[id] = ModuleNotFoundReason.WRONG_WORKING_DIRECTORY\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, ignore_missing_py_typed=False\n    ) -> OnePackageDir | ModuleNotFoundReason:\n        plausible_match = cast(Optional[OnePackageDir], None)\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 = os.path.join(pkg_dir, *components[:-1]), index == 0\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 (\n                plausible_match\n                if ignore_missing_py_typed\n                else ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS\n            )\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), ModuleNotFoundReason):\n                return True\n        return False\n\n    def _find_module(self, id: str, use_typeshed: bool) -> ModuleSearchResult:\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\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        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            ignore_missing_py_typed = (\n                self.options\n                and self.options.clone_for_module(\".\".join(components)).ignore_missing_py_typed\n            )\n            non_stub_match = self._find_module_non_stub_helper(\n                id, pkg_dir, ignore_missing_py_typed or False\n            )\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            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            # 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                path_stubs = base_path + \"-stubs\" + 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\n                elif 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                        continue\n                    return path_stubs\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\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]\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\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\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\n            if self.find_module(parent_id) is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\n                return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED\n            return ModuleNotFoundReason.NOT_FOUND\n\n        if found_possible_third_party_missing_type_hints:\n            return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS\n        return ModuleNotFoundReason.NOT_FOUND\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\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        if re.search(exclude, subpath_str):\n            if verbose:\n                print(\n                    f\"TRACE: Excluding {subpath_str} (matches pattern {exclude})\", file=sys.stderr\n                )\n            return True\n    return False\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        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            )\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    path.append(typeshed_dir)\n\n    # Get mypy-extensions stubs from typeshed, since we treat it as an\n    # \"internal\" library, similar to typing and typing-extensions.\n    path.append(mypy_extensions_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://kotlinisland.github.io/basedmypy/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.8, so 3.8 is\n    # the earliest we can support.\n    return max(options.python_version, (3, 8))\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\nfrom mypy.util import getattr\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 typing 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/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 Iterator, Sequence\nfrom enum import Enum, unique\nfrom typing import TYPE_CHECKING, Any, Callable, Final, Optional, TypeVar, Union, cast\nfrom typing_extensions import TypeAlias as _TypeAlias, TypeGuard\n\nfrom mypy_extensions import trait\n\nimport mypy.strconv\nfrom mypy.options import Options\nfrom mypy.util import is_typeshed_file, short_type\nfrom mypy.visitor import ExpressionVisitor, NodeVisitor, StatementVisitor\n\nif TYPE_CHECKING:\n    from mypy.patterns import Pattern\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\nLITERAL_YES: Final = 2\nLITERAL_TYPE: Final = 1\nLITERAL_NO: Final = 0\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    \"typing.Callable\": \"collections.abc.Callable\",\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_nongen_builtins: Final = {\"builtins.tuple\": \"typing.Tuple\", \"builtins.enumerate\": \"\"}\n_nongen_builtins.update((name, alias) for alias, name in type_aliases.items())\n\n_fake_generics = {\n    \"_collections_abc.dict_keys\": \"\",\n    \"_collections_abc.dict_values\": \"\",\n    \"_collections_abc.dict_items\": \"\",\n    \"_operator.attrgetter\": \"\",\n    \"_operator.itemgetter\": \"\",\n}\n\n\n# Drop OrderedDict from this for backward compatibility\ndel _nongen_builtins[\"collections.OrderedDict\"]\n# HACK: consequence of hackily treating LiteralString as an alias for str\ndel _nongen_builtins[\"builtins.str\"]\n\n\ndef get_nongen_builtins(python_version: tuple[int, int]) -> dict[str, str]:\n    # After 3.9 with pep585 generic builtins are allowed\n    result = _nongen_builtins if python_version < (3, 9) else {}\n    return {**result, **_fake_generics}\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        ans = self.accept(mypy.strconv.StrConv(options=Options()))\n        if ans is None:\n            return repr(self)\n        return ans\n\n    def str_with_options(self, options: Options) -> str:\n        ans = self.accept(mypy.strconv.StrConv(options=options))\n        assert ans\n        return ans\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\n# Items: fullname, related symbol table node, surrounding type (if any)\nDefinition: _TypeAlias = tuple[str, \"SymbolTableNode\", Optional[\"TypeInfo\"]]\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        \"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        \"plugin_deps\",\n        \"future_import_flags\",\n        \"_is_typeshed_file\",\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    # 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    # 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\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.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.future_import_flags = set()\n        self._is_typeshed_file = 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\": list(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\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\", \"is_type_check_only\"]\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        \"_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        self.is_static = False\n        self.is_final = False\n        self.is_explicit_override = False\n        self.is_type_check_only = 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\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__ = (\"items\", \"unanalyzed_items\", \"impl\", \"is_mypy_only\", \"deprecated\")\n\n    items: list[OverloadPart]\n    unanalyzed_items: list[OverloadPart]\n    impl: OverloadPart | None\n    is_mypy_only: bool\n    deprecated: str | 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        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        self.is_mypy_only = False\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    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        }\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        # NOTE: res.info will be set in the fixup phase.\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        from mypy.types import CallableType\n\n        return self.type is None or isinstance(self.type, CallableType) and self.type.implicit\n\n\nFUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [\n    \"is_decorated\",\n    \"is_conditional\",\n    \"is_trivial_body\",\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_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    )\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\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        }\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.arg_kinds = [ArgKind(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\n# All types that are both SymbolNodes and FuncBases. See the FuncBase\n# docstring for the rationale.\nSYMBOL_FUNCBASE_TYPES = (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 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        \"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    )\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        # 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 initialized explicitly to a non-None value in class body?\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\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 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            \"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        v = Var(name, 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\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\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\", \"is_mypy_only\")\n\n    __match_args__ = (\"expr\", \"body\", \"else_body\", \"is_mypy_only\")\n\n    expr: list[Expression]\n    body: list[Block]\n    else_body: Block | None\n    is_mypy_only: bool | None\n\n    def __init__(\n        self,\n        expr: list[Expression],\n        body: list[Block],\n        else_body: Block | None,\n        is_mypy_only: bool | None = None,\n    ) -> None:\n        super().__init__()\n        self.expr = expr\n        self.body = body\n        self.else_body = else_body\n        self.is_mypy_only = is_mypy_only\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\", \"patterns\", \"guards\", \"bodies\")\n\n    __match_args__ = (\"subject\", \"patterns\", \"guards\", \"bodies\")\n\n    subject: Expression\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.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\",)\n\n    __match_args__ = (\"value\",)\n\n    value: str  # '' by default\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_str_expr(self)\n\n\ndef is_StrExpr_list(seq: list[Expression]) -> TypeGuard[list[StrExpr]]:  # type: ignore[typeguard-subtype]  # 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.TypeGuardType | 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\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\", \"type_guard\")\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        type_guard: mypy.types.TypeGuardType | 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        self.type_guard = type_guard\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\")\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\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\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: Expression, 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    )\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\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\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_op_expr(self)\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 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\", \"type_guard\")\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_guard: mypy.types.TypeGuardType | None = None,\n    ) -> None:\n        super().__init__(arguments=arguments, body=body, typ=typ)\n        self.type_guard = type_guard\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 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\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\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\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\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        \"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    )\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\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    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_intersection\",\n        \"is_type_check_only\",\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_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\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        return [\n            name\n            for name, sym in self.names.items()\n            if (\n                isinstance(sym.node, Var)\n                and name not in EXCLUDED_ENUM_ATTRIBUTES\n                and not name.startswith(\"__\")\n                and sym.node.has_explicit_value\n            )\n        ]\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                if isinstance(node, FuncBase):\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        candidates = [\n            s.declared_metaclass\n            for s in self.mro\n            if s.declared_metaclass is not None and s.declared_metaclass.type is not None\n        ]\n        for c in candidates:\n            if all(other.type in c.type.mro for other in candidates):\n                return c\n        return None\n\n    def is_metaclass(self) -> bool:\n        return (\n            self.has_base(\"builtins.type\")\n            or self.fullname == \"abc.ABCMeta\"\n            or self.fallback_to_any\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\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\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        # TODO: Is there a reason to reconstruct ti.subtypes?\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\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 in (\"__class__\", \"msg\"):\n            return cast(type, object.__getattribute__(self, attr))\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    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        \"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        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.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.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.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 serialize(self) -> JsonDict:\n        data: JsonDict = {\n            \".class\": \"TypeAlias\",\n            \"fullname\": self._fullname,\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            \"line\": self.line,\n            \"column\": self.column,\n            \"python_3_12_type_alias\": self.python_3_12_type_alias,\n        }\n        return data\n\n    def accept(self, visitor: NodeVisitor[T]) -> T:\n        return visitor.visit_type_alias(self)\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeAlias:\n        assert data[\".class\"] == \"TypeAlias\"\n        fullname = data[\"fullname\"]\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        line = data[\"line\"]\n        column = data[\"column\"]\n        python_3_12_type_alias = data[\"python_3_12_type_alias\"]\n        return cls(\n            target,\n            fullname,\n            line,\n            column,\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\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\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                a.append(\"  <invalid item>\")\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\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\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 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_arg_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 argument \"{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(\n    node: SymbolNode | None,\n) -> node is Var | FuncDef | OverloadedFuncDef | Decorator if True else False:\n    \"\"\"Check whether `node` corresponds to a final attribute.\"\"\"\n    return isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)) and node.is_final\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"
  },
  {
    "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 Mapping\nfrom re import Pattern\nfrom typing import Any, Callable, Final\n\nfrom mypy import defaults\nfrom mypy.errorcodes import ErrorCode, error_codes\nfrom mypy.util import get_class_descriptors, getattr, 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\",\n    \"allow_untyped_globals\",\n    \"always_false\",\n    \"always_true\",\n    \"check_untyped_defs\",\n    \"debug_cache\",\n    \"default_return\",\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    \"ignore_missing_py_typed\",\n    \"implicit_optional\",\n    \"implicit_reexport\",\n    \"local_partial_types\",\n    \"infer_function_types\",\n    \"mypyc\",\n    \"nonlocal_partial_types\",\n    \"incomplete_is_typed\",\n    \"strict_concatenate\",\n    \"strict_equality\",\n    \"strict_optional\",\n    \"warn_no_return\",\n    \"warn_return_any\",\n    \"warn_unreachable\",\n    \"warn_unused_ignores\",\n    \"work_not_properly_function_names\",\n}\n\nOPTIONS_AFFECTING_CACHE: Final = (\n    PER_MODULE_OPTIONS\n    | {\n        \"platform\",\n        \"bazel\",\n        \"old_type_inference\",\n        \"plugins\",\n        \"disable_bytearray_promotion\",\n        \"disable_memoryview_promotion\",\n        \"strict_bytes\",\n    }\n) - {\"debug_cache\"}\n\n_based = True\n\n\ndef flip_if_not_based(b: bool) -> bool:\n    \"\"\"Flips this bool if we are not based.\n\n    Used to run tests in non-strict and old mode.\n    \"\"\"\n    return b if _based else not b\n\n\n_legacy = False\n\n\ndef flip_if_legacy(b: bool) -> bool:\n    \"\"\"Flips this bool if we are legacy.\n\n    Used to run tests in old mode.\n    \"\"\"\n    return not b if _legacy else b\n\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\"\nINCOMPLETE_FEATURES: Final = frozenset((PRECISE_TUPLE_TYPES, INLINE_TYPEDDICT))\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        # stupid thing to make mypy project check properly\n        self.work_not_properly_function_names = False\n\n        # Cache for clone_for_module()\n        self._per_module_cache: dict[str, Options] | None = None\n        # Despite the warnings about _per_module_cache being slow, this one might be good\n        self._final_per_module_cache: dict[str, Options] = {}\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\n        # Based options\n        self.write_baseline = False\n        self.baseline_file = defaults.BASELINE_FILE\n        self.auto_baseline = True\n        self.default_return = True\n        self.infer_function_types = True\n        self._targets: list[str] = []\n        \"\"\"This is private so that it's not included in the snapshot\"\"\"\n        self.hide_any_from_error = True\n        self.incomplete_is_typed = flip_if_not_based(False)\n        self.bare_literals = True\n        self.ignore_missing_py_typed = False\n        self.ide = False\n\n        # disallow_any options\n        self.disallow_any_generics = flip_if_not_based(True)\n        self.disallow_any_unimported = flip_if_not_based(True)\n        self.disallow_any_expr = flip_if_not_based(True)\n        self.disallow_any_decorated = flip_if_not_based(True)\n        self.disallow_any_explicit = flip_if_not_based(True)\n\n        # Disallow calling untyped functions from typed ones\n        self.disallow_untyped_calls = flip_if_not_based(True)\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 = flip_if_not_based(True)\n\n        # Disallow defining incompletely typed functions\n        self.disallow_incomplete_defs = flip_if_not_based(True)\n\n        # Type check unannotated functions\n        self.check_untyped_defs = flip_if_not_based(True)\n\n        # Disallow decorating typed functions with untyped decorators\n        self.disallow_untyped_decorators = flip_if_not_based(True)\n\n        # Disallow subclassing values of type 'Any'\n        self.disallow_subclassing_any = flip_if_not_based(True)\n\n        # Also check typeshed for missing annotations\n        self.warn_incomplete_stub = flip_if_not_based(True)\n\n        # Warn about casting an expression to its inferred type\n        self.warn_redundant_casts = flip_if_not_based(True)\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 = flip_if_not_based(True)\n\n        # Report importing or using deprecated features as errors instead of notes.\n        self.report_deprecated_as_note = False\n\n        # Warn about unused '# type: ignore' comments\n        self.warn_unused_ignores = flip_if_not_based(True)\n\n        # Warn about unused '[mypy-<pattern>]'  or '[[tool.mypy.overrides]]' config sections\n        self.warn_unused_configs = flip_if_not_based(True)\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 = flip_if_legacy(True)\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 = flip_if_not_based(False)\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 = flip_if_not_based(True)\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 = flip_if_not_based(True)\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 = flip_if_not_based(True)\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 = False\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.shadow_file: list[list[str]] | None = None\n        self.show_column_numbers: bool = flip_if_not_based(True)\n        self.show_error_end: bool = False\n        self.hide_error_codes = False\n        self.show_error_code_links = True\n        # Use soft word wrap and show trimmed source snippets with error location markers.\n        self.pretty = True\n        self.dump_graph = False\n        self.dump_deps = False\n        self.logical_deps = False\n        # If True, partial types can span a module top level and a function\n        self.nonlocal_partial_types = flip_if_not_based(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 experimental type inference algorithm.\n        self.old_type_inference = False\n        # Deprecated reverse version of the above, do not use.\n        self.new_type_inference = False\n        # Export line-level, limited, fine-grained dependency information in cache data\n        # (undocumented feature).\n        self.export_ref_info = False\n\n        self.disable_bytearray_promotion = flip_if_not_based(True)\n        self.disable_memoryview_promotion = flip_if_not_based(True)\n        self.force_uppercase_builtins = False\n        self.force_union_syntax = False\n\n        # Sets custom output format\n        self.output: str | None = None\n\n    def use_lowercase_names(self) -> bool:\n        if self.python_version >= (3, 9) or _based:\n            return not self.force_uppercase_builtins\n        return False\n\n    def use_or_syntax(self) -> bool:\n        if self.python_version >= (3, 10):\n            return not self.force_union_syntax\n        return False\n\n    def use_star_unpack(self) -> bool:\n        return self.python_version >= (3, 11)\n\n    # To avoid breaking plugin compatibility, keep providing local_partial_types\n    @property\n    def local_partial_types(self) -> bool:\n        return not self.nonlocal_partial_types\n\n    @local_partial_types.setter\n    def local_partial_types(self, value: bool) -> None:\n        self.nonlocal_partial_types = not value\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(\n        self, *, error_callback: Callable[[str], Any], based_enabled_codes: set[str] | None = None\n    ) -> None:\n        # Process `--enable-error-code` and `--disable-error-code` flags\n        disabled_codes = set(self.disable_error_code)\n        self.enable_error_code.extend(sorted((based_enabled_codes or set()) - disabled_codes))\n        enabled_codes = set(self.enable_error_code)\n\n        valid_error_codes = set(error_codes.keys())\n\n        invalid_codes = (enabled_codes | disabled_codes) - valid_error_codes\n        if invalid_codes:\n            error_callback(f\"Invalid error code(s): {', '.join(sorted(invalid_codes))}\")\n\n        self.disabled_error_codes |= {error_codes[code] for code in disabled_codes}\n        self.enabled_error_codes |= {error_codes[code] for code in enabled_codes}\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 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\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            result = self._per_module_cache[module]\n            self._final_per_module_cache[module] = result\n            return result\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        # BASED: We cache it anyway, so.\n        self._final_per_module_cache[module] = options\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) -> Mapping[str, object]:\n        result: dict[str, object] = {}\n        for opt in OPTIONS_AFFECTING_CACHE:\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[opt] = val\n        return result\n\n    def per_module(self, module: str) -> Options:\n        return self._final_per_module_cache.get(module, self)\n"
  },
  {
    "path": "mypy/parse.py",
    "content": "from __future__ import annotations\n\nfrom mypy.errors import Errors\nfrom mypy.nodes import 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) -> 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.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"
  },
  {
    "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\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\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        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\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.else_body:\n            if not o.else_body.is_unreachable:\n                o.else_body.accept(self)\n            else:\n                self.tracker.skip_branch()\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                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        self.tracker.skip_branch()\n\n    def visit_expression_stmt(self, o: ExpressionStmt) -> None:\n        if isinstance(self.type_map.get(o.expr, None), (UninhabitedType, type(None))):\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            o.finally_body.accept(self)\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 self.tracker.is_possibly_undefined(o.name):\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 typing import Any, Callable, NamedTuple, TypeVar\n\nfrom mypy_extensions import mypyc_attr, trait\n\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.lookup import lookup_fully_qualified\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.messages import MessageBuilder\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.tvar_scope import TypeVarLikeScope\nfrom mypy.types import (\n    CallableType,\n    FunctionLike,\n    Instance,\n    ProperType,\n    Type,\n    TypeList,\n    UnboundType,\n)\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    ) -> 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        return self._find_hook(lambda plugin: plugin.get_type_analyze_hook(fullname))\n\n    def get_function_signature_hook(\n        self, fullname: str\n    ) -> Callable[[FunctionSigContext], FunctionLike] | None:\n        return self._find_hook(lambda plugin: plugin.get_function_signature_hook(fullname))\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        return self._find_hook(lambda plugin: plugin.get_method_signature_hook(fullname))\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        return self._find_hook(lambda plugin: plugin.get_method_hook(fullname))\n\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        return self._find_hook(lambda plugin: plugin.get_attribute_hook(fullname))\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:\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, Optional, 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 get_type_vars, make_simplified_union, map_type_from_supertype\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, 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    kw_only=True means that all attributes created here will be keyword only args 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, 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)\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, 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(ctx, auto_attribs, kw_only, lhs, rvalue, stmt)\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, 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    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, kw_only, None, stmt, init_type)\n\n\ndef _attribute_from_attrib_maker(\n    ctx: mypy.plugin.ClassDefContext,\n    auto_attribs: bool,\n    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    # Note: If the class decorator says kw_only=True the attribute is ignored.\n    # See https://github.com/python-attrs/attrs/issues/481 for explanation.\n    kw_only |= _get_bool_argument(ctx, rvalue, \"kw_only\", False)\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 = cast(Optional[Type], 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            from mypy.checkmember import type_object_type  # To avoid import cycle.\n\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        from mypy.checkmember import type_object_type  # To avoid import cycle.\n\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 = cast(Optional[list[Mapping[str, Type]]], [])\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 = 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/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, Optional, cast\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(\"Cannot inherit frozen dataclass from a non-frozen one\", 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(\"Cannot inherit non-frozen dataclass from a frozen one\", 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) for attr in attributes if attr.is_in_init\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        type_vars = [tv for tv in self._cls.type_vars]\n        add_method_to_class(\n            self._api,\n            self._cls,\n            \"__replace__\",\n            args=args,\n            return_type=Instance(self._cls.info, type_vars),\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        generated_slots = {attr.name for attr in attributes}\n        if (info.slots is not None and info.slots != generated_slots) or info.names.get(\n            \"__slots__\"\n        ):\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        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(self._api, self._cls, \"__slots__\", slots_type)\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        found_dataclass_supertype = False\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            found_dataclass_supertype = True\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)\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        if found_dataclass_supertype:\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                    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    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 = cast(Optional[list[CallableType]], [])\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 functools import partial\nfrom typing import Callable, Final\n\nimport mypy.errorcodes as codes\nfrom mypy import message_registry\nfrom mypy.nodes import DictExpr, 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.common import try_getting_str_literals\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\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        from mypy.plugins import ctypes, enums, re, singledispatch\n\n        if fullname == \"_ctypes.Array\":\n            return ctypes.array_constructor_callback\n        elif fullname == \"functools.singledispatch\":\n            return singledispatch.create_singledispatch_function_callback\n        elif (\n            fullname == \"re.match\"\n            or fullname == \"re.fullmatch\"\n            or fullname == \"re.search\"\n            or fullname == \"re.finditer\"\n        ):\n            return re.match\n        elif fullname == \"re.compile\" or fullname == \"re.template\":\n            return re.compile\n        elif fullname == \"re.split\":\n            return re.split\n        elif fullname == \"re.findall\":\n            return re.findall\n        elif fullname == \"functools.partial\":\n            import mypy.plugins.functools\n\n            return mypy.plugins.functools.partial_new_callback\n        elif fullname == \"enum.member\":\n            return enums.enum_member_callback\n\n        return None\n\n    def get_function_signature_hook(\n        self, fullname: str\n    ) -> Callable[[FunctionSigContext], FunctionLike] | None:\n        from mypy.plugins import attrs, dataclasses, re\n\n        if fullname in (\"attr.evolve\", \"attrs.evolve\", \"attr.assoc\", \"attrs.assoc\"):\n            return attrs.evolve_function_sig_callback\n        elif fullname in (\"attr.fields\", \"attrs.fields\"):\n            return attrs.fields_function_sig_callback\n        elif fullname == \"dataclasses.replace\":\n            return dataclasses.replace_function_sig_callback\n        elif fullname in {\"re.sub\", \"re.subn\"}:\n            return re.sub\n        return None\n\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], FunctionLike] | None:\n        from mypy.plugins import ctypes, re, singledispatch\n\n        if fullname == \"typing.Mapping.get\":\n            return typed_dict_get_signature_callback\n        elif fullname in {n + \".setdefault\" for n in TPDICT_FB_NAMES}:\n            return typed_dict_setdefault_signature_callback\n        elif fullname in {n + \".pop\" for n in TPDICT_FB_NAMES}:\n            return typed_dict_pop_signature_callback\n        elif fullname == \"_ctypes.Array.__setitem__\":\n            return ctypes.array_setitem_callback\n        elif fullname == singledispatch.SINGLEDISPATCH_CALLABLE_CALL_METHOD:\n            return singledispatch.call_singledispatch_function_callback\n        elif fullname in {\"re.Pattern.sub\", \"re.Pattern.subn\"}:\n            return re.sub\n\n        typed_dict_updates = set()\n        for n in TPDICT_FB_NAMES:\n            typed_dict_updates.add(n + \".update\")\n            typed_dict_updates.add(n + \".__or__\")\n            typed_dict_updates.add(n + \".__ror__\")\n            typed_dict_updates.add(n + \".__ior__\")\n\n        if fullname in typed_dict_updates:\n            return typed_dict_update_signature_callback\n\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        from mypy.plugins import ctypes, re, singledispatch\n\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 {n + \".setdefault\" for n in TPDICT_FB_NAMES}:\n            return typed_dict_setdefault_callback\n        elif fullname in {n + \".pop\" for n in TPDICT_FB_NAMES}:\n            return typed_dict_pop_callback\n        elif fullname in {n + \".__delitem__\" for n in TPDICT_FB_NAMES}:\n            return typed_dict_delitem_callback\n        elif fullname == \"_ctypes.Array.__getitem__\":\n            return ctypes.array_getitem_callback\n        elif fullname == \"_ctypes.Array.__iter__\":\n            return ctypes.array_iter_callback\n        elif fullname == singledispatch.SINGLEDISPATCH_REGISTER_METHOD:\n            return singledispatch.singledispatch_register_callback\n        elif fullname == singledispatch.REGISTER_CALLABLE_CALL_METHOD:\n            return singledispatch.call_singledispatch_function_after_register_argument\n        elif fullname == \"re.Match.groups\":\n            return re.match_groups\n        elif fullname == \"re.Match.group\" or fullname == \"re.Match.__getitem__\":\n            return re.match_group\n        elif fullname == \"re.Match.groupdict\":\n            return re.match_groupdict\n        elif (\n            fullname == \"re.Pattern.match\"\n            or fullname == \"re.Pattern.fullmatch\"\n            or fullname == \"re.Pattern.search\"\n            or fullname == \"re.Pattern.finditer\"\n        ):\n            return re.match\n        elif fullname == \"re.Pattern.split\":\n            return re.split\n        elif fullname == \"re.Pattern.findall\":\n            return re.findall\n        elif fullname == \"functools.partial.__call__\":\n            import mypy.plugins.functools\n\n            return mypy.plugins.functools.partial_call_callback\n        return None\n\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        from mypy.plugins import ctypes, enums\n\n        if fullname == \"_ctypes.Array.value\":\n            return ctypes.array_value_callback\n        elif fullname == \"_ctypes.Array.raw\":\n            return ctypes.array_raw_callback\n        elif fullname in enums.ENUM_NAME_ACCESS:\n            return enums.enum_name_callback\n        elif fullname in enums.ENUM_VALUE_ACCESS:\n            return enums.enum_value_callback\n        return None\n\n    def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        from mypy.plugins import attrs, dataclasses\n\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 dataclasses.dataclass_makers:\n            return dataclasses.dataclass_tag_callback\n        if (\n            fullname in attrs.attr_class_makers\n            or fullname in attrs.attr_dataclass_makers\n            or fullname in attrs.attr_frozen_makers\n            or fullname in attrs.attr_define_makers\n        ):\n            return attrs.attr_tag_callback\n\n        return None\n\n    def get_class_decorator_hook_2(\n        self, fullname: str\n    ) -> Callable[[ClassDefContext], bool] | None:\n        import mypy.plugins.functools\n        from mypy.plugins import attrs, dataclasses\n\n        if fullname in dataclasses.dataclass_makers:\n            return dataclasses.dataclass_class_maker_callback\n        elif fullname in mypy.plugins.functools.functools_total_ordering_makers:\n            return mypy.plugins.functools.functools_total_ordering_maker_callback\n        elif fullname in attrs.attr_class_makers:\n            return attrs.attr_class_maker_callback\n        elif fullname in attrs.attr_dataclass_makers:\n            return partial(attrs.attr_class_maker_callback, auto_attribs_default=True)\n        elif fullname in attrs.attr_frozen_makers:\n            return partial(\n                attrs.attr_class_maker_callback, auto_attribs_default=None, frozen_default=True\n            )\n        elif fullname in attrs.attr_define_makers:\n            return partial(\n                attrs.attr_class_maker_callback, auto_attribs_default=None, slots_default=True\n            )\n\n        return None\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        output_types: list[Type] = []\n        for key in keys:\n            value_type = get_proper_type(ctx.type.items.get(key))\n            if value_type is None:\n                return ctx.default_return_type\n\n            if len(ctx.arg_types) == 1:\n                output_types.append(value_type)\n            elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1:\n                default_arg = ctx.args[1][0]\n                if (\n                    isinstance(default_arg, DictExpr)\n                    and len(default_arg.items) == 0\n                    and isinstance(value_type, TypedDictType)\n                ):\n                    # Special case '{}' as the default for a typed dict type.\n                    output_types.append(value_type.copy_modified(required_keys=set()))\n                else:\n                    output_types.append(value_type)\n                    output_types.append(ctx.arg_types[1][0])\n\n        if len(ctx.arg_types) == 1:\n            output_types.append(NoneType())\n\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:\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 = arg_type.as_anonymous()\n        arg_type = arg_type.copy_modified(required_keys=set())\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(ctx.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 Final, TypeVar, cast\n\nimport mypy.plugin  # To avoid circular imports.\nfrom mypy.nodes import TypeInfo\nfrom mypy.semanal_enum import ENUM_BASES\nfrom mypy.subtypes import is_equivalent\nfrom mypy.typeops import fixup_partial_type, make_simplified_union\nfrom mypy.types import (\n    CallableType,\n    Instance,\n    LiteralType,\n    ProperType,\n    Type,\n    get_proper_type,\n    is_named_instance,\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\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    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 _implements_new(info: TypeInfo) -> bool:\n    \"\"\"Check whether __new__ comes from enum.Enum or was implemented in a\n    subclass. 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    type_with_new = _first(\n        ti\n        for ti in info.mro\n        if ti.names.get(\"__new__\") and not ti.fullname.startswith(\"builtins.\")\n    )\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 or 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.nodes import ARG_POS, ARG_STAR2, ArgKind, Argument, CallExpr, FuncItem, NameExpr, Var\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, FuncItem) 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):\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):\n        ret_type = fn_type.ret_type  # same kind of hack as above\n\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    ret = ctx.api.named_generic_type(PARTIAL, [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 typing 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        ):\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/re.py",
    "content": "\"\"\"Plugin to provide accurate types for regex patterns.\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom functools import lru_cache\nfrom typing import Optional, cast\n\nfrom mypy import errorcodes\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import CallExpr, Context, Expression, OpExpr, RefExpr\nfrom mypy.plugin import FunctionContext, FunctionSigContext, MethodContext, MethodSigContext\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    NoneType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    UnionType,\n    get_proper_type,\n)\n\nGroups = tuple[tuple[Optional[str], bool], ...]\n\n\ndef match(ctx: FunctionContext | MethodContext) -> Type:\n    \"\"\"re.{match,fullmatch,search,finditer}, re.Pattern.{match,fullmatch,search,finditer}\"\"\"\n    default = cast(\"UnionType | Instance\", ctx.default_return_type)\n    if isinstance(ctx, FunctionContext):\n        value = _get_first_str_arg(ctx.arg_types[0][0])\n        if value is None:\n            return default\n        verbose = is_verbose(ctx)\n        if verbose is None:\n            return default\n        groups = parse_groups(value, ctx.args[0][0], ctx.api.msg, verbose=verbose)\n        if groups is None:\n            return AnyType(TypeOfAny.from_error)\n    else:\n        assert isinstance(ctx.type, Instance)\n        groups = get_groups(ctx.type)\n        if groups is None:\n            return default\n    instance = default.items[0] if isinstance(default, UnionType) else default.args[0]\n    # type ignore because this implementation is closely tied to the stubs and will never see a type alias\n    assert isinstance(instance, Instance)  # type: ignore[misc]\n    instance = instance.copy_modified()\n    instance.metadata[\"groups\"] = groups\n    return (\n        UnionType([instance, NoneType()])\n        if isinstance(default, UnionType)\n        else default.copy_modified(args=[instance])\n    )\n\n\ndef match_groups(ctx: MethodContext) -> Type:\n    default = ctx.default_return_type\n    if not isinstance(ctx.type, Instance):\n        return default\n    proper_default = get_proper_type(default)\n    if isinstance(proper_default, TupleType):\n        anystr_none = proper_default.items[0]\n        fallback = proper_default.partial_fallback\n    elif isinstance(proper_default, Instance):\n        anystr_none = proper_default.args[0]\n        fallback = proper_default\n    else:\n        return default\n    if isinstance(anystr_none, UnionType):  # type: ignore[misc]\n        anystr = anystr_none.items[0]\n    else:\n        anystr = anystr_none\n\n    groups = get_groups(ctx.type)\n    if groups is None:\n        return default\n    return TupleType([anystr if group[1] == 1 else anystr_none for group in groups], fallback)\n\n\ndef match_group(ctx: MethodContext) -> Type:\n    default = ctx.default_return_type\n    if not isinstance(ctx.type, Instance):\n        return default\n    if not ctx.args[0]:\n        return default\n    value = _get_first_arg(ctx.arg_types[0][0])\n    groups = get_groups(ctx.type)\n    if groups is None:\n        return default\n    return _group(value, groups, ctx)\n\n\ndef _group(value: object, groups: Groups, ctx: MethodContext) -> Type:\n    assert isinstance(ctx.type, Instance)\n    if isinstance(value, int):\n        if value > len(groups):\n            ctx.api.msg.fail(f\"No such group: {value}\", ctx.context, code=errorcodes.REGEX)\n            return AnyType(TypeOfAny.from_error)\n        if value == 0 or groups[value - 1][1] == 1:\n            assert isinstance(ctx.type, Instance)\n            return ctx.type.args[0]\n    elif isinstance(value, str):\n        for group in groups:\n            if value == group[0]:\n                if group[1] == 1:\n                    return ctx.type.args[0]\n                return ctx.default_return_type\n        ctx.api.msg.fail(f\"No such group: '{value}'\", ctx.context, code=errorcodes.REGEX)\n\n        return AnyType(TypeOfAny.from_error)\n    return ctx.default_return_type\n\n\ndef compile(ctx: FunctionContext) -> Type:\n    \"\"\"re.compile, re.template\"\"\"\n    default = ctx.default_return_type\n    if not ctx.arg_types[0]:\n        return default\n    value = _get_first_str_arg(ctx.arg_types[0][0])\n    if value is None:\n        return default\n    verbose = is_verbose(ctx)\n    if verbose is None:\n        return default\n    groups = parse_groups(value, ctx.args[0][0], ctx.api.msg, verbose=verbose)\n    if groups is None:\n        return AnyType(TypeOfAny.from_error)\n    assert isinstance(default, Instance)  # type: ignore[misc]\n    default.metadata[\"groups\"] = groups\n    return default\n\n\ndef split(ctx: FunctionContext | MethodContext) -> Type:\n    default = cast(Instance, ctx.default_return_type)\n    if isinstance(ctx, FunctionContext):\n        value = _get_first_str_arg(ctx.arg_types[0][0])\n        if value is None:\n            return default\n        verbose = is_verbose(ctx)\n        if verbose is None:\n            return default\n        groups = parse_groups(value, ctx.args[0][0], ctx.api.msg, verbose=verbose)\n        if groups is None:\n            return AnyType(TypeOfAny.from_error)\n    else:\n        if not isinstance(ctx.type, Instance):\n            return default\n        groups = get_groups(ctx.type)\n    if groups is None:\n        return default\n    if all(group for _, group in groups):\n        # all groups are non-optional\n        arg = default.args[0]\n        assert isinstance(arg, UnionType)  # type: ignore[misc]\n        return default.copy_modified(args=[arg.items[0]])\n    return default\n\n\ndef findall(ctx: FunctionContext | MethodContext) -> Type:\n    default = cast(Instance, ctx.default_return_type)\n    if isinstance(ctx, FunctionContext):\n        value = _get_first_str_arg(ctx.arg_types[0][0])\n        if value is None:\n            return default\n        verbose = is_verbose(ctx)\n        if verbose is None:\n            return default\n        groups = parse_groups(value, ctx.args[0][0], ctx.api.msg, verbose=verbose)\n        if groups is None:\n            return AnyType(TypeOfAny.from_error)\n    else:\n        groups = get_groups(cast(Instance, ctx.type))\n        if groups is None:\n            return default\n    l = len(groups)\n    arg = default.args[0]\n    assert isinstance(arg, UnionType)  # type: ignore[misc]\n    any_str = arg.items[0]\n    if l <= 1:\n        return ctx.api.named_generic_type(\"builtins.list\", [any_str])\n    return ctx.api.named_generic_type(\n        \"builtins.list\",\n        [TupleType([any_str] * l, ctx.api.named_generic_type(\"builtins.tuple\", [any_str]))],\n    )\n\n\ndef sub(ctx: FunctionSigContext | MethodSigContext) -> CallableType:\n    default = ctx.default_signature\n    args = default.arg_types.copy()\n\n    if isinstance(ctx, FunctionSigContext):\n        if not isinstance(ctx.context, CallExpr):\n            return default\n        arg_one = ctx.context.args[0]\n        typ = ctx.api.get_expression_type(arg_one)\n        value = _get_first_str_arg(typ)\n        if value is None:\n            return default\n        verbose = is_verbose(ctx)\n        if verbose is None:\n            return default\n        groups = parse_groups(value, ctx.context, ctx.api.msg, verbose=verbose)\n        repl_index = 1\n    else:\n        groups = get_groups(cast(Instance, ctx.type))\n        repl_index = 0\n    if groups is None:\n        return default\n    repl = args[repl_index]\n    assert isinstance(repl, UnionType)  # type: ignore[misc]\n    call = repl.items[1]\n    assert isinstance(call, CallableType)  # type: ignore[misc]\n    arg = call.arg_types[0]\n    assert isinstance(arg, Instance)  # type: ignore[misc]\n    grouped = arg.copy_modified()\n    grouped.metadata[\"groups\"] = groups\n    call = call.copy_modified(arg_types=[grouped])\n    items = repl.items.copy()\n    items[1] = call\n    repl = UnionType(items)\n    args[repl_index] = repl\n    return default.copy_modified(arg_types=args)\n\n\ndef _get_first_arg(arg: Type) -> str | int | None:\n    arg = get_proper_type(arg)\n    if isinstance(arg, LiteralType):\n        result = arg.value\n        if not isinstance(result, (str, int)):\n            return None\n        return result\n    elif (\n        isinstance(arg, Instance)\n        and arg.last_known_value\n        and isinstance(arg.last_known_value.value, (str, int))\n    ):\n        return arg.last_known_value.value\n    return None\n\n\ndef _get_first_str_arg(arg: Type) -> str | None:\n    result = _get_first_arg(arg)\n    assert not isinstance(result, int)\n    return result\n\n\ndef match_groupdict(ctx: MethodContext) -> Type:\n    default = ctx.default_return_type\n    if not isinstance(ctx.type, Instance):\n        return default\n    groups = get_groups(ctx.type)\n    if groups is None:\n        return default\n\n    assert isinstance(default, Instance)  # type: ignore[misc]\n    anystr_default = default.args[1]\n    anystr = ctx.type.args[0]\n    groups_keys = {key for key, _ in groups if key}\n\n    def t(name: str) -> Instance | None:\n        try:\n            return ctx.api.named_generic_type(name, [])\n        except KeyError:\n            return None\n\n    fallback = (\n        t(\"typing._TypedDict\")\n        or t(\"typing_extensions._TypedDict\")\n        or t(\"mypy_extensions._TypedDict\")\n    )\n    assert fallback is not None\n    return TypedDictType(\n        items={name: anystr if group else anystr_default for name, group in groups if name},\n        required_keys=groups_keys,\n        readonly_keys=set(),\n        fallback=fallback,\n    )\n\n\ndef is_verbose(\n    ctx: FunctionContext | MethodContext | FunctionSigContext | MethodSigContext,\n) -> bool | None:\n    call = ctx.context\n    assert isinstance(call, CallExpr)\n    if isinstance(ctx, (FunctionContext, MethodContext)):\n        sig_names = ctx.callee_arg_names\n    else:\n        sig_names = ctx.default_signature.arg_names\n    if \"flags\" in call.arg_names:\n        supplied_flag = call.args[call.arg_names.index(\"flags\")]\n    else:\n        flags_index = sig_names.index(\"flags\")\n        if len(call.args) <= flags_index:\n            return False\n        supplied_flag = call.args[flags_index]\n\n    def inner_is_verbose(node: Expression) -> bool | None:\n        \"\"\"None means unsure\"\"\"\n        if isinstance(node, OpExpr):\n            if node.op != \"|\":\n                return None\n            left = inner_is_verbose(node.left)\n            right = inner_is_verbose(node.right)\n            if left is None or right is None:\n                return None\n            return left or right\n        if not isinstance(node, RefExpr):\n            return None\n        if node.fullname in {\"re.X\", \"re.VERBOSE\"}:\n            return True\n        if node.fullname.startswith(\"re.\"):\n            return False\n        return None\n\n    return inner_is_verbose(supplied_flag)\n\n\ndef parse_groups(\n    value: str, context: Context, msg: MessageBuilder, verbose=False\n) -> Groups | None:\n    groups = _parse_groups(value, verbose)\n    if isinstance(groups, Exception):\n        msg.fail(str(groups), context, code=errorcodes.REGEX)\n        return None\n    return groups\n\n\n@lru_cache(None)\ndef _parse_groups(value: str, verbose=False) -> Groups | re.error:\n    \"\"\"The 'most important part' of this feature, we parse the regex pattern to discern which groups are optional.\"\"\"\n    try:\n        p = re.compile(value, flags=re.VERBOSE if verbose else 0)\n    except re.error as e:\n        return e\n\n    groups: list[bool] = []\n    working = []\n    \"\"\"\n    1 = capturing group\n    0 = optional capturing group\n    -1 = non-capturing group\n    -2 = optional non-capturing group\n    \"\"\"\n    depth = 0\n    escape = False\n    union = -1\n    character_set = 0\n    \"\"\"\n    0 = not in a character set\n    1 = `]` is literal in a character set\n    2 = normal character set\n    \"\"\"\n    comment_group = False\n    comment = False\n    backreference = False\n    for i in range(len(value)):\n        if escape:\n            escape = False\n            continue\n        char = value[i]\n        if backreference:\n            if char != \")\":\n                continue\n            else:\n                backreference = False\n                continue\n        if comment_group and char == \")\":\n            comment_group = False\n        if char == \"\\n\" and comment:\n            comment = False\n            continue\n        if char == \"\\\\\":\n            if character_set:\n                character_set = 2\n            escape = True\n            continue\n        if comment_group or comment:\n            continue\n        if char == \"^\" and character_set == 1:\n            continue\n        if char == \"]\" and character_set == 2:\n            character_set = 0\n            continue\n        if character_set:\n            character_set = 2\n            continue\n        if char == \"[\":\n            character_set = 1\n            continue\n        if char == \"|\" and (union > depth or union == -1):\n            union = depth\n            continue\n        if verbose and char == \"#\":\n            comment = True\n            continue\n        if char not in (\"(\", \")\"):\n            continue\n        if char == \"(\":\n            depth += 1\n            if value[i + 1] == \"?\":\n                if value[i + 2 : i + 4] == \"P<\":\n                    working.append(1)\n                elif value[i + 2] == \"(\":\n                    backreference = True\n                    working.append(-1)\n                elif value[i + 2] == \"!\":\n                    working.append(-2)\n                elif value[i + 2] == \":\":\n                    working.append(-1)\n                elif value[i + 2] == \"#\":\n                    comment_group = True\n                    continue\n                elif \"x\" in value[i + 2 : value.find(\")\", i)]:\n                    verbose = True\n                    continue\n                else:\n                    working.append(-1)\n            else:\n                working.append(1)\n            continue\n        if char == \")\":\n            depth -= 1\n            if i + 1 < len(value) and value[i + 1] in \"*?\":\n                for d in range(depth, len(working)):\n                    if working[d] == 1:\n                        working[d] = 0\n            if depth == union - 1 or (depth < len(working) and working[depth] < -1):\n                for d in range(depth + 1, len(working)):\n                    if working[d] == 1:\n                        working[d] = 0\n                union = -1\n            if depth == 0:\n                groups.extend(bool(group) for group in working if group > -1)\n                working.clear()\n    if union == 0:\n        for d in range(len(groups)):\n            if groups[d] is True:\n                groups[d] = False\n    assert len(groups) == p.groups, \"parsed groups differ from compiled groups\"\n    mapping = {value: key for key, value in p.groupindex.items()}\n    return tuple((mapping.get(i + 1), group) for i, group in enumerate(groups))\n\n\ndef get_groups(typ: Instance) -> Groups | None:\n    return cast(\"Groups | None\", typ.metadata.get(\"groups\"))\n"
  },
  {
    "path": "mypy/plugins/singledispatch.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Final, NamedTuple, TypeVar, Union\nfrom typing_extensions import TypeAlias as _TypeAlias\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.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\nSINGLEDISPATCH_TYPE: Final = \"functools._SingleDispatchCallable\"\n\nSINGLEDISPATCH_REGISTER_METHOD: Final = f\"{SINGLEDISPATCH_TYPE}.register\"\n\nSINGLEDISPATCH_CALLABLE_CALL_METHOD: Final = f\"{SINGLEDISPATCH_TYPE}.__call__\"\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\nREGISTER_RETURN_CLASS: Final = \"_SingleDispatchRegisterCallable\"\n\nREGISTER_CALLABLE_CALL_METHOD: Final = f\"functools.{REGISTER_RETURN_CLASS}.__call__\"\n\n\ndef make_fake_register_class_instance(\n    api: CheckerPluginInterface, type_args: Sequence[Type]\n) -> Instance:\n    defn = ClassDef(REGISTER_RETURN_CLASS, Block([]))\n    defn.fullname = f\"functools.{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 = Union[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\nfrom typing import cast\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        cast(str, 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    OverloadedFuncDef,\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            if result == MYPY_FALSE:\n                s.is_mypy_only = 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                s.is_mypy_only = 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_FALSE, MYPY_TRUE) and guard_value in (\n            ALWAYS_TRUE,\n            MYPY_TRUE,\n        ):\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    pyversion = options.python_version\n    name = \"\"\n    negated = False\n    alias = expr\n    if isinstance(alias, UnaryExpr):\n        if alias.op == \"not\":\n            expr = alias.expr\n            negated = True\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) and expr.op in (\"and\", \"or\"):\n        left = infer_condition_value(expr.left, options)\n        if (left in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == \"and\") or (\n            left in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == \"or\"\n        ):\n            # Either `True and <other>` or `False or <other>`: the result will\n            # always be the right-hand-side.\n            return infer_condition_value(expr.right, options)\n        else:\n            # The result will always be the left-hand-side (e.g. ALWAYS_* or\n            # TRUTH_VALUE_UNKNOWN).\n            return left\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 in {\"BASEDMYPY_TYPE_CHECKING\", \"MYPY\", \"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    if negated:\n        result = inverted_truth_mapping[result]\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 == 'posix'\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\n    def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:\n        o.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            super().visit_try_stmt(stmt)\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 time\nimport tokenize\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Iterator\nfrom typing import Any, Callable, Final\nfrom typing_extensions import 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.util import attrgetter\nfrom mypy.version import __based_version__\n\ntry:\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    try:\n        with tokenize.open(path) as input_file:\n            yield from enumerate(input_file, 1)\n    except IsADirectoryError:\n        # can happen with namespace packages\n        pass\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        try:\n            with open(tree.path, \"rb\") as f:\n                physical_lines = len(f.readlines())\n        except IsADirectoryError:\n            # can happen with namespace packages\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        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(\n            \"coverage\", timestamp=str(int(time.time())), version=__based_version__\n        )\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 Optional\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nfrom mypy.nodes import FuncBase, TypeInfo\n\nSavedScope: _TypeAlias = tuple[str, Optional[TypeInfo], Optional[FuncBase]]\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\nfrom collections import defaultdict\nfrom collections.abc import Collection, Iterable, Iterator\nfrom contextlib import contextmanager, nullcontext\nfrom typing import Any, Callable, Final, TypeVar, cast\nfrom typing_extensions import TypeAlias as _TypeAlias, TypeGuard\n\nimport mypy.state\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_STAR,\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    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    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\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    ForStmt,\n    FuncBase,\n    FuncDef,\n    FuncItem,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportBase,\n    ImportFrom,\n    IndexExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    Lvalue,\n    MatchStmt,\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    StarExpr,\n    Statement,\n    StrExpr,\n    SuperExpr,\n    SymbolNode,\n    SymbolTable,\n    SymbolTableNode,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\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    get_nongen_builtins,\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 Options\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    SequencePattern,\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.subtypes import is_subtype\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    detect_diverging_alias,\n    find_self_type,\n    fix_instance,\n    has_any_from_unimported_type,\n    no_subscript_builtin_alias,\n    type_constructors,\n    validate_instance,\n)\nfrom mypy.typeops import (\n    callable_type,\n    function_type,\n    get_type_vars,\n    try_getting_str_literals_from_type,\n)\nfrom mypy.types import (\n    ASSERT_TYPE_NAMES,\n    DATACLASS_TRANSFORM_NAMES,\n    DEPRECATED_TYPE_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_VAR_LIKE_NAMES,\n    TYPED_NAMEDTUPLE_NAMES,\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PlaceholderType,\n    ProperType,\n    RawExpressionType,\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    UnionType,\n    UnpackType,\n    UntypedType,\n    get_proper_type,\n    get_proper_types,\n    has_type_vars,\n    is_named_instance,\n    is_unannotated_any,\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, fill_typevars_with_any\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\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\nclass SemanticAnalyzer(\n    NodeVisitor[None], SemanticAnalyzerInterface, SemanticAnalyzerPluginInterface\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: set[str],\n        incomplete_namespaces: set[str],\n        errors: Errors,\n        plugin: Plugin,\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.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        # Map from module id to list of explicitly exported names (i.e. names in __all__).\n        self.export_map: dict[str, list[str]] = {}\n        self.plugin = plugin\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        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    # 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        # For cringe reasons, we import 'typing.Callable' as soon at it is loaded\n        from mypy import typeanal\n\n        if node.fullname == \"typing\" and not typeanal.CALLABLE_TYPE and not self.deferred:\n            typeanal.CALLABLE_TYPE = self.named_type(typeanal.CALLABLE_NAME)\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        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.export_map[self.cur_mod_id] = self.all_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 self.final_iteration:\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                    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        infer_fdef_types_from_defaults(defn, self)\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 defn.fullname == \"typing.type_check_only\":\n            defn.is_type_check_only = True\n\n        if not self.recurse_into_functions:\n            return\n\n        with self.scope.function_scope(defn):\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.name in (\"__init__\", \"__init_subclass__\"):\n                if defn.type:\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                elif self.options.infer_function_types:\n                    defn.type = CallableType(\n                        [UntypedType() for _ in defn.arg_kinds],\n                        defn.arg_kinds,\n                        defn.arg_names,\n                        NoneType(),\n                        self.named_type(\"builtins.function\"),\n                        definition=defn,\n                        implicit=True,\n                    )\n            if defn.name == \"__new__\" and self.options.infer_function_types:\n                if defn.type:\n                    assert isinstance(defn.type, CallableType)\n                    if isinstance(get_proper_type(defn.type.ret_type), (AnyType, NoneType)):\n                        self_type = fill_typevars_with_any(defn.info)\n                        defn.type = defn.type.copy_modified(ret_type=self_type)\n                elif self.options.infer_function_types:\n                    self_type = fill_typevars_with_any(defn.info)\n                    defn.type = CallableType(\n                        [UntypedType() for _ in defn.arg_kinds],\n                        defn.arg_kinds,\n                        defn.arg_names,\n                        self_type,\n                        self.named_type(\"builtins.function\"),\n                        definition=defn,\n                        implicit=True,\n                    )\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                analyzer.always_allow_new_syntax = (\n                    analyzer.always_allow_new_syntax or defn.is_mypy_only\n                )\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                    if result.type_guard:\n                        original_target = result.type_guard.target\n                        if (\n                            result.type_guard.target != \"first argument\"\n                            and result.type_guard.target not in result.arg_names\n                        ):\n                            args = [arg.variable.name for arg in defn.arguments]\n                            if result.type_guard.target in args:\n                                result.type_guard.target = args.index(result.type_guard.target)  # type: ignore[arg-type]\n                            else:\n                                self.fail(\n                                    f'Cannot find parameter \"{result.type_guard.target}\"',\n                                    result,\n                                    code=codes.NAME_DEFINED,\n                                )\n                                result = result.copy_modified(type_guard=None)\n\n                    skip_self = self.is_class_scope() and not defn.is_static\n                    if result.type_guard:\n                        if result.type_guard.target == \"first argument\":\n                            if (\n                                len(result.arg_names) > skip_self\n                                and result.arg_kinds[skip_self].is_positional()\n                            ):\n                                result.type_guard.target = result.arg_names[skip_self] or skip_self\n                            else:\n                                self.fail(\n                                    \"TypeGuard functions must have a positional argument\",\n                                    result,\n                                    code=codes.VALID_TYPE,\n                                )\n                                if skip_self:\n                                    self.note(\n                                        f'If you want to type-guard the implicit argument, use \"-> {defn.arguments[0].variable.name} is {result.type_guard.type_guard}\" instead.',\n                                        result,\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_guard:\n                        if defn.info and original_target == defn.arguments[0].variable.name:\n                            if defn.is_class:\n                                result.type_guard.target = f\"class@{result.type_guard.target}\"\n                            elif self.is_class_scope():\n                                result.type_guard.target = f\"self@{result.type_guard.target}\"\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                    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] + list(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        last_type = get_proper_type(last_type.type)\n        if not isinstance(last_type, TypedDictType):\n            self.fail(\"Unpack item in ** argument 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(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 overlap])\n            self.fail(f\"Overlap between argument names and ** TypedDict items: {overlapped}\", defn)\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] + [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 not func.is_static or func.name == \"__new__\":\n            if func.name in [\"__init_subclass__\", \"__class_getitem__\"]:\n                func.is_class = True\n            if not func.arguments:\n                self.fail(\n                    'Method must have at least one argument. Did you forget the \"self\" argument?',\n                    func,\n                )\n            elif 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                        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 (\n                    sym is not None\n                    and (\n                        sym.fullname == \"typing.Type\"\n                        or (\n                            sym.fullname == \"builtins.type\"\n                            and (\n                                self.is_stub_file\n                                or self.is_future_flag_set(\"annotations\")\n                                or self.options.python_version >= (3, 9)\n                            )\n                        )\n                    )\n                    and typ.args\n                ):\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        if self.is_stub_file:\n            defn.is_mypy_only = True\n        if not self.recurse_into_functions:\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):\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        if isinstance(first_item, Decorator) and first_item.func.is_property:\n            # This is a property.\n            first_item.func.is_overload = True\n            self.analyze_property_with_multi_part_definition(defn)\n            typ = function_type(first_item.func, self.named_type(\"builtins.function\"))\n            assert isinstance(typ, CallableType)\n            types = [typ]\n        else:\n            # This is an 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            isinstance(it, Decorator) and len(it.decorators) > 1\n            for it in 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\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} \"\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.named_type(\"builtins.function\"))\n                assert isinstance(callable, CallableType)\n                # overloads ignore the rule regarding default return and untyped defs\n                if item.type is None and self.options.default_return:\n                    if is_unannotated_any(callable.ret_type):\n                        callable.ret_type = NoneType()\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        if self.options.infer_function_types and impl and not non_overload_indexes:\n            self.infer_impl_from_parts(\n                impl, types, self.named_type(\"builtins.function\"), self.named_type\n            )\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 and not defn.is_mypy_only:\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            else:\n\n                # TODO: also allow omitting an implementation for abstract methods in ABCs?\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(self, defn: OverloadedFuncDef) -> 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        \"\"\"\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        for i, item in enumerate(items[1:]):\n            if isinstance(item, Decorator):\n                if len(item.decorators) >= 1:\n                    first_node = item.decorators[0]\n                    if isinstance(first_node, MemberExpr):\n                        none_func = callable_type(\n                            item.func, self.named_type(\"builtins.function\"), NoneType()\n                        )\n                        none_func.implicit = False\n                        untyped_func = callable_type(\n                            item.func,\n                            self.named_type(\"builtins.function\"),\n                            UntypedType(TypeOfAny.explicit),\n                        )\n                        if first_node.name == \"setter\":\n                            # The first item represents the entire property.\n                            first_item.var.is_settable_property = True\n                            # Get abstractness from the original definition.\n                            item.func.abstract_status = first_item.func.abstract_status\n                            # infer types from the getter\n                            if isinstance(first_item.func.type, CallableType):\n                                if not item.func.type:\n                                    item.func.type = none_func\n                                    if len(item.func.type.arg_types) == 2:\n                                        item.func.type.arg_types[1] = first_item.func.type.ret_type\n                                elif isinstance(item.func.type, CallableType):\n                                    if len(item.func.type.arg_types) == 2 and is_unannotated_any(\n                                        item.func.type.arg_types[1]\n                                    ):\n                                        item.func.type.arg_types[1] = first_item.func.type.ret_type\n                                    if is_unannotated_any(item.func.type.ret_type):\n                                        item.func.type.ret_type = NoneType()\n                            else:\n                                # set some boring defaults\n                                if not item.func.type:\n                                    item.func.type = untyped_func\n                                    item.func.type.arg_types[1] = UntypedType(TypeOfAny.explicit)\n                                    item.func.type.implicit = True\n                                elif isinstance(item.func.type, CallableType):\n                                    if len(item.func.type.arg_types) == 2 and is_unannotated_any(\n                                        item.func.type.arg_types[1]\n                                    ):\n                                        item.func.type.arg_types[1] = NoneType()\n                                    if is_unannotated_any(item.func.type.ret_type):\n                                        item.func.type.ret_type = NoneType()\n                        if first_node.name == \"deleter\":\n                            item.func.abstract_status = first_item.func.abstract_status\n                            # infer types from the getter\n                            if first_item.func.type:\n                                if not item.type:\n                                    item.func.type = none_func\n                            else:\n                                if not item.func.type:\n                                    item.func.type = untyped_func\n                                    item.func.type.implicit = True\n                        for other_node in item.decorators[1:]:\n                            other_node.accept(self)\n                    else:\n                        self.fail(\n                            f\"Only supported top decorator is @{first_item.func.name}.setter\", item\n                        )\n                item.func.accept(self)\n            else:\n                self.fail(f'Unexpected definition for property \"{first_item.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\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 (not defn.is_static or defn.name == \"__new__\") 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 not no_type_check and self.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        for name, tv in tvs:\n            if self.is_defined_type_param(name):\n                self.fail(f'\"{name}\" already defined as a type parameter', context)\n            else:\n                self.add_symbol(name, tv, context, no_progress=True, type_param=True)\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, 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        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                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)\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, defn.name)\n        return base_type_exprs, tvar_defs, is_protocol\n\n    def analyze_class_typevar_declaration(self, base: Type) -> 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            have_type_var_tuple = False\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 have_type_var_tuple:\n                            self.fail(\"Can only use one type var tuple in a class def\", base)\n                            continue\n                        have_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 (\"typing.Unpack\", \"typing_extensions.Unpack\"):\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, scopename: str | None = None\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            tvar_def = self.tvar_scope.bind_new(name, tvar_expr, scopename)\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 = []\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            base_tvars = self.find_type_var_likes(base)\n            tvars.extend(base_tvars)\n        tvars = remove_dups(tvars)  # Variables are defined in order of textual appearance.\n        tvar_defs = []\n        for name, tvar_expr in tvars:\n            tvar_def = self.tvar_scope.bind_new(name, tvar_expr)\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, code=codes.SUBCLASS_ANY)\n                info.fallback_to_any = True\n            elif isinstance(base, TypedDictType):\n                base_types.append(base.fallback)\n            elif isinstance(base, CallableType) and base.is_callable:\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 info.special_alias and has_placeholder(info.special_alias.target):\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)\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(f'Dynamic metaclass not supported for \"{name}\"', metaclass_expr)\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                    )\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(f'Invalid metaclass \"{metaclass_name}\"', metaclass_expr)\n                return None, False, False\n            if not metaclass_info.is_metaclass():\n                self.fail(\n                    'Metaclasses not inheriting from \"type\" are not supported', metaclass_expr\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__\" and module_id in self.export_map:\n                    self.all_exports[:] = self.export_map[module_id]\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            # we recheck if it's a stub manually to avoid TYPE_CHECKING blocks\n            is_stub_file = self.cur_mod_node.path.lower().endswith(\".pyi\")\n            use_implicit_reexport = not 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 not self.is_stub_file and (\n            isinstance(node.node, (TypeInfo, FuncDef))\n            and node.node.is_type_check_only\n            or isinstance(node.node, Decorator)\n            and node.node.func.is_type_check_only\n        ):\n            self.fail(message_registry.TYPE_CHECK_ONLY.format(node.node.name), context)\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            else:\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://kotlinisland.github.io/basedmypy/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                fullname = i_id + \".\" + name\n                self.set_future_import_flags(fullname)\n                if node is None:\n                    continue\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\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.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            # Already analyzed enum -- nothing to do here.\n            return True\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                return True  # This is a valid and analyzed named tuple definition, nothing to do here.\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 a valid and analyzed typed dict definition, nothing to do here.\n                return True\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 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 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                        top_function = self.function_stack[-1]\n                        if (\n                            top_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(\n                s.type,\n                allow_tuple_literal=allow_tuple_literal,\n                runtime=False if self.is_func_scope() else None,\n            )\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(\n        self, rvalue: Expression, is_final: bool, do_inner=False\n    ) -> 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 and not do_inner:\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], list[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\n        qualified type variable names for generic aliases, a set of names the alias depends on,\n        and a list of type variables if the alias is generic.\n        A schematic 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,\n                self.options,\n                self.is_stub_file or python_3_12_type_alias,\n                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        tvar_defs: list[TypeVarLikeType] = []\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        qualified_tvars = [node.fullname for _name, node in alias_type_vars]\n        empty_tuple_index = typ.empty_tuple_index if isinstance(typ, UnboundType) else False\n        return analyzed, new_tvar_defs, depends_on, qualified_tvars, empty_tuple_index\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 = s.rvalue.args[1]\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            qualified_tvars: list[str] = []\n            empty_tuple_index = False\n        else:\n            tag = self.track_incomplete_refs()\n            res, alias_tvars, depends_on, qualified_tvars, empty_tuple_index = 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        # In addition to the aliases used, we add deps on unbound\n        # type variables, since they are erased from target type.\n        self.add_type_alias_deps(qualified_tvars)\n        # The above are only direct deps on other aliases.\n        # For subscripted aliases, type deps from expansion are added in deps.py\n        # (because the type is stored).\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 res.args\n            and not empty_tuple_index\n            and not pep_695\n            and not pep_613\n        )\n        if isinstance(res, ProperType) and isinstance(res, Instance):\n            if not validate_instance(res, self.fail, empty_tuple_index):\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            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) != 2:\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 (\"typing.Unpack\", \"typing_extensions.Unpack\"):\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 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) == \"_\":\n                        # Special case for assignment to local named '_': always infer 'Any'.\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    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        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 constraints\", 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 constraints and an upper bound\", context)\n                    return None\n                tv_arg = self.get_typevarlike_argument(\n                    \"TypeVar\", param_name, param_value, context, allow_unbound_tvars=True\n                )\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 or contravariant) and has_values:\n            self.fail(\n                \"TypeVar with constraints cannot have variance\", context, code=codes.VALID_TYPE\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            elif isinstance(typ, LiteralType) and typ.bare_literal:\n                msg = message_registry.INVALID_BARE_LITERAL.format(typ.value_repr())\n                self.fail(msg.value, param_value, code=msg.code)\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        self.check_typevarlike_name(call, lvalue.name, s)\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        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 analyzed is not None and set(get_type_vars(analyzed)) & set(\n                self.type.defn.type_vars\n            ):\n                # This means that we have a type var defined inside of a ClassVar.\n                # This is not allowed by PEP526.\n                # See https://github.com/python/mypy/issues/11538\n\n                self.fail(message_registry.CLASS_VAR_WITH_TYPEVARS, s)\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\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        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\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        is_stub_file = self.is_stub_file\n        if s.is_mypy_only:\n            self._is_stub_file = True\n        for i in range(len(s.expr)):\n            s.expr[i].accept(self)\n            self.visit_block(s.body[i])\n        if s.is_mypy_only is False:\n            self._is_stub_file = True\n        else:\n            self._is_stub_file = is_stub_file\n        self.visit_block_maybe(s.else_body)\n        self._is_stub_file = is_stub_file\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, qualified_tvars, empty_tuple_index = 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            self.add_type_alias_deps(depends_on)\n            # In addition to the aliases used, we add deps on unbound\n            # type variables, since they are erased from target type.\n            self.add_type_alias_deps(qualified_tvars)\n            # The above are only direct deps on other aliases.\n            # For subscripted aliases, type deps from expansion are added in deps.py\n            # (because the type is stored).\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) and not res.args:\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                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            rvalue = s.value.expr()\n            if isinstance(rvalue, (IndexExpr, CallExpr, OpExpr)):\n                # Note: CallExpr is for \"void = type(None)\" and OpExpr is for \"X | Y\" union syntax.\n                if not isinstance(rvalue.analyzed, TypeAliasExpr):\n                    rvalue.analyzed = TypeAliasExpr(alias_node)\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 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                        updated = True\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    #\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_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, FuncBase)\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\"):\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(expr.callee, \"typing.TypeVar\"):\n            for a, a_name in zip(expr.args, expr.arg_names):\n                # fmt: off\n                #  in 3.8, ast bug or something\n                with \\\n                    self.allow_unbound_tvars_set() \\\n                    if a_name in (\"bound\", \"default\") \\\n                    else nullcontext() \\\n                :\n                # fmt: on\n                    a.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        else:\n            # Normal call expression.\n            for a in expr.args:\n                a.accept(self)\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                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 not func_def.is_static and isinstance(func_def.type, CallableType):\n                    formal_arg = func_def.type.argument_by_name(base.node.name)\n                    if formal_arg and formal_arg.pos == 0:\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                    if not n:\n                        return\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        # Types list, dict, set are not subscriptable, prohibit this if\n        # subscripted either via type alias...\n        if isinstance(base, RefExpr) and isinstance(base.node, TypeAlias):\n            alias = base.node\n            target = get_proper_type(alias.target)\n            if isinstance(target, Instance):\n                name = target.type.fullname\n                if (\n                    alias.no_args\n                    and name  # this avoids bogus errors for already reported aliases\n                    in get_nongen_builtins(self.options.python_version)\n                    and not self.is_stub_file\n                    and not alias.normalized\n                ):\n                    self.fail(no_subscript_builtin_alias(name, propose_alt=False), expr)\n        # ...or directly.\n        else:\n            n = self.lookup_type_node(base)\n            if (\n                n\n                and n.fullname in get_nongen_builtins(self.options.python_version)\n                and not self.is_stub_file\n            ):\n                self.fail(no_subscript_builtin_alias(n.fullname, propose_alt=False), expr)\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            if base.node.fullname == \"typing.Callable\":\n                allow_unpack = True\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 [...]\", item)\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                runtime=True,\n            )\n            if analyzed is None:\n                return None\n            types.append(analyzed)\n\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, runtime=not isinstance(expr.type, RawExpressionType))\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 not self.is_func_scope() or not self.function_stack[-1].is_coroutine:\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 not self.is_func_scope() or not self.function_stack[-1].is_coroutine:\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 not self.is_func_scope() or not self.function_stack[-1].is_coroutine:\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        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        \"\"\"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            return SymbolTableNode(MDEF, Var(name, self.str_type()))\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        return (\n            node is None\n            or self.is_textually_before_statement(node)\n            or not self.is_defined_in_current_module(node.fullname)\n            or isinstance(node, (TypeInfo, TypeAlias))\n            or (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_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        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:\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_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        return self.named_type(\"builtins.object\")\n\n    def str_type(self) -> Instance:\n        return self.named_type(\"builtins.str\")\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)\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, [UntypedType()] * 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        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 not (isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new)):\n                    self.name_already_defined(name, context, existing)\n        elif name not in self.missing_names[-1] and \"*\" not in self.missing_names[-1]:\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 = cast(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(ctx.line, ctx.column, msg, blocker=blocker, code=code)\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        runtime: bool | None = None,\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        if not a.api.is_stub_file and runtime:\n            a.always_allow_new_syntax = False\n        if runtime is False:\n            a.always_allow_new_syntax = True\n        if self.is_stub_file:\n            a.always_allow_new_syntax = True\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            # A basic optimization to avoid adding targets with no dependencies to\n            # the `alias_deps` dict.\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    def infer_impl_from_parts(\n        self,\n        impl: OverloadPart,\n        types: list[CallableType],\n        fallback: Instance,\n        named_type: Callable[[str, list[Type]], Type],\n    ):\n        impl_func = impl if isinstance(impl, FuncDef) else impl.func\n        # infer the types of the impl from the overload types\n        arg_types: dict[str | int, dict[Type, None]] = defaultdict(dict)\n        ret_types: dict[Type, None] = {}\n        for tp in types:\n            for i, arg_type in enumerate(tp.arg_types):\n                arg_name = tp.arg_names[i]\n                if not arg_name:  # if it's positional only\n                    arg_types[i][arg_type] = None\n                else:\n                    if arg_name in impl_func.arg_names:\n                        if arg_type not in arg_types[arg_name]:\n                            arg_types[arg_name][arg_type] = None\n                    if arg_name and arg_name in impl_func.arg_names:\n                        if arg_type not in arg_types[arg_name]:\n                            arg_types[arg_name][arg_type] = None\n            t = get_proper_type(tp.ret_type)\n            if isinstance(t, Instance) and t.type.fullname == \"typing.Coroutine\":\n                ret_type = t.args[2]\n            else:\n                ret_type = tp.ret_type\n            ret_types[ret_type] = None\n\n        res_arg_types = [\n            (\n                UnionType.make_union(\n                    tuple({**(arg_types[arg_name_] if arg_name_ else {}), **arg_types[i]})\n                )\n                if arg_kind not in (ARG_STAR, ARG_STAR2)\n                else UntypedType()\n            )\n            for i, (arg_name_, arg_kind) in enumerate(\n                zip(impl_func.arg_names, impl_func.arg_kinds)\n            )\n        ]\n\n        if isinstance(impl, Decorator):\n            impl = impl.func\n        for i, arg in enumerate(impl.arguments):\n            init = arg.initializer\n            if not arg.initializer:\n                continue\n            typ: Type | None\n            if isinstance(init, NameExpr) and init.fullname == \"builtins.None\":\n                typ = NoneType()\n            else:\n                typ = self.analyze_simple_literal_type(arg.initializer, True, do_inner=True)\n                if not typ:\n                    continue\n            with mypy.state.state.strict_optional_set(self.options.strict_optional):\n                if not is_subtype(typ, res_arg_types[i], options=self.options):\n                    res_arg_types[i] = UnionType.make_union((res_arg_types[i], typ))\n\n        ret_type = UnionType.make_union(tuple(ret_types))\n\n        if impl_func.is_coroutine:\n            # if the impl is a coroutine, then assume the parts are also, if not need annotation\n            any_type = AnyType(TypeOfAny.special_form)\n            ret_type = named_type(\"typing.Coroutine\", [any_type, any_type, ret_type])\n\n        # use unanalyzed_type because we would have already tried to infer from defaults\n        if impl_func.unanalyzed_type:\n            assert isinstance(impl_func.unanalyzed_type, CallableType)\n            assert isinstance(impl_func.type, CallableType)\n            impl_func.type = impl_func.type.copy_modified(\n                arg_types=[\n                    i if not is_unannotated_any(u) else r\n                    for i, u, r in zip(\n                        impl_func.type.arg_types,\n                        impl_func.unanalyzed_type.arg_types,\n                        res_arg_types,\n                    )\n                ],\n                ret_type=(\n                    ret_type\n                    if isinstance(\n                        get_proper_type(impl_func.unanalyzed_type.ret_type), (AnyType, NoneType)\n                    )\n                    else impl_func.type.ret_type\n                ),\n            )\n        else:\n            impl_func.type = CallableType(\n                res_arg_types,\n                impl_func.arg_kinds,\n                impl_func.arg_names,\n                ret_type,\n                fallback,\n                definition=impl_func,\n            )\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):\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 infer_fdef_types_from_defaults(defn: FuncDef | Decorator, self: SemanticAnalyzer):\n    def is_unannotated_any(typ_: Type) -> bool:\n        return isinstance(get_proper_type(typ_), AnyType)\n\n    if isinstance(defn, Decorator):\n        defn = defn.func\n\n    if defn.type and isinstance(defn.type, CallableType) and defn.type.fully_typed:\n        return\n\n    if not defn.type and (\n        self.options.default_return\n        or (self.options.infer_function_types and any(arg.initializer for arg in defn.arguments))\n    ):\n        arg_types = []\n        if self.options.infer_function_types:\n            for arg in defn.arguments:\n                typ = None\n                if arg.variable.is_inferred and arg.initializer:\n                    arg.initializer.accept(self)\n                    typ = self.analyze_simple_literal_type(arg.initializer, False, do_inner=True)\n                elif all(char == \"_\" for char in arg.variable.name):\n                    typ = self.named_type(\"builtins.object\")\n                arg_types.append(typ or UntypedType())\n        ret_type = None\n        if self.options.default_return and self.options.disallow_untyped_defs:\n            ret_type = NoneType()\n        if any(not isinstance(get_proper_type(t), AnyType) for t in arg_types) or ret_type:\n            defn.type = CallableType(\n                arg_types or [UntypedType() for _ in defn.arg_kinds],\n                defn.arg_kinds,\n                defn.arg_names,\n                ret_type or UntypedType(),\n                self.named_type(\"builtins.function\"),\n                definition=defn,\n                line=defn.line,\n                column=defn.column,\n                implicit=not self.options.disallow_untyped_defs,\n            )\n    elif defn.type:\n        assert isinstance(defn.type, CallableType)\n        if (\n            self.options.default_return\n            and is_unannotated_any(defn.type.ret_type)\n            and (\n                isinstance(defn.unanalyzed_type, CallableType)\n                and not self.options.disallow_untyped_defs\n                and any(defn.unanalyzed_type.arg_types)\n                or self.options.disallow_untyped_defs\n            )\n        ):\n            defn.type.ret_type = NoneType()\n        if self.options.infer_function_types:\n            for i, arg in enumerate(defn.arguments):\n                ret = None\n                if is_unannotated_any(defn.type.arg_types[i]):\n                    if arg.variable.is_inferred and arg.initializer:\n                        ret = self.analyze_simple_literal_type(\n                            arg.initializer, False, do_inner=True\n                        )\n                    if ret:\n                        defn.type.arg_types[i] = ret\n                    if all(char == \"_\" for char in arg.variable.name):\n                        defn.type.arg_types[i] = self.named_type(\"builtins.object\")\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"
  },
  {
    "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 and not typ.is_protocol:\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                it = cast(list[StrExpr], seq_items)\n                items = [seq_item.value for seq_item in it]\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    UntypedType,\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        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.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(\"typing.Callable\"))\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 UntypedType()\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 contextlib import nullcontext\nfrom typing import TYPE_CHECKING, Callable, Final, Optional, Union\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nimport mypy.build\nimport mypy.state\nfrom mypy.checker import FineGrainedDeferredNode\nfrom mypy.errors import Errors\nfrom mypy.nodes import Decorator, FuncDef, MypyFile, OverloadedFuncDef, TypeInfo, Var\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\nfrom mypy.server.aststrip import SavedAttributes\nfrom mypy.util import is_typeshed_file\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\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, saved_attrs: SavedAttributes\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    The saved_attrs are implicitly declared instance attributes (attributes\n    defined on self) removed by AST stripper that may need to be reintroduced\n    here.  They must be added before any methods are analyzed.\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    restore_saved_attrs(saved_attrs)\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 restore_saved_attrs(saved_attrs: SavedAttributes) -> None:\n    \"\"\"Restore instance variables removed during AST strip that haven't been added yet.\"\"\"\n    for (cdef, name), sym in saved_attrs.items():\n        info = cdef.info\n        existing = info.get(name)\n        defined_in_this_class = name in info.names\n        assert isinstance(sym.node, Var)\n        # This needs to mimic the logic in SemanticAnalyzer.analyze_member_lvalue()\n        # regarding the existing variable in class body or in a superclass:\n        # If the attribute of self is not defined in superclasses, create a new Var.\n        if (\n            existing is None\n            or\n            # (An abstract Var is considered as not defined.)\n            (isinstance(existing.node, Var) and existing.node.is_abstract_var)\n            or\n            # Also an explicit declaration on self creates a new Var unless\n            # there is already one defined in the class body.\n            sym.node.explicit_self_type\n            and not defined_in_this_class\n        ):\n            info.names[name] = sym\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))\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\n\ndef process_functions(graph: Graph, scc: list[str], patches: Patches) -> None:\n    # Process functions.\n    for module in scc:\n        tree = graph[module].tree\n        assert tree is not None\n        analyzer = graph[module].manager.semantic_analyzer\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 on\n        # Python 3.5, which doesn't preserve dictionary order.\n        targets = sorted(get_all_leaf_targets(tree), key=lambda x: (x[1].line, x[0]))\n        for target, node, active_type in targets:\n            assert isinstance(node, (FuncDef, OverloadedFuncDef, Decorator))\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, Union[MypyFile, FuncDef, OverloadedFuncDef, Decorator], Optional[TypeInfo]\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.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    for dep in analyzer.imports:\n        state.add_dependency(dep)\n        priority = mypy.build.PRI_LOW\n        if priority <= state.priorities.get(dep, priority):\n            state.priorities[dep] = priority\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    analyzer = TypeArgumentAnalyzer(\n        errors,\n        state.options,\n        is_typeshed_file(state.options.abs_custom_typeshed_dir, state.path or \"\"),\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    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    UntypedType,\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(UntypedType())\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 analyzis.\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                it = cast(list[StrExpr], listexpr.items)\n                items = [item.value for item in it]\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 = [UntypedType() 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        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 info.special_alias and has_placeholder(info.special_alias.target):\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                # 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, message_registry\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    LiteralType,\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        \"\"\"Ananlyze 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 and bare literals into None.\n        if isinstance(old_type, AnyType) and old_type.is_from_error:\n            self.fail(msg, context)\n            return None, False\n        elif isinstance(old_type, LiteralType) and old_type.bare_literal:\n            msg_ = message_registry.INVALID_BARE_LITERAL.format(old_type.value_repr())\n            self.fail(msg_.value, context, code=msg_.code)\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                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 typing import Callable, 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    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 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                raise NotImplementedError\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 typing 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 in self.seen_aliases:\n            # Avoid infinite recursion on recursive type aliases.\n            # Note: it is fine to skip the aliases we have already seen in non-recursive\n            # types, since errors there have already been reported.\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            get_proper_type(t).accept(self)\n\n    def visit_tuple_type(self, t: TupleType) -> None:\n        t.items = flatten_nested_tuples(t.items)\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 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 (i, arg), tvar in zip(enumerate(args), type_vars):\n            context = ctx if arg.line < 0 else arg\n            if isinstance(tvar, TypeVarType):\n                if isinstance(arg, ParamSpecType):\n                    is_invalid = True\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),\n                        context,\n                        code=codes.VALID_TYPE,\n                    )\n                    continue\n                if isinstance(arg, Parameters):\n                    is_invalid = True\n                    self.fail(\n                        f\"Cannot use {format_type(arg, self.options)} for regular type variable,\"\n                        \" only for ParamSpec\",\n                        context,\n                        code=codes.VALID_TYPE,\n                    )\n                    continue\n                if tvar.values:\n                    if isinstance(arg, TypeVarType):\n                        if self.in_type_alias_expr:\n                            # Type aliases are allowed to use unconstrained type variables\n                            # error will be checked at substitution point.\n                            continue\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,  # TODO: can we use arg as the 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                    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                    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        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        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                    message = message_registry.INVALID_TYPEVAR_ARG_VALUE.format(name)\n                else:\n                    message = message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(\n                        arg_name, f'\"{name}\"', f'\"{actual.type.name}\"'\n                    )\n                self.fail(\n                    message,\n                    context,  # TODO: can the context be on the arg\n                    code=codes.TYPE_VAR,\n                    notes=[\n                        f'\"{arg_name}\" of \"{name}\" is a constrained type variable, it is not generic'\n                    ],\n                )\n        return is_error\n\n    def fail(\n        self,\n        msg: str,\n        context: Context,\n        *,\n        code: ErrorCode | None = None,\n        notes: list[str] | None = None,\n    ) -> None:\n        self.errors.report(context.line, context.column, msg, code=code, notes=notes)\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    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    UntypedType,\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 isinstance(expr, RefExpr) and self.is_typeddict(expr):\n                assert expr.fullname\n                if expr.fullname not in typeddict_bases_set:\n                    typeddict_bases_set.add(expr.fullname)\n                    typeddict_bases.append(expr)\n                else:\n                    assert isinstance(expr.node, TypeInfo)\n                    self.fail(f'Duplicate base class \"{expr.node.name}\"', defn)\n            elif isinstance(expr, IndexExpr) and self.is_typeddict(expr.base):\n                assert isinstance(expr.base, RefExpr)\n                assert expr.base.fullname\n                if expr.base.fullname not in typeddict_bases_set:\n                    typeddict_bases_set.add(expr.base.fullname)\n                    typeddict_bases.append(expr)\n                else:\n                    assert isinstance(expr.base.node, TypeInfo)\n                    self.fail(f'Duplicate base class \"{expr.base.node.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        base_args: list[Type] = []\n        if isinstance(base, RefExpr):\n            assert isinstance(base.node, TypeInfo)\n            info = base.node\n        elif isinstance(base, IndexExpr):\n            assert isinstance(base.base, RefExpr)\n            assert isinstance(base.base.node, TypeInfo)\n            info = base.base.node\n            args = self.analyze_base_args(base, ctx)\n            if args is None:\n                return\n            base_args = args\n        else:\n            assert isinstance(base, CallExpr)\n            assert isinstance(base.analyzed, TypedDictExpr)\n            info = base.analyzed.info\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 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 = UntypedType()\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, call)\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]], context: Context\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 info.special_alias and has_placeholder(info.special_alias.target):\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 (\n            isinstance(expr, RefExpr)\n            and isinstance(expr.node, TypeInfo)\n            and expr.node.typeddict_type is not None\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 Union\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nfrom mypy.expandtype import expand_type\nfrom mypy.nodes import (\n    UNBOUND_IMPORTED,\n    Decorator,\n    FuncBase,\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    IntersectionType,\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 = Union[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, FuncBase):\n        # TODO: info\n        if node.type:\n            signature = 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 isinstance(node, OverloadedFuncDef) and node.impl:\n            impl = node.impl.func if isinstance(node.impl, Decorator) else node.impl\n        is_trivial_body = impl.is_trivial_body if impl else False\n        dataclass_transform_spec = find_dataclass_transform_spec(node)\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            node.deprecated if isinstance(node, FuncDef) else None,\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        )\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        )\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_intersection_type(self, typ: IntersectionType) -> SnapshotItem:\n        # Sort and remove duplicates so that we can use equality to test for\n        # equivalent intersection type snapshots.\n        items = {snapshot_type(item) for item in typ.items}\n        normalized = tuple(sorted(items))\n        return \"IntersectionType\", 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))\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    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    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    IntersectionType,\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_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, SymbolNode):\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        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            skip_slots: tuple[str, ...] = ()\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                skip_slots = (\"special_alias\",)\n                replace_object_state(new.special_alias, node.special_alias)\n            replace_object_state(new, node, skip_slots=skip_slots)\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\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_intersection_type(self, typ: IntersectionType):\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                # Needed for TypeInfo, see comment in fixup() above.\n                replace_object_state(new, old, skip_slots=(\"special_alias\",))\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"
  },
  {
    "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\nfrom typing_extensions import TypeAlias as _TypeAlias\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    StarExpr,\n    SuperExpr,\n    SymbolTableNode,\n    TupleExpr,\n    TypeInfo,\n    Var,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import CallableType\nfrom mypy.typestate import type_state\n\nSavedAttributes: _TypeAlias = dict[tuple[ClassDef, str], SymbolTableNode]\n\n\ndef strip_target(\n    node: MypyFile | FuncDef | OverloadedFuncDef, saved_attrs: SavedAttributes\n) -> None:\n    \"\"\"Reset a fine-grained incremental target to state before semantic analysis.\n\n    All TypeInfos are killed. Therefore we need to preserve the variables\n    defined as attributes on self. This is done by patches (callbacks)\n    returned from this function that re-add these variables when called.\n\n    Args:\n        node: node to strip\n        saved_attrs: collect attributes here that may need to be re-added to\n            classes afterwards if stripping a class body (this dict is mutated)\n    \"\"\"\n    visitor = NodeStripVisitor(saved_attrs)\n    if isinstance(node, MypyFile):\n        visitor.strip_file_top_level(node)\n    else:\n        node.accept(visitor)\n\n\nclass NodeStripVisitor(TraverserVisitor):\n    def __init__(self, saved_class_attrs: SavedAttributes) -> 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        # By default, process function definitions. If False, don't -- this is used for\n        # processing module top levels.\n        self.recurse_into_functions = True\n        # These attributes were removed from top-level classes during strip and\n        # will be added afterwards (if no existing definition is found). These\n        # must be added back before semantically analyzing any methods.\n        self.saved_class_attrs = saved_class_attrs\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 save the implicitly defined instance variables,\n        # i.e. those defined as attributes on self. Otherwise, they would\n        # be lost if we only reprocess top-levels (this kills TypeInfos)\n        # but not the methods that defined those variables.\n        if not self.recurse_into_functions:\n            self.save_implicit_attributes(node)\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 for s in node.defs.body if s not in to_delete  # type: ignore[comparison-overlap]\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 save_implicit_attributes(self, node: ClassDef) -> None:\n        \"\"\"Produce callbacks that re-add attributes defined on self.\"\"\"\n        for name, sym in node.info.names.items():\n            if isinstance(sym.node, Var) and sym.implicit:\n                self.saved_class_attrs[node, name] = sym\n\n    def visit_func_def(self, node: FuncDef) -> None:\n        if not self.recurse_into_functions:\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 self.enter_method(node.info) if node.info else nullcontext():\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:\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:\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        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                key = (self.type.defn, lvalue.name)\n                if key in self.saved_class_attrs:\n                    del self.saved_class_attrs[key]\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    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    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    IntersectionType,\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 are\n        # only present in expanded form in symbol tables. For example, after:\n        #    A = List[int]\n        #    x: A\n        # The module symbol table will just have a Var `x` with type `List[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        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, FuncBase):\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_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        # TODO: Now that type aliases are its own kind of types we can simplify\n        # the logic to rely on intermediate dependencies (like for instance types).\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        if typ.upper_bound:\n            triggers.extend(self.get_type_triggers(typ.upper_bound))\n        if typ.default:\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        if typ.upper_bound:\n            triggers.extend(self.get_type_triggers(typ.upper_bound))\n        if typ.default:\n            triggers.extend(self.get_type_triggers(typ.default))\n        triggers.extend(self.get_type_triggers(typ.upper_bound))\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        if typ.upper_bound:\n            triggers.extend(self.get_type_triggers(typ.upper_bound))\n        if typ.default:\n            triggers.extend(self.get_type_triggers(typ.default))\n        triggers.extend(self.get_type_triggers(typ.upper_bound))\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    def visit_intersection_type(self, typ: IntersectionType) -> 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 names, since they are ambiguous.\n        # TODO: Everything should have a proper full name?\n        if fn is None:\n            continue\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[sym.fullname] = 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\nfrom mypy.util import getattr\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__\"):\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    TupleExpr,\n    TypeApplication,\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_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_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 Sequence\nfrom typing import Callable, Final, NamedTuple, Optional, Union, cast\nfrom typing_extensions import 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    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    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 SavedAttributes, 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 = Union[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        manager.missing_modules.remove(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\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    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        manager.missing_modules.add(module_id)\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)\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)\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)\n\n    # Strip semantic analysis information.\n    saved_attrs: SavedAttributes = {}\n    for deferred in nodes:\n        processed_targets.append(deferred.node.fullname)\n        strip_target(deferred.node, saved_attrs)\n    semantic_analysis_for_targets(graph[module_id], nodes, graph, saved_attrs)\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    more = checker.check_second_pass(nodes)\n    while more:\n        more = False\n        if graph[module_id].type_checker().check_second_pass():\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\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\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 = cast(Optional[SymbolNode], 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(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    \"__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    \"__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_extensions 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_types\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 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    bottom: Type | None = None\n    top: Type | None = None\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    if not uppers and not lowers:\n        candidate = UninhabitedType()\n        candidate.ambiguous = True\n        return candidate\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    for target in lowers:\n        if bottom is None:\n            bottom = target\n        else:\n            if type_state.infer_unions:\n                # This deviates from the general mypy semantics because\n                # recursive types are union-heavy in 95% of cases.\n                bottom = UnionType.make_union([bottom, target])\n            else:\n                bottom = join_types(bottom, target)\n\n    for target in uppers:\n        if top is None:\n            top = target\n        else:\n            top = meet_types(top, target, intersect=True)\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 = sorted(scc, key=lambda x: (x.id not in original_vars, x.id.raw_id))[0]\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.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    TypeQuery,\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(TypeQuery[bool]):\n    def __init__(self) -> None:\n        super().__init__(any)\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.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: list[object] = [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.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    # 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            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_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_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\nfrom typing_extensions import 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\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    ) -> 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 or 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 docstring:\n            suffix = f\"\\n{indent}    {mypy.util.quote_docstring(docstring)}\"\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        # 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] 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                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                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\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    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    Decorator,\n    DictExpr,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    FuncBase,\n    FuncDef,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    OpExpr,\n    OverloadedFuncDef,\n    SetExpr,\n    StarExpr,\n    Statement,\n    StrExpr,\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    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        legacy: 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        self.legacy = legacy\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_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_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_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\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        legacy: bool = False,\n    ) -> None:\n        super().__init__(_all_, include_private, export_less, include_docstrings, legacy=legacy)\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, True, 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            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 if self.legacy else self.add_name(\"_typeshed.Incomplete\")  # implicit Any\n        retname = infer_method_ret_type(o.name)\n        if not self.legacy and retname == \"None\":\n            return None\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 o.is_property:\n            return None\n\n        if not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT:\n            return \"None\" if self.legacy else None\n        return None if self.legacy else self.add_name(\"_typeshed.Incomplete\")\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\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 not self.is_private_name(lvalue.name)\n                # it is never an alias with explicit annotation\n                and not o.unanalyzed_type\n                and self.is_alias_expression(o.rvalue)\n            ):\n                self.process_typealias(lvalue, o.rvalue)\n                continue\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 (\n            \"typing.TypeVar\",\n            \"typing_extensions.TypeVar\",\n            \"typing.ParamSpec\",\n            \"typing_extensions.ParamSpec\",\n            \"typing.TypeVarTuple\",\n            \"typing_extensions.TypeVarTuple\",\n        ):\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(self, lvalue: NameExpr, rvalue: Expression) -> None:\n        p = AliasPrinter(self)\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(\n        self, rvalue: Expression, can_infer_optional: bool = False, can_be_any: bool = True\n    ) -> 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_infer_optional and isinstance(rvalue, NameExpr) and rvalue.name == \"None\":\n            return f\"{self.add_name('_typeshed.Incomplete')} | None\"\n        if can_be_any:\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    if sys.platform == \"win32\":\n        return path.replace(\"\\\\\", \"/\")\n    return path  # type: ignore[unreachable, unused-ignore]\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.runtime_all = res.manager.semantic_analyzer.export_map[mod.module]\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    legacy: 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            legacy=legacy,\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            legacy=legacy,\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                legacy=options.legacy,\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(\"--legacy\", action=\"store_true\", help=\"don't used based features\")\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        legacy=ns.legacy,\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 glob\nimport importlib\nimport inspect\nimport keyword\nimport os.path\nfrom collections.abc import Mapping\nfrom types import FunctionType, ModuleType\nfrom typing import Any, Callable\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 getattr\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\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        legacy=False,\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, legacy=legacy)\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 | None]\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 None:\n                    if arg in annotations:\n                        argtype = annotations[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 | None:\n            if defaults and i >= len(args) - len(defaults):\n                return defaults[i - (len(args) - len(defaults))]\n            else:\n                return None\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 wee need to add \"*\"\n        elif kwonlyargs:\n            arglist.append(ArgSig(\"*\"))\n\n        def get_kw_default(_i: int, arg: str) -> Any | None:\n            if kwonlydefaults:\n                return kwonlydefaults.get(arg)\n            else:\n                return None\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__\")\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__\")\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        if docstring:\n            docstring = self._indent_docstring(docstring)\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                ro_properties.append(f\"{self._indent}@property\")\n                sig = FunctionSig(name, [ArgSig(\"self\")], inferred_type)\n                ro_properties.append(sig.format_sig(indent=self._indent))\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        # typ is a TypeForm, not a type\n        if typ is Any:  # type: ignore[comparison-overlap, unused-ignore]\n            return \"Any\"\n        typename = getattr(typ, \"__qualname__\", typ.__name__)\n        module_name = self.get_obj_module(typ)\n        assert module_name is not None, typ\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__\")\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        if types or static_properties or rw_properties or methods or ro_properties:\n            output.append(f\"{self._indent}class {class_name}{bases_str}:\")\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            for line in static_properties:\n                output.append(line)\n            for line in rw_properties:\n                output.append(line)\n            for line in methods:\n                output.append(line)\n            for line in ro_properties:\n                output.append(line)\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    \"OpenSSL\": \"types-pyOpenSSL\",\n    \"paramiko\": \"types-paramiko\",\n    \"pkg_resources\": \"types-setuptools\",\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    \"_win32typing\": \"types-pywin32\",\n    \"antlr4\": \"types-antlr4-python3-runtime\",\n    \"assertpy\": \"types-assertpy\",\n    \"atheris\": \"types-atheris\",\n    \"authlib\": \"types-Authlib\",\n    \"aws_xray_sdk\": \"types-aws-xray-sdk\",\n    \"boltons\": \"types-boltons\",\n    \"braintree\": \"types-braintree\",\n    \"bs4\": \"types-beautifulsoup4\",\n    \"bugbear\": \"types-flake8-bugbear\",\n    \"caldav\": \"types-caldav\",\n    \"capturer\": \"types-capturer\",\n    \"cffi\": \"types-cffi\",\n    \"chevron\": \"types-chevron\",\n    \"click_default_group\": \"types-click-default-group\",\n    \"click_log\": \"types-click-log\",\n    \"click_web\": \"types-click-web\",\n    \"colorama\": \"types-colorama\",\n    \"commctrl\": \"types-pywin32\",\n    \"commonmark\": \"types-commonmark\",\n    \"consolemenu\": \"types-console-menu\",\n    \"corus\": \"types-corus\",\n    \"cronlog\": \"types-python-crontab\",\n    \"crontab\": \"types-python-crontab\",\n    \"crontabs\": \"types-python-crontab\",\n    \"datemath\": \"types-python-datemath\",\n    \"dateparser_data\": \"types-dateparser\",\n    \"dde\": \"types-pywin32\",\n    \"defusedxml\": \"types-defusedxml\",\n    \"docker\": \"types-docker\",\n    \"dockerfile_parse\": \"types-dockerfile-parse\",\n    \"editdistance\": \"types-editdistance\",\n    \"entrypoints\": \"types-entrypoints\",\n    \"exifread\": \"types-ExifRead\",\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    \"gevent\": \"types-gevent\",\n    \"greenlet\": \"types-greenlet\",\n    \"hdbcli\": \"types-hdbcli\",\n    \"html5lib\": \"types-html5lib\",\n    \"httplib2\": \"types-httplib2\",\n    \"humanfriendly\": \"types-humanfriendly\",\n    \"hvac\": \"types-hvac\",\n    \"ibm_db\": \"types-ibm-db\",\n    \"icalendar\": \"types-icalendar\",\n    \"import_export\": \"types-django-import-export\",\n    \"influxdb_client\": \"types-influxdb-client\",\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    \"lupa\": \"types-lupa\",\n    \"lzstring\": \"types-lzstring\",\n    \"m3u8\": \"types-m3u8\",\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    \"portpicker\": \"types-portpicker\",\n    \"psutil\": \"types-psutil\",\n    \"psycopg2\": \"types-psycopg2\",\n    \"pyasn1\": \"types-pyasn1\",\n    \"pyaudio\": \"types-pyaudio\",\n    \"pyautogui\": \"types-PyAutoGUI\",\n    \"pycocotools\": \"types-pycocotools\",\n    \"pyflakes\": \"types-pyflakes\",\n    \"pygit2\": \"types-pygit2\",\n    \"pygments\": \"types-Pygments\",\n    \"pyi_splash\": \"types-pyinstaller\",\n    \"PyInstaller\": \"types-pyinstaller\",\n    \"pynput\": \"types-pynput\",\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    \"regex\": \"types-regex\",\n    \"regutil\": \"types-pywin32\",\n    \"reportlab\": \"types-reportlab\",\n    \"requests_oauthlib\": \"types-requests-oauthlib\",\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    \"slumber\": \"types-slumber\",\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    \"tree_sitter_languages\": \"types-tree-sitter-languages\",\n    \"ttkthemes\": \"types-ttkthemes\",\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    \"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    \"xdg\": \"types-pyxdg\",\n    \"xdgenvpy\": \"types-xdgenvpy\",\n    \"Xlib\": \"types-python-xlib\",\n    \"xmltodict\": \"types-xmltodict\",\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}\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 importlib.machinery\nimport inspect\nimport os\nimport pkgutil\nimport re\nimport symtable\nimport sys\nimport traceback\nimport types\nimport typing\nimport typing_extensions\nimport warnings\nfrom collections import defaultdict\nfrom collections.abc import Iterator, Set as AbstractSet\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom functools import singledispatch\nfrom pathlib import Path\nfrom typing import Any, Final, Generic, TypeVar, Union\nfrom typing_extensions import get_origin, is_typeddict\n\nimport mypy.build\nimport mypy.modulefinder\nimport mypy.nodes\nimport mypy.state\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.options import Options\nfrom mypy.util import FancyFormatter, bytes_to_human_readable_repr, getattr, 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 = Union[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 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/KotlinIsland/basedmypy\\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        yield Error(object_path, \"is not a module\", stub, runtime)\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 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[subclass-any]\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\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, runtime: MaybeMissing[type[Any]], object_path: list[str]\n) -> Iterator[Error]:\n    if stub.is_type_check_only:\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        yield Error(object_path, \"is not a type\", stub, runtime, stub_desc=repr(stub))\n        return\n\n    yield from _verify_final(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 runtime_attr is not MISSING and type(runtime) is not runtime:\n            if getattr(runtime_attr, \"__objclass__\", None) is type(runtime):\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    def strip_prefix(s: str, prefix: str) -> str:\n        return s[len(prefix) :] if s.startswith(prefix) else s\n\n    if strip_prefix(stub_arg.variable.name, \"__\") == runtime_arg.name:\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 argument \"{stub_arg.variable.name}\" '\n        f'differs from runtime argument \"{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 argument \"{runtime_arg.name}\" '\n                \"has a default value but stub argument does not\"\n            )\n        else:\n            runtime_type = get_mypy_type_of_runtime_value(runtime_arg.default)\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 argument \"{runtime_arg.name}\" '\n                    f\"has a default value of type {runtime_type}, \"\n                    f\"which is incompatible with stub argument 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 argument \"{runtime_arg.name}\" '  # type: ignore[any, unused-ignore]\n                            f\"has a default value of {runtime_arg.default!r}, \"\n                            f\"which is different from stub argument default {stub_default!r}\"\n                        )\n    else:\n        if stub_arg.kind.is_optional():\n            yield (\n                f'stub argument \"{stub_arg.variable.name}\" has a default value '\n                f\"but runtime argument 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        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\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                name = (\n                    f\"__{index}\"\n                    if arg.variable.name.startswith(\"__\")\n                    or arg.pos_only\n                    or assume_positional_only\n                    or arg.variable.name.strip(\"_\") == \"self\"\n                    else arg.variable.name\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], runtime: Signature[inspect.Parameter], function_name: str\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 not is_dunder(function_name, exclude_special=True)  # noisy for dunder methods\n        ):\n            yield (\n                f'stub argument \"{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 stub_arg.variable.name.strip(\"_\") != \"self\"\n            and not is_dunder(function_name, exclude_special=True)  # noisy for dunder methods\n        ):\n            yield (\n                f'stub argument \"{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 argument \"{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                    yield msg\n                else:\n                    yield f'stub argument \"{stub_arg.variable.name}\" is not keyword-only'\n            if stub.varpos is not None:\n                yield f'runtime does not have *args argument \"{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 argument \"{runtime_arg.name}\"'\n            else:\n                yield f'runtime argument \"{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 argument \"{runtime.varpos.name}\"'\n        if stub.varpos is not None and runtime.varpos is None:\n            yield f'runtime does not have *args argument \"{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 argument \"{arg}\" is not keyword-only'\n            else:\n                yield f'runtime does not have argument \"{arg}\"'\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 argument \"{arg}\" is not keyword-only'\n        else:\n            if not _is_private_parameter(runtime.kwonly[arg]):\n                yield f'stub does not have argument \"{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 argument \"{runtime.varkw.name}\"'\n    if stub.varkw is not None and runtime.varkw is None:\n        yield f'runtime does not have **kwargs argument \"{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(stub_sig, runtime_sig, function_name=stub.name):\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_none(\n    stub: Missing, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\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)\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 ...\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 == \"builtins.ellipsis\"\n            ):\n                should_error = False\n\n        if should_error:\n            yield Error(\n                object_path, f\"variable differs from runtime type {runtime_type}\", stub, runtime\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(stub_sig, runtime_sig, function_name=stub.name):\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 _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 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.FINAL_DECORATOR_NAMES\n        ):\n            return func\n        if decorator.fullname == \"builtins.classmethod\":\n            if func.arguments[0].variable.name not in (\"cls\", \"mcs\", \"metacls\"):\n                raise StubtestFailure(\n                    f\"unexpected class argument 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            return None\n        func = resulting_func\n    return func\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(stub_origin, runtime_origin, object_path)\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        \"__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        \"__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        # 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        # 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(runtime, (types.FunctionType, types.BuiltinFunctionType))\n        or isinstance(runtime, (types.MethodType, types.BuiltinMethodType))\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    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\ndef is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool:\n    \"\"\"Checks whether ``left`` is a subtype of ``right``.\"\"\"\n    left = mypy.types.get_proper_type(left)\n    right = 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_type_of_runtime_value(runtime: Any) -> 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.UntypedType:\n        return mypy.types.UntypedType()\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    # Try and look up a stub for the runtime object\n    stub = get_stub(type(runtime).__module__)\n    if stub is None:\n        return None\n    type_name = type(runtime).__name__\n    if type_name not in stub.names:\n        return None\n    type_info = stub.names[type_name].node\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\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    all_stdlib_modules: AbstractSet[str]\n    if sys.version_info >= (3, 10):\n        all_stdlib_modules = sys.stdlib_module_names\n    else:\n        all_stdlib_modules = set(sys.builtin_module_names)\n        modules_by_finder: defaultdict[importlib.machinery.FileFinder, set[str]] = defaultdict(set)\n        for m in pkgutil.iter_modules():\n            if isinstance(m.module_finder, importlib.machinery.FileFinder):\n                modules_by_finder[m.module_finder].add(m.name)\n        for finder, module_group in modules_by_finder.items():\n            if (\n                \"site-packages\" not in Path(finder.path).parts\n                # if \"_queue\" is present, it's most likely the module finder\n                # for stdlib extension modules;\n                # if \"queue\" is present, it's most likely the module finder\n                # for pure-Python stdlib modules.\n                # In either case, we'll want to add all the modules that the finder has to offer us.\n                # This is a bit hacky, but seems to work well in a cross-platform way.\n                and {\"_queue\", \"queue\"} & module_group\n            ):\n                all_stdlib_modules.update(module_group)\n\n    importable_stdlib_modules: set[str] = set()\n    for module_name in all_stdlib_modules:\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    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\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\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 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            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 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    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 = ()\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        legacy=False,\n    ):\n        self.legacy = legacy\n\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\n        if fullname == \"_typeshed.Incomplete\" and not self.legacy:\n            fullname = \"basedtyping.Untyped\"\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 if self._include_docstrings else None,\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 Iterator\nfrom contextlib import contextmanager\nfrom typing import Callable, Final, TypeVar, cast\nfrom typing_extensions import TypeAlias as _TypeAlias\n\nimport mypy.applytype\nimport mypy.constraints\nimport mypy.typeops\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    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    IntersectionType,\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    UntypedType,\n    find_unpack_in_list,\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\nfrom mypy.util import safe\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\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        self.checking_callable_instance = False\n        \"\"\"ergh, #cringe\"\"\"\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 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 not any(\n            {\n                ignore_type_params,\n                ignore_pos_arg_names,\n                ignore_declared_variance,\n                always_covariant,\n                ignore_promotions,\n                options,\n            }\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 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 not any(\n            {ignore_promotions, erase_instances, 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 isinstance(a, TypeVarType) and isinstance(b, TypeVarType) and a.id == b.id:\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(mypy.typeops.try_contracting_literals_in_union(right.items))\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    if isinstance(right, IntersectionType) and not isinstance(left, IntersectionType):\n        if proper_subtype:\n            if all(\n                is_proper_subtype(orig_left, item, subtype_context=subtype_context)\n                for item in right.items\n            ):\n                return True\n        else:\n            if all(\n                is_subtype(orig_left, item, subtype_context=subtype_context)\n                for item in right.items\n            ):\n                return True\n\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    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    # 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 case to consider Foo[*tuple[Any, ...]] (i.e. bare Foo) a\n                    # subtype of Foo[<whatever>], when Foo is user defined variadic tuple type.\n                    mapped = map_instance_to_supertype(left, right.partial_fallback.type)\n                    for arg in map(get_proper_type, mapped.args):\n                        if isinstance(arg, UnpackType):\n                            unpacked = get_proper_type(arg.type)\n                            if not isinstance(unpacked, Instance):\n                                break\n                            assert unpacked.type.fullname == \"builtins.tuple\"\n                            if not isinstance(get_proper_type(unpacked.args[0]), AnyType):\n                                break\n                        elif not isinstance(arg, AnyType):\n                            break\n                    else:\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 t.args:\n                        for arg in map(get_proper_type, t.args):\n                            if isinstance(arg, UnpackType):\n                                unpacked = get_proper_type(arg.type)\n                                if not isinstance(unpacked, Instance):\n                                    break\n                                assert unpacked.type.fullname == \"builtins.tuple\"\n                                if not isinstance(get_proper_type(unpacked.args[0]), AnyType):\n                                    break\n                            elif not isinstance(arg, AnyType):\n                                break\n                        else:\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                checking_callable_instance = self.subtype_context.checking_callable_instance\n                self.subtype_context.checking_callable_instance = True\n                try:\n                    result = self._is_subtype(call, right)\n                finally:\n                    self.subtype_context.checking_callable_instance = checking_callable_instance\n                if not result:\n                    return False\n                if right.is_named:\n                    str_type = safe(find_member(\"__name__\", right.fallback, right.fallback))\n                    name = find_member(\"__name__\", left, left)\n                    if not (name and is_subtype(name, str_type)):\n                        return False\n                    qualname = find_member(\"__qualname__\", left, left)\n                    if not (qualname and is_subtype(qualname, str_type)):\n                        return False\n                return True\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            return True\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 left.type_guard.target != right.type_guard.target:\n                    if left.type_guard.target_is_self or left.type_guard.target_is_class:\n                        return False\n                    if (\n                        left.type_guard.target == \"first argument\"\n                        and right.arg_names.index(right.type_guard.target) != 0  # type: ignore[arg-type]\n                    ):\n                        return False\n                    elif (\n                        right.type_guard.target == \"first argument\"\n                        and left.arg_names.index(left.type_guard.target) != 0  # type: ignore[arg-type]\n                    ):\n                        return False\n                if not right.type_guard.only_true and left.type_guard.only_true:\n                    # only_true is a supertype\n                    return False\n                if not self._is_subtype(left.type_guard.type_guard, right.type_guard.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            checking_callable_instance = self.subtype_context.checking_callable_instance\n            self.subtype_context.checking_callable_instance = False\n            try:\n                result = 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            finally:\n                self.subtype_context.checking_callable_instance = checking_callable_instance\n            if not result:\n                return False\n            if checking_callable_instance:\n                return True\n            if right.is_named and left.is_callable:\n                return False\n            return True\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                # TODO: we should probably explicitly exclude self-types in this case.\n                call = find_member(\"__call__\", right, left, 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_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 unpacks can't be split.\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            left_prefix = left_unpack_index\n            left_suffix = len(left.items) - left_prefix - 1\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 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, left, 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_intersection_type(self, left: IntersectionType) -> bool:\n        if isinstance(self.right, IntersectionType):\n            return all(self._is_subtype(left, item) for item in self.right.items)\n        return any(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 isinstance(right, TypeType):\n            return self._is_subtype(left.item, right.item)\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        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            # 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 = get_proper_type(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 isinstance(subtype, PartialType):\n                subtype = (\n                    NoneType()\n                    if subtype.type is None\n                    else Instance(subtype.type, [UntypedType()] * len(subtype.type.type_vars))\n                )\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(subtype, supertype, options=options)\n            else:\n                is_compat = is_proper_subtype(subtype, supertype)\n            if not is_compat:\n                return False\n            if isinstance(subtype, NoneType) and isinstance(supertype, CallableType):\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 not is_subtype(supertype, subtype, options=options):\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            if IS_SETTABLE in superflags and IS_SETTABLE not in subflags:\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        ignore_names = False\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, itype: Instance, subtype: Type, is_operator: bool = False, class_obj: 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    # TODO: this code shares some logic with checkmember.analyze_member_access,\n    # consider refactoring.\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            return find_node_type(dec.var, itype, subtype, class_obj=class_obj)\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                return {IS_VAR, IS_SETTABLE}\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        if v.is_classvar:\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 find_node_type(\n    node: Var | FuncBase, itype: Instance, subtype: Type, class_obj: 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        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            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    if not allow_partial_overlap:\n        # Non-type cannot be a subtype of type.\n        if right.is_type_obj() and not left.is_type_obj():\n            return False\n\n        # type can only be a subtype of Callable.\n        elif left.is_type_obj() and not (right.is_type_obj() or right.is_callable):\n            return False\n\n        # everything can be a 'named' (i think)\n        elif right.is_named:\n            pass\n\n        # Callable cannot be a subtype of different fallbacks. (assuming there are no subtypes between fallbacks)\n        elif not right.is_callable and left.fallback_name != right.fallback_name:\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    if (\n        right.arg_kinds == [ARG_STAR]\n        and isinstance(get_proper_type(right.arg_types[0]), AnyType)\n        and not is_proper_subtype\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        # HACK: working around upstream issues:\n        #  https://github.com/python/mypy/issues/16567\n        #  https://github.com/python/mypy/issues/16568\n        # if all(k.is_positional() for k in left.arg_kinds) and ignore_pos_arg_names:\n        if all(k.is_positional() for k in left.arg_kinds):\n            return 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 _incompatible(left_star, right_star) or _incompatible(left_star2, right_star2):\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    # 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: are we handling UnpackType correctly here?\n    if right_star is not None and not trivial_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 and not trivial_suffix:\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(*_, **__) -> 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, *, erase=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(item, s, erase=erase)\n                for item in p_t.relevant_items()\n                if (\n                    isinstance(get_proper_type(item), AnyType)\n                    or not covers_at_runtime(item, s, erase=erase)\n                )\n            ]\n        return UnionType.make_union(new_items)\n    elif isinstance(p_t, TypeVarType):\n        return p_t.copy_modified(upper_bound=restrict_subtype_away(p_t.upper_bound, s))\n    elif covers_at_runtime(t, s, erase=erase):\n        return UninhabitedType()\n    else:\n        return t\n\n\ndef covers_at_runtime(item: Type, supertype: Type, *, erase=True) -> 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 erase:\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    elif is_proper_subtype(item, supertype, ignore_promotions=True):\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            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"
  },
  {
    "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\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import Callable, 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    reverse_builtin_aliases,\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 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\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 tyeps\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 not node.is_static\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            if key.count(\":\") > 1:\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.split(\":\")\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, FuncDef):\n                typ = dec.node.type\n            elif (\n                isinstance(dec, CallExpr)\n                and isinstance(dec.callee, RefExpr)\n                and isinstance(dec.callee.node, FuncDef)\n                and isinstance(dec.callee.node.type, CallableType)\n            ):\n                typ = get_proper_type(dec.callee.node.type.ret_type)\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 isinstance(ct.arg_types[0], TypeVarType)\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        if s in reverse_builtin_aliases:\n            s = reverse_builtin_aliases[s]\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:\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            return f\"Optional[{remove_optional(t).accept(self)}]\"\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.is_type_obj() or s.is_type_obj()) and 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, Union\nfrom typing_extensions import 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\nfrom mypy.util import safe\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 = Union[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    ignore = \"\\n# mypy: allow-untyped-defs, allow-any-explicit, allow-incomplete-defs, allow_any_generics, disable-error-code=explicit-override\\n\"\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() + ignore))\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() + ignore))\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    tmp_output = []\n    for file_path, contents in files:\n        expand_errors(contents.split(\"\\n\"), tmp_output, file_path)\n    output = tmp_output + output\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: DataSuiteCollector\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: DataSuiteCollector,\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        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        os.environ[\"__MYPY_UNDER_TEST__\"] = \"1\"\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        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: {Path(self.file).as_uri()}:{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 = safe(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)], safe(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        \"--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)  # type: ignore[no-untyped-call, unused-ignore]\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    r\"(?P<version>-3.\\d+)?\"\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 = safe(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        version = m.group(\"version\")\n        if version:\n            if sys.version_info < (3, int(version.split(\".\")[1])):\n                continue\n            name += version\n        yield DataDrivenTestCase.from_parent(  # type: ignore[unused-ignore, no-untyped-call]\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 Iterable, Iterator\nfrom re import Pattern\nfrom typing import IO, Any, Callable\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, errorcodes\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\nfrom mypy.util import getattr\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\"\n        render_diff_range(expected_ranges, expected, colour=red)\n        sys.stderr.write(\"Actual:\\n\")\n        green = \"\\033[32m\"\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        # 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    m = re.search(r\"python3([0-9]+)\\.test$\", path)\n    if m:\n        return 3, int(m.group(1))\n    else:\n        return defaults.PYTHON3_VERSION\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, based: bool = False\n) -> Options:\n    \"\"\"Parse comments like '# flags: --foo' in a test case.\"\"\"\n    import mypy.options\n\n    # This is extremely sus as it's a global option shared by all tests.\n    #  But it seems to be okay (I tested it)\n    mypy.options._based = based\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: list[str] = flags.group(1).split()\n        flag_list = [\"--no-pretty\", \"--hide-error-context\", \"--hide-error-code-links\"] + flag_list\n        if based:\n            flag_list.append(\"--hide-column-numbers\")\n            flag_list.extend([\"--enable-error-code\", \"no-untyped-usage\"])\n        else:\n            flag_list = [\n                \"--no-default-return\",\n                \"--no-infer-function-types\",\n                \"--no-bare-literals\",\n                \"--no-strict\",\n            ] + flag_list\n        flag_list.append(\"--no-site-packages\")  # the tests shouldn't need an installed Python\n        if \"--local-partial-types\" in flag_list:\n            flag_list.remove(\"--local-partial-types\")\n            flag_list.append(\"--no-nonlocal-partial-types\")\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 not based and \"--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        if based:\n            options.show_column_numbers = False\n            options.enabled_error_codes.update(\n                {\n                    errorcodes.NO_UNTYPED_USAGE,\n                    errorcodes.BAD_CAST,\n                    errorcodes.REDUNDANT_EXPR,\n                    errorcodes.HELPFUL_STRING,\n                    errorcodes.CALLABLE_FUNCTIONTYPE,\n                    errorcodes.POSSIBLE_FUNCTION,\n                }\n            )\n        else:\n            options.default_return = False\n            options.bare_literals = False\n            options.infer_function_types = False\n            options.hide_error_codes = True\n            options.force_uppercase_builtins = True\n        options.force_union_syntax = True\n        options.pretty = False\n        options.show_error_context = False\n        options.show_error_code_links = False\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\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        if path.startswith(strip_prefix):\n            path = path[len(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        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.__based_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_based_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 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"
  },
  {
    "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            \"\"\"\n            [case abc]\n            s: str\n            [case foo-XFAIL]\n            s: str\n            \"\"\"\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            \"\"\"\n            [case abc]\n            s: str\n            [unknownsection]\n            abc\n            \"\"\"\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            \"\"\"\n            [case abc]\n            s: str\n            [out version>=3.9]\n            abc\n            \"\"\"\n        )\n\n        # Assert\n        assert \"version>=3.9 always true since minimum runtime version is (3, 9)\" in actual.stdout\n\n    def test_bad_eq_version_check(self) -> None:\n        # Act\n        actual = _run_pytest(\n            \"\"\"\n            [case abc]\n            s: str\n            [out version==3.7]\n            abc\n            \"\"\"\n        )\n\n        # Assert\n        assert \"version==3.7 always false since minimum runtime version is (3, 9)\" in actual.stdout\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            \"\"\"\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\n        # Assert\n        expected = dedent_docstring(\n            \"\"\"\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        )\n        assert result.input_updated == expected\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_ref_info.py",
    "content": "\"\"\"Test exporting line-level reference information (undocumented feature)\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport sys\nfrom typing import Any\n\nimport mypy.options\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        mypy.options._based = False\n        options = Options()\n        mypy.options._based = False\n        options.default_return = False\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\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: Any = 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\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        import mypy.options\n\n        mypy.options._based = False\n        options = Options()\n        _, parsed_options = process_options([\"--no-strict\"], 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 = 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\n\nfrom mypy import build\nfrom mypy.build import Graph\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)\nfrom mypy.test.update_data import update_testcase_output\n\ntry:\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\nbased_files = find_test_files(pattern=\"check-based-*.test\")\ntypecheck_files = find_test_files(pattern=\"check-*.test\", exclude=based_files)\n\n\n# Tests that use Python version specific features:\nif sys.version_info < (3, 10):\n    typecheck_files.remove(\"check-python310.test\")\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\")\n    based_files.remove(\"check-based-python313.test\")\n\n# Special tests for platforms with case-insensitive filesystems.\nif sys.platform not in (\"darwin\", \"win32\"):\n    typecheck_files.remove(\"check-modules-case.test\")\n\n\nclass TypeCheckSuite(DataSuite):\n    files = typecheck_files + based_files\n\n    def based(self, testcase: DataDrivenTestCase) -> bool:\n        return \"based\" in testcase.parent.name\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\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        based = self.based(testcase)\n        # Parse options after moving files (in case mypy.ini is being moved).\n        options = parse_options(original_program_text, testcase, incremental_step, based=based)\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        version_match = re.search(r\"-3\\.(\\d+)$\", testcase.name)\n        if version_match:\n            options.python_version = 3, int(version_match.group(1))\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        if \"lowercase\" not in testcase.file and not based:\n            options.force_uppercase_builtins = True\n        if \"union-error\" not in testcase.file:\n            options.force_union_syntax = True\n\n        if incremental_step and options.incremental:\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        sys.path.insert(0, plugin_dir)\n\n        res = None\n        try:\n            res = build.build(sources=sources, options=options, alt_lib_path=test_temp_dir)\n            a = res.errors\n        except CompileError as e:\n            a = e.messages\n        finally:\n            assert sys.path[0] == plugin_dir\n            del sys.path[0]\n\n        # When running the legacy tests in based mode, we just make sure they don't crash\n        if isinstance(self, BasedTypeCheckSuite):\n            # We fail xfail tests explicitly\n            if testcase.xfail:\n                raise AssertionError()\n            return\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        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.errors, res.manager, res.graph)\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            if 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\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        a: list[str],\n        manager: build.BuildManager,\n        graph: Graph,\n    ) -> None:\n        # There should be valid cache metadata for each module except\n        # for those that had an error in themselves or one of their\n        # dependencies.\n        error_paths = self.find_error_message_paths(a)\n        busted_paths = {m.path for id, m in manager.modules.items() if graph[id].transitive_error}\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        # We would like to assert error_paths.issubset(busted_paths)\n        # but this runs into trouble because while some 'notes' are\n        # really errors that cause an error to be marked, many are\n        # just notes attached to other errors.\n        assert error_paths or not busted_paths, \"Some modules reported error despite no errors\"\n        if not missing_paths == busted_paths:\n            raise AssertionError(f\"cache data discrepancy {missing_paths} != {busted_paths}\")\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_error_message_paths(self, a: list[str]) -> set[str]:\n        hits = set()\n        for line in a:\n            m = re.match(r\"([^\\s:]+):(\\d+:)?(\\d+:)? (error|warning|note):\", line)\n            if m:\n                p = m.group(1)\n                hits.add(p)\n        return hits\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\n\nclass BasedTypeCheckSuite(TypeCheckSuite):\n    files = typecheck_files\n\n    def based(self, testcase: DataDrivenTestCase) -> bool:\n        return True\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\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    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 = [\n    \"cmdline.test\",\n    \"cmdline-based.test\",\n    \"cmdline-based-baseline.test\",\n    \"cmdline-based-regex.test\",\n    \"cmdline.pyproject.test\",\n    \"reports.test\",\n    \"envvars.test\",\n]\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    preload_cache = \"# preload-cache:\" in testcase.input\n    args.append(\"--show-traceback\")\n    based = \"based\" in testcase.parent.name\n    if not based:\n        args.append(\"--no-strict\")\n        args.append(\"--no-default-return\")\n    if \"--pretty\" not in args:\n        args.append(\"--no-pretty\")\n    args.append(\"--no-color-output\")\n    if \"--show-error-code-links\" not in args and \"--ide\" not in args:\n        args.append(\"--hide-error-code-links\")\n    if \"--error-summary\" not in args:\n        args.append(\"--no-error-summary\")\n    if \"--show-error-codes\" not in args and not based:\n        args.append(\"--hide-error-codes\")\n    if \"--disallow-empty-bodies\" not in args:\n        args.append(\"--allow-empty-bodies\")\n    if \"--no-force-uppercase-builtins\" not in args:\n        args.append(\"--force-uppercase-builtins\")\n    if \"--no-force-union-syntax\" not in args:\n        args.append(\"--force-union-syntax\")\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    env[\"__MYPY_UNDER_TEST__\"] = \"1\" if based else \"2\"\n    if \"--pretty\" in args:\n        env[\"COLUMNS\"] = \"80\"\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    if preload_cache:\n        subprocess.Popen(\n            fixed + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env\n        ).communicate()\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        assert not testcase.output, \"output not checked when outfile supplied\"\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, IntersectionType, 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\n    def test_intersection(self):\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                IntersectionType([fx.t, fx.d]), IntersectionType([fx.a, fx.d]), SUPERTYPE_OF\n            )\n        ) == {Constraint(fx.t, SUPERTYPE_OF, fx.a)}\n        assert set(\n            infer_constraints(\n                IntersectionType([fx.t, fx.d]), IntersectionType([fx.a, fx.d]), SUBTYPE_OF\n            )\n        ) == {Constraint(fx.t, SUBTYPE_OF, fx.a)}\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\"]\nbased_daemon_files = [\"daemon-based.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\nclass BasedDaemonSuite(DaemonSuite):\n    files = based_daemon_files\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        if cmd.split()[1] in (\"start\", \"restart\", \"run\"):\n            unbased = \" -- --no-strict --no-infer-function-types --no-default-return --hide-column-numbers --no-pretty --hide-error-context --hide-error-code-links \"\n            if \" -- \" in cmd:\n                cmd = cmd.replace(\" -- \", unbased)\n            else:\n                cmd += unbased\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    env[\"__MYPY_UNDER_TEST__\"] = \"1\"\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    import mypy.options\n\n    mypy.options._based = False\n    options = Options()\n    options.show_traceback = True\n    options.hide_error_codes = True\n    options.show_error_context = False\n    options.pretty = False\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/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, cast\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            return\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        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 fixup(self, output: list[str]) -> list[str]:\n        # HACK: for some reason, macs can use this privatetmp folder\n        return [line.replace(\"/privatetmp/\", \"tmp/\") for line in output]\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 = cast(\n                dict[str, Any],\n                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            )\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                # on Windows tmp_dir can be in the form x\\y\\asdf~1\\z, do also try to replace is as is\n                val = val.replace(tmp_dir + os.path.sep, \"\")\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 self.fixup(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 = cast(\n                dict[str, Any],\n                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            )\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 cast(list[tuple[str, str]], 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 cast(list[tuple[str, str]], 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 sys\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 sys.platform in (\"win32\", \"darwin\"):\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 __based_version__\n\n\nclass GraphSuite(Suite):\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_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=__based_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(\"a\", None, \"import b, c\", manager),\n            \"d\": State(\"d\", None, \"pass\", manager),\n            \"b\": State(\"b\", None, \"import c\", manager),\n            \"c\": State(\"c\", None, \"import b, d\", manager),\n        }\n        res = sorted_components(graph)\n        assert_equal(res, [frozenset({\"d\"}), frozenset({\"c\", \"b\"}), frozenset({\"a\"})])\n\n    def test_order_ascc(self) -> None:\n        manager = self._make_manager()\n        graph = {\n            \"a\": State(\"a\", None, \"import b, c\", manager),\n            \"d\": State(\"d\", None, \"def f(): import a\", manager),\n            \"b\": State(\"b\", None, \"import c\", manager),\n            \"c\": State(\"c\", None, \"import b, d\", manager),\n        }\n        res = sorted_components(graph)\n        assert_equal(res, [frozenset({\"a\", \"d\", \"c\", \"b\"})])\n        ascc = res[0]\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    Node,\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.force_uppercase_builtins = 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        if isinstance(node.node, Node):\n            s = f\"{str(type(node.node).__name__)}<{self.id_mapper.id(node.node)}>\"\n        else:\n            s = f\"? ({type(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) + str(type_map[n]),\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 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 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 os\nfrom unittest import TestCase\n\nimport mypy\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"
  },
  {
    "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\nimport mypy.options\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\", \"--no-strict\", \"--hide-error-code-links\"]\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    mypy.options._based = False\n    os.environ[\"__MYPY_UNDER_TEST__\"] = \"2\"\n    out, err, returncode = api.run(mypy_cmdline)\n    os.environ[\"__MYPY_UNDER_TEST__\"] = \"1\"\n    mypy.options._based = True\n\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\nimport mypy.options\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, 10):\n        files.remove(\"parse-python310.test\")\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\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    mypy.options._based = False\n    options = Options()\n    mypy.options._based = True\n    options.force_uppercase_builtins = True\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    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\n        based = mypy.options._based\n        mypy.options._based = False\n        try:\n            a = n.str_with_options(options).split(\"\\n\")\n        finally:\n            mypy.options._based = based\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 != 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(\n            [\n                \"--no-error-summary\",\n                \"--hide-error-codes\",\n                \"--no-strict\",\n                \"--no-pretty\",\n                \"--hide-error-context\",\n                \"--no-color-output\",\n            ]\n        )\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                    line = line.replace(test_temp_dir + os.sep, test_temp_dir + \"/\")\n                    output.append(line.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\n\ndef test_mypy_path_is_respected() -> None:\n    assert False\n    packages = \"packages\"\n    pkg_name = \"a\"\n    with tempfile.TemporaryDirectory() as temp_dir:\n        old_dir = os.getcwd()\n        os.chdir(temp_dir)\n        try:\n            # Create the pkg for files to go into\n            full_pkg_name = os.path.join(temp_dir, packages, pkg_name)\n            os.makedirs(full_pkg_name)\n\n            # Create the empty __init__ file to declare a package\n            pkg_init_name = os.path.join(temp_dir, packages, pkg_name, \"__init__.py\")\n            open(pkg_init_name, \"w\", encoding=\"utf8\").close()\n\n            mypy_config_path = os.path.join(temp_dir, \"mypy.ini\")\n            with open(mypy_config_path, \"w\") as mypy_file:\n                mypy_file.write(\"[mypy]\\n\")\n                mypy_file.write(f\"mypy_path = ./{packages}\\n\")\n\n            with virtualenv() as venv:\n                venv_dir, python_executable = venv\n\n                cmd_line_args = []\n                if python_executable != sys.executable:\n                    cmd_line_args.append(f\"--python-executable={python_executable}\")\n                cmd_line_args.extend([\"--config-file\", mypy_config_path, \"--package\", pkg_name])\n\n                out, err, returncode = mypy.api.run(cmd_line_args)\n                assert returncode == 0\n        finally:\n            os.chdir(old_dir)\n"
  },
  {
    "path": "mypy/test/testplugins.py",
    "content": "import re\nfrom unittest import TestCase\n\nfrom mypy.plugins.re import _parse_groups\n\n\nclass TestRe(TestCase):\n    def test_parse_groups(self):\n        assert _parse_groups(\"\") == ()\n        assert _parse_groups(\"()\") == ((None, True),)\n        assert _parse_groups(\"(?:)\") == ()\n        assert _parse_groups(\"(?m)\") == ()\n        assert _parse_groups(\"()?\") == ((None, False),)\n        assert _parse_groups(\"()*\") == ((None, False),)\n\n        error = _parse_groups(\"(\")\n        assert isinstance(error, re.error)\n        assert error.msg == \"missing ), unterminated subpattern\"\n        assert _parse_groups(\"([\\\\'])\") == ((None, True),)\n        assert _parse_groups(\"(())?\") == ((None, False), (None, False))\n        assert _parse_groups(\"(()?)\") == ((None, True), (None, False))\n        assert _parse_groups(\"((())?)\") == ((None, True), (None, False), (None, False))\n\n        assert _parse_groups(\"()|()\") == ((None, False), (None, False))\n        assert _parse_groups(\"(()|())\") == ((None, True), (None, False), (None, False))\n        assert _parse_groups(\"(())(()|()())\") == (\n            (None, True),\n            (None, True),\n            (None, True),\n            (None, False),\n            (None, False),\n            (None, False),\n        )\n\n        assert _parse_groups(\"[()]\") == ()\n        assert _parse_groups(\"[]\\\\]()]\") == ()\n        assert _parse_groups(\"[^]()]\") == ()\n\n        assert _parse_groups(\"(?P<a>(?P<b>))(?P<c>(?P<d>)|(?P<e>)(?P<f>))\") == (\n            (\"a\", True),\n            (\"b\", True),\n            (\"c\", True),\n            (\"d\", False),\n            (\"e\", False),\n            (\"f\", False),\n        )\n        assert _parse_groups(\"(?P<n>a)(?(n)b)\") == ((\"n\", True),)\n\n        assert _parse_groups(\"(?=a(b)c)a\") == ((None, True),)\n        assert _parse_groups(\"(?!a(b)c)a\") == ((None, False),)\n        assert _parse_groups(\"(?#as(|[]]]|[((((\\\\)df)fdsa\") == ()\n        assert _parse_groups(\"(?#a)()\") == ((None, True),)\n        assert _parse_groups(\"(?#()()\") == ((None, True),)\n\n        assert _parse_groups(\"(?x)#()\\n(?#()()?\") == ((None, False),)\n        assert _parse_groups(\"#()\\n(?#()()?\", verbose=True) == ((None, False),)\n        assert _parse_groups(\"((?:#x))\") == ((None, True),)\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        \"--no-default-return\",\n        \"--show-traceback\",\n        \"--no-silence-site-packages\",\n        \"--no-error-summary\",\n        \"--hide-error-codes\",\n        \"--allow-empty-bodies\",\n        \"--no-infer-function-types\",\n        \"--force-uppercase-builtins\",\n        \"--no-strict\",\n        \"--no-pretty\",\n        \"--hide-error-context\",\n        \"--no-color-output\",\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 textwrap\n\nfrom mypy.report import CoberturaPackage, get_line_rate\nfrom mypy.test.helpers import Suite, assert_equal\n\ntry:\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            \"\"\"\\\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        \"\"\"\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\nimport sys\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.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\n# Semantic analysis test case description files.\nsemanal_files = find_test_files(\n    pattern=\"semanal-*.test\",\n    exclude=[\n        \"semanal-errors-python310.test\",\n        \"semanal-errors.test\",\n        \"semanal-typeinfo.test\",\n        \"semanal-symtable.test\",\n    ],\n)\n\n\nif sys.version_info < (3, 10):\n    semanal_files.remove(\"semanal-python310.test\")\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.force_uppercase_builtins = 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\"]\n    if sys.version_info >= (3, 10):\n        semanal_files.append(\"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 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            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 = str(typeinfos).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 __str__(self) -> str:\n        a: list[str] = [\"TypeInfoMap(\"]\n        for x, y in sorted(self.items()):\n            ti = (\"\\n\" + \"  \").join(str(y).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.uninhabited])\n        self.assert_solve([self.fx.t, self.fx.s], [], [self.fx.uninhabited, self.fx.uninhabited])\n        self.assert_solve(\n            [self.fx.t, self.fx.s],\n            [self.supc(self.fx.s, self.fx.a)],\n            [self.fx.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.uninhabited, self.fx.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.uninhabited, self.fx.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\nfrom mypy.util import getattr\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(\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_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\", \"stubgen-based.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        if \"based\" not in testcase.parent.name:\n            options.legacy = True\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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_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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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, legacy=True\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\n            mod.__name__, known_modules=[mod.__name__], module=mod, legacy=True\n        )\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(\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(\"bs4\") == \"types-beautifulsoup4\"\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 Iterator\nfrom types import FunctionType\nfrom typing import Any, Callable\n\nimport mypy.stubtest\nfrom mypy.stubtest import parse_options, test_stubs\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\nGeneric: _SpecialForm = ...\nProtocol: _SpecialForm = ...\nUnion: _SpecialForm = ...\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 Callable:\n    def __call__(self): ...\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\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, ...]): ...\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 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 run_stubtest_with_stderr(\n    stub: str, runtime: str, options: list[str], config_file: str | 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 not config_file:\n            config_file = \"[mypy]\"\n        config_file += \"\\nshow_error_code_links=false\\npretty=false\"\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()\n        outerr = io.StringIO()\n        mypy.options._based = False\n        with contextlib.redirect_stdout(output), contextlib.redirect_stderr(outerr):\n            test_stubs(parse_options([TEST_MODULE_NAME] + options), use_builtins_fixtures=True)\n        mypy.options._based = 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]]) -> FunctionType[..., 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_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\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\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            \"\"\",\n            runtime=\"\"\"\n            class Good:\n                @property\n                def read_only_attr(self): return 1\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            \"\"\",\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            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\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        if sys.version_info >= (3, 10):\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            from typing_extensions import Final, Literal\n            class BytesEnum(bytes, enum.Enum):\n                a = b'foo'\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\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_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\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\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_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_extensions 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_extensions 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_extensions 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_extensions import Protocol, TypedDict\",\n            runtime=\"from typing_extensions 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        if sys.version_info >= (3, 10):\n            yield Case(\n                stub=\"from typing import ParamSpec\",\n                runtime=\"from typing import ParamSpec\",\n                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_extensions import NamedTuple, TypedDict\",\n            runtime=\"from typing_extensions 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\n    @collect_cases\n    def test_no_param_defaults_bool_eval(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class Censored:\n                def __bool__(self) -> bool: ...\n            def snowflaky(sensitive_do_not_touch: Censored = ...) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Censored:\n                def __bool__(self) -> bool:  # never try this at home, kids\n                    raise ValueError\n            def snowflaky(sensitive_do_not_touch: Censored = Censored()) -> None: ...\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 argument \"number\" differs '\n            'from runtime argument \"num\"\\n'\n            f\"Stub: in file {TEST_MODULE_NAME}.pyi:1\\n\"\n            \"def (number: builtins.int, text: builtins.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 argument \"number\" differs from runtime argument \"num\"\\n'.format(TEST_MODULE_NAME)\n        )\n        assert output == expected\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                    \"\"\"\n                    def good() -> None: ...\n                    def bad(number: int) -> None: ...\n                    def also_bad(number: int) -> None: ...\n                    \"\"\".lstrip(\n                        \"\\n\"\n                    )\n                ),\n                runtime=textwrap.dedent(\n                    \"\"\"\n                    def good(): pass\n                    def bad(asdf): pass\n                    def also_bad(asdf): pass\n                    \"\"\".lstrip(\n                        \"\\n\"\n                    )\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_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, outerr = run_stubtest_with_stderr(\n            stub=stub, runtime=runtime, options=[], config_file=config_file\n        )\n        assert output == \"Success: no issues found in 1 module\\n\"\n        assert outerr == (\n            \"test_module_config.ini: [mypy]: disable_error_code: \"\n            \"Invalid error code(s): not-a-valid-name\\n\"\n        )\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, 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_callables(self):\n        c = self.fx.callable(self.fx.nonet)\n        n = self.fx.named_callable()\n        f = self.fx.function_()\n\n        self.assert_subtype(c, c)\n        self.assert_subtype(n, n)\n        self.assert_subtype(n, c)\n        self.assert_subtype(f, n)\n        self.assert_subtype(f, c)\n        self.assert_subtype(f, f)\n\n        self.assert_not_subtype(c, n)\n        self.assert_not_subtype(c, f)\n        self.assert_not_subtype(n, f)\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.force_uppercase_builtins = 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\nimport mypy.options\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            mypy.options._based = False\n            options = Options()\n            options.default_return = False\n            options.infer_function_types = False\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.force_uppercase_builtins = 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_simple, 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.options import Options\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_intersection, make_simplified_union, true_only\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    IntersectionType,\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        mypy.options._based = False\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_upper(self) -> None:\n        options = Options()\n        options.force_uppercase_builtins = True\n        assert_equal(TupleType([], self.fx.std_tuple).str_with_options(options), \"Tuple[()]\")\n        assert_equal(TupleType([self.x], self.fx.std_tuple).str_with_options(options), \"Tuple[X?]\")\n        assert_equal(\n            TupleType(\n                [self.x, AnyType(TypeOfAny.special_form)], self.fx.std_tuple\n            ).str_with_options(options),\n            \"Tuple[X?, Any]\",\n        )\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`1\",\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`1\",\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(A) == target\n        assert get_proper_type(target) == target\n\n        A, target = self.fx.def_alias_2(self.fx.a)\n        assert get_proper_type(A) == target\n        assert get_proper_type(target) == target\n\n    def test_type_alias_expand_all(self) -> None:\n        A, _ = self.fx.def_alias_1(self.fx.a)\n        assert A.expand_all_if_possible() is None\n        A, _ = self.fx.def_alias_2(self.fx.a)\n        assert A.expand_all_if_possible() is None\n\n        B = self.fx.non_rec_alias(self.fx.a)\n        C = self.fx.non_rec_alias(TupleType([B, B], Instance(self.fx.std_tuplei, [B])))\n        assert C.expand_all_if_possible() == TupleType(\n            [self.fx.a, self.fx.a], Instance(self.fx.std_tuplei, [self.fx.a])\n        )\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        assert is_proper_subtype(IntersectionType([fx.a, fx.b]), fx.a)\n        assert not is_proper_subtype(fx.a, IntersectionType([fx.a, fx.b]))\n        assert not is_proper_subtype(\n            IntersectionType([fx.a, fx.b]), IntersectionType([fx.a, fx.b, fx.c])\n        )\n        assert is_proper_subtype(IntersectionType([fx.a, fx.b]), IntersectionType([fx.a, fx.b]))\n        assert is_proper_subtype(\n            IntersectionType([fx.a, fx.b, fx.c]), IntersectionType([fx.a, fx.b])\n        )\n        assert not is_proper_subtype(\n            IntersectionType([fx.a, fx.b]), IntersectionType([fx.b, fx.c])\n        )\n        assert is_proper_subtype(IntersectionType([fx.a, fx.b]), IntersectionType([fx.b, fx.a]))\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    def test_simplified_intersection(self):\n        fx = self.fx\n\n        self.assert_simplified_intersection([fx.a, fx.a], fx.a)\n        self.assert_simplified_intersection([fx.a, fx.b], fx.b)\n        self.assert_simplified_intersection([fx.a, fx.d], IntersectionType([fx.a, fx.d]))\n        self.assert_simplified_intersection([fx.a, fx.uninhabited], fx.uninhabited)\n        self.assert_simplified_intersection([fx.ga, fx.gs2a], fx.gs2a)\n        self.assert_simplified_intersection([fx.ga, fx.gsab], IntersectionType([fx.ga, fx.gsab]))\n        self.assert_simplified_intersection([fx.ga, fx.gsba], fx.gsba)\n        self.assert_simplified_intersection(\n            [fx.a, IntersectionType([fx.d])], IntersectionType([fx.a, fx.d])\n        )\n        self.assert_simplified_intersection([fx.a, IntersectionType([fx.a])], fx.a)\n        self.assert_simplified_intersection(\n            [fx.b, IntersectionType([fx.c, IntersectionType([fx.d])])],\n            IntersectionType([fx.b, fx.c, fx.d]),\n        )\n\n    def assert_simplified_intersection(self, original: list[Type], intersection: Type) -> None:\n        assert_equal(make_simplified_intersection(original), intersection)\n        assert_equal(make_simplified_intersection(list(reversed(original))), intersection)\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        mypy.options._based = False\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        # join_simple against differently restricted truthiness types drops restrictions.\n        true_a = true_only(self.fx.a)\n        false_o = false_only(self.fx.o)\n        j = join_simple(self.fx.o, true_a, false_o)\n        assert j.can_be_true\n        assert j.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            self.tuple(UnpackType(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            self.tuple(UnpackType(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            self.tuple(UnpackType(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    # 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 = 12\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(\"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\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(\"typing.Callable\")  # function TODO\n        self.defi = self.make_type_info(\"types.FunctionType\")\n        self.named_callablei = self.make_type_info(\"typing._NamedCallable\")\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.def_ = Instance(self.defi, [])  # function TODO\n        self._named_callable = Instance(self.named_callablei, [])  # 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 named_callable(self) -> CallableType:\n        \"\"\"callable(a1, ..., an, r) constructs a callable with argument types\n        a1, ... an and return type r.\n        \"\"\"\n        return CallableType([], [], [], self.nonet, self._named_callable)\n\n    def function_(self) -> CallableType:\n        \"\"\"callable(a1, ..., an, r) constructs a callable with argument types\n        a1, ... an and return type r.\n        \"\"\"\n        return CallableType([], [], [], self.nonet, self.def_)\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\", -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\", -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\", -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/typetest/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/test/typetest/functools.py",
    "content": "from __future__ import annotations\n\nfrom functools import lru_cache\n\n# use `basedtyping` when we drop python 3.8\nfrom types import MethodType\nfrom typing import TYPE_CHECKING, Callable\nfrom typing_extensions import assert_type\n\nfrom mypy_extensions import Arg\n\n# use `functools.cache` when we drop python 3.8\ncache = lru_cache(None)\n\n\nclass A:\n    @cache\n    def m(self, a: list[int]): ...\n\n    @classmethod\n    @cache\n    def c(cls, a: list[int]): ...\n\n    @staticmethod\n    @cache\n    def s(a: list[int]): ...\n\n\n@cache\ndef f(a: list[int]): ...\n\n\nif TYPE_CHECKING:\n    from functools import _HashCallable, _LruCacheWrapperBase, _LruCacheWrapperMethod\n\n    ExpectedFunction = _LruCacheWrapperBase[Callable[[Arg(list[int], \"a\")], None]]\n    ExpectedMethod = _LruCacheWrapperMethod[Callable[[Arg(list[int], \"a\")], None]]\n    ExpectedMethodNone = _LruCacheWrapperMethod[\"() -> None\"]\n    a = A()\n    a.m([1])  # type: ignore[arg-type]\n    assert_type(a.m, ExpectedMethod)\n    assert_type(a.c, ExpectedMethod)\n    # this is wrong, it shouldn't eat the `a` argument, but this is because of mypy `staticmethod` special casing\n    assert_type(a.s, ExpectedMethodNone)\n    assert_type(a.s, MethodType & (_LruCacheWrapperBase[Callable[[Arg(list[int], \"a\")], None]] | _HashCallable))  # type: ignore[assert-type]\n    assert_type(f.__get__(1), ExpectedMethodNone)\n    f([1])  # type: ignore[arg-type]\n"
  },
  {
    "path": "mypy/test/typetest/operator.py",
    "content": "from operator import attrgetter\nfrom typing_extensions import assert_type\n\n\ndef check_attrgetter():\n    assert_type(attrgetter(\"name\"), attrgetter[object])\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\nfrom mypy.util import safe\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 = safe(comment_match.group(\"filename\"))\n            lineno = int(safe(comment_match.group(\"lineno\")))\n            severity = safe(comment_match.group(\"severity\"))\n            msg = safe(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    RaiseStmt,\n    ReturnStmt,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    StrExpr,\n    SuperExpr,\n    TryStmt,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\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\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_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_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\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 to skip 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_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_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 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 Optional, 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    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\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(Optional[FunctionLike], 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(Optional[FunctionLike], 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        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        )\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(Optional[TypeAliasExpr], 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_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.expr(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_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 typing import Optional, cast\n\nfrom mypy.nodes import (\n    ParamSpecExpr,\n    SymbolTableNode,\n    TypeVarExpr,\n    TypeVarLikeExpr,\n    TypeVarTupleExpr,\n)\nfrom mypy.types import (\n    ParamSpecFlavor,\n    ParamSpecType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n)\nfrom mypy.typetraverser import TypeTraverserVisitor\n\n\nclass TypeVarLikeNamespaceSetter(TypeTraverserVisitor):\n    \"\"\"Set namespace for all TypeVarLikeTypes types.\"\"\"\n\n    def __init__(self, namespace: str) -> None:\n        self.namespace = namespace\n\n    def visit_type_var(self, t: TypeVarType) -> None:\n        t.id.namespace = self.namespace\n        super().visit_type_var(t)\n\n    def visit_param_spec(self, t: ParamSpecType) -> None:\n        t.id.namespace = self.namespace\n        return super().visit_param_spec(t)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:\n        t.id.namespace = self.namespace\n        super().visit_type_var_tuple(t)\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 = cast(Optional[TypeVarLikeScope], 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, scopename: str | None = None\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        tvar_expr.default.accept(TypeVarLikeNamespaceSetter(namespace))\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=tvar_expr.default,\n                variance=tvar_expr.variance,\n                line=tvar_expr.line,\n                column=tvar_expr.column,\n                scopename=scopename,\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=tvar_expr.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=tvar_expr.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, Callable, 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    IntersectionType,\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    TypeGuardType,\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\")\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_intersection_type(self, t: IntersectionType) -> 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    def visit_typeguard_type(self, t: TypeGuardType) -> T:\n        raise NotImplementedError\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        result = Instance(\n            typ=t.type,\n            args=self.translate_types(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        result.metadata = t.metadata\n        return result\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_types(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_types(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_types(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_types(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 visit_intersection_type(self, t: IntersectionType) -> Type:\n        return IntersectionType(self.translate_types(t.items), t.line, t.column)\n\n    def translate_types(self, types: Iterable[Type]) -> list[Type]:\n        return [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(t.item.accept(self), line=t.line, column=t.column)\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 re-used 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, strategy: Callable[[list[T]], T]) -> None:\n        self.strategy = strategy\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        # 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 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.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_intersection_type(self, t: IntersectionType, /) -> 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        # Skip type aliases already visited types to avoid infinite recursion.\n        # TODO: Ideally we should fire subvisitors here (or use caching) if we care\n        #       about duplicates.\n        if t in self.seen_aliases:\n            return self.strategy([])\n        self.seen_aliases.add(t)\n        if self.skip_alias_target:\n            return self.query_types(t.args)\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 re-used 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])\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.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_intersection_type(self, t: IntersectionType) -> 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        # Skip type aliases already visited types to avoid infinite recursion.\n        # TODO: Ideally we should fire subvisitors here (or use caching) if we care\n        #       about duplicates.\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        if self.skip_alias_target:\n            return self.query_types(t.args)\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 Iterable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom typing import Callable, Final, Protocol, TypeVar\n\nimport mypy.options\nfrom mypy import errorcodes as codes, message_registry, nodes\nfrom mypy.errorcodes import ErrorCode\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    FakeInfo,\n    FuncBase,\n    FuncDef,\n    FuncItem,\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_arg_names,\n    get_nongen_builtins,\n)\nfrom mypy.options import INLINE_TYPEDDICT, 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    FINAL_TYPE_NAMES,\n    LITERAL_TYPE_NAMES,\n    NEVER_NAMES,\n    TYPE_ALIAS_NAMES,\n    AnyType,\n    BoolTypeQuery,\n    CallableArgument,\n    CallableType,\n    DeletedType,\n    EllipsisType,\n    ErasedType,\n    Instance,\n    IntersectionType,\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    TypeGuardType,\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    UntypedType,\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    \"basedtyping.Intersection\",\n    \"basedtyping.FunctionType\",\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\nGENERIC_STUB_NOT_AT_RUNTIME_TYPES: Final = {\n    \"queue.Queue\",\n    \"builtins._PathLike\",\n    \"asyncio.futures.Future\",\n}\n\nCALLABLE_NAME = \"typing.Callable\"\nCALLABLE_TYPE: Instance | None = None\n\"\"\"Very hacky way to globally access this special cased type\"\"\"\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.always_allow_new_syntax = api.is_stub_file\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\ndef no_subscript_builtin_alias(name: str, propose_alt: bool = True) -> str:\n    class_name = name.split(\".\")[-1]\n    msg = f'\"{class_name}\" is not subscriptable'\n    # This should never be called if the python_version is 3.9 or newer\n    nongen_builtins = get_nongen_builtins((3, 8))\n    replacement = nongen_builtins[name]\n    if replacement and propose_alt:\n        msg += f', use \"{replacement}\" instead'\n    return msg\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    @contextmanager\n    def string_type(self) -> Iterator[None]:\n        always_allow_new_syntax = self.always_allow_new_syntax\n        self.always_allow_new_syntax = True\n        try:\n            yield\n        finally:\n            self.always_allow_new_syntax = always_allow_new_syntax\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            if (\n                fullname in get_nongen_builtins(self.options.python_version)\n                and t.args\n                and not self.always_allow_new_syntax\n            ):\n                self.fail(\n                    no_subscript_builtin_alias(fullname, propose_alt=not self.defining_alias), t\n                )\n            tvar_def = self.tvar_scope.get_binding(sym)\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(\n                    line=t.line, column=t.column, scopename=tvar_def.scopename\n                )\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)\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\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 (\"typing_extensions.Concatenate\", \"typing.Concatenate\"):\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]) -> 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:\n            return []\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\" or fullname == \"builtins.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 == \"typing.Tuple\" or (\n            fullname == \"builtins.tuple\"\n            and (self.always_allow_new_syntax or self.options.python_version >= (3, 9))\n        ):\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)\n        elif fullname == \"basedtyping.Intersection\":\n            items = self.anal_array(t.args)\n            return IntersectionType.make_intersection(items)\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 == \"typing._NamedCallable\":\n            return self.analyze_callable_type(t, fullname)\n        elif fullname in {\"basedtyping.FunctionType\", \"basedtyping.BuiltinFunctionType\"}:\n            return self.analyze_callable_type(t, type_name=fullname)\n        elif fullname in {\"types.FunctionType\", \"types.BuiltinFunctionType\"}:\n            if not self.always_allow_new_syntax and not self.python_3_12_type_alias and t.args:\n                name = fullname.rsplit(\".\")[-1]\n                self.fail(\n                    f'Type parameters for \"{name}\" requires `from __future__ import annotations` or quoted types',\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                self.note('Or you can use \"basedtyping.FunctionType\" instead', t)\n            return self.analyze_callable_type(t, type_name=fullname)\n        elif fullname == \"typing.Type\" or (\n            fullname == \"builtins.type\"\n            and (self.always_allow_new_syntax or self.options.python_version >= (3, 9))\n        ):\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 == \"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 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 (\"typing.Unpack\", \"typing_extensions.Unpack\"):\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 == \"basedtyping.Untyped\":\n            return UntypedType(TypeOfAny.explicit)\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:\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        ):\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        if info.is_type_check_only and not self.always_allow_new_syntax:\n            message = message_registry.TYPE_CHECK_ONLY.format(info.name)\n            self.fail(message.value, ctx, code=message.code)\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        if len(info.type_vars) == 1 and info.has_param_spec_type:\n            instance.args = tuple(self.pack_paramspec_args(instance.args))\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.VALID_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        # Based: we permit things like `def foo(x: Color.RED) -> None: ...`\n        if (\n            isinstance(sym.node, Var)\n            and sym.node.info\n            and sym.node.info.is_enum\n            and not sym.node.name.startswith(\"__\")\n        ):\n            value = sym.node.name\n            # it's invalid to use in an expression, ie: a TypeAlias\n            if not defining_literal:\n                if not self.options.bare_literals:\n                    base_enum_short_name = sym.node.info.name\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                if t.expression:\n                    base_enum_short_name = sym.node.info.name\n                    name = f\"{base_enum_short_name}.{value}\"\n                    msg = message_registry.INVALID_BARE_LITERAL.format(name)\n                    self.fail(msg.value, t, code=msg.code)\n            result = 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                bare_literal=not defining_literal,\n            )\n            if t.expression:\n                return result\n            return result.accept(self)\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://kotlinisland.github.io/basedmypy/\"\n                \"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            old_report_invalid_types = self.report_invalid_types\n            try:\n                params = self.analyze_callable_args(t)\n            finally:\n                self.report_invalid_types = old_report_invalid_types\n            if params:\n                ts, kinds, names = params\n                # bind these types\n                return Parameters(\n                    self.anal_array(ts, allow_unpack=self.allow_unpack),\n                    kinds,\n                    names,\n                    line=t.line,\n                    column=t.column,\n                )\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            first_arg = t.arg_names[0] if t.arg_names and t.arg_kinds[0].is_positional() else None\n            if isinstance(t.definition, FuncDef) and t.definition.info:\n                # old typeguard on a class is checked later\n                first_arg = \"first argument\"\n            type_guard = self.anal_type_guard(t.ret_type, first_arg=first_arg)\n            type_is = self.anal_type_is(t.ret_type)\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            use_callable = False\n            definition = t.definition\n            if definition:\n                assert isinstance(definition, FuncBase)\n                use_callable = definition.is_static and definition.name != \"__new__\"\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                fallback=(\n                    t.fallback\n                    if not isinstance(t.fallback.type, FakeInfo)\n                    else (\n                        # Ah yes, we pretend that static methods are `Callable`, not `FunctionType`\n                        #  so that you can subtype it with a `classmethod`, because that makes sense!\n                        self.named_type(\"typing.Callable\")\n                        if use_callable\n                        else self.named_type(t.fallback.type.msg)\n                    )\n                ),\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, first_arg: str | None = None) -> TypeGuardType | None:\n        proper = get_proper_type(t)\n        if isinstance(proper, TypeGuardType):\n            if not self.always_allow_new_syntax and proper.is_evaluated:\n                self.fail(\n                    \"You need to put quotes around the entire type-guard, or enable `__future__.annotations`\",\n                    t,\n                )\n            return proper.copy_modified(type_guard=self.anal_type(proper.type_guard))\n        elif isinstance(t, UnboundType):\n            sym = self.lookup_qualified(t.name, t)\n            if sym is not None and sym.node is not None:\n                result = self.anal_type_guard_arg(t, sym.node.fullname)\n                if result is None or isinstance(get_proper_type(result), AnyType):\n                    return None\n                return TypeGuardType(first_arg or \"first argument\", result)\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 not mypy.options._based and 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        result = TupleType(self.anal_array(t.items, allow_unpack=True), fallback, t.line)\n        if (\n            self.nesting_level\n            and t.implicit\n            and not self.always_allow_new_syntax\n            and self.options.bare_literals\n        ):\n            self.fail(\n                f'\"{result}\" is a bare literal and shouldn\\'t be used in a type operation without'\n                ' \"__future__.annotations\"',\n                t,\n                code=codes.VALID_TYPE,\n            )\n        return result\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        # Based: signatures like \"foo(x: 20) -> None\" are legal, this method\n        # generates and returns an actual LiteralType instead.\n\n        if self.report_invalid_types:\n            msg = None\n            if t.base_type_name in (\"builtins.int\", \"builtins.bool\"):\n                if not self.options.bare_literals:\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                if t.expression and not self.python_3_12_type_alias:\n                    msg = message_registry.INVALID_BARE_LITERAL.value.format(t.literal_value)\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            if msg:\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        if t.base_type_name in (\"builtins.int\", \"builtins.bool\"):\n            v = t.literal_value\n            assert v is not None\n            result = LiteralType(\n                v,\n                fallback=self.named_type(t.base_type_name),\n                line=t.line,\n                column=t.column,\n                bare_literal=True,\n            )\n            if t.expression:\n                return result\n            return result.accept(self)\n        return AnyType(TypeOfAny.from_error, line=t.line, column=t.column)\n\n    def visit_literal_type(self, t: LiteralType) -> Type:\n        if (\n            self.nesting_level\n            and t.bare_literal\n            and not self.always_allow_new_syntax\n            and self.options.bare_literals\n        ):\n            self.fail(\n                f'\"{t}\" is a bare literal and shouldn\\'t be used in a type operation without'\n                ' \"__future__.annotations\"',\n                t,\n                code=codes.VALID_TYPE,\n            )\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(\n                \"`X | Y` syntax for unions requires Python 3.10 or above\", t, code=codes.VALID_TYPE\n            )\n        return UnionType(self.anal_array(t.items), t.line, uses_pep604_syntax=t.uses_pep604_syntax)\n\n    def visit_intersection_type(self, t: IntersectionType) -> Type:\n        if (\n            t.uses_based_syntax is True\n            and t.is_evaluated is True\n            and not self.always_allow_new_syntax\n            and not self.python_3_12_type_alias\n        ):\n            self.fail(\n                \"`X & Y` syntax for intersections requires `from __future__ import annotations` or quoted types\",\n                t,\n                code=codes.VALID_TYPE,\n            )\n        return IntersectionType(self.anal_array(t.items), t.line)\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(self.anal_type(t.item), line=t.line)\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 visit_typeguard_type(self, t: TypeGuardType) -> Instance:\n        return self.named_type(\"builtins.bool\")\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 (\"typing_extensions.Concatenate\", \"typing.Concatenate\"):\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_name: str = CALLABLE_NAME) -> Type:\n        fallback = self.named_type(\n            \"builtins.function\"\n            if type_name in {\"basedtyping.FunctionType\", \"types.FunctionType\"}\n            else type_name\n        )\n        if len(t.args) == 0:\n            # Callable (bare). Treat as Callable[..., Any].\n            any_type = self.get_omitted_any(t, type_name)\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(self.tvar_scope.bind_new(name, tvar_expr))\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://kotlinisland.github.io/basedmypy/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, (\"typing_extensions.Unpack\", \"typing.Unpack\"))\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_arg_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: CallableType | FuncItem\n    ) -> tuple[Sequence[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(\n                    var.name,\n                    var_expr,\n                    scopename=var.scopename if isinstance(var, TypeVarType) else None,\n                )\n                defs.append(binding)\n            return 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                self.fail(\n                    f'Type variable \"{name}\" is bound by an outer class',\n                    defn,\n                    code=codes.VALID_TYPE,\n                )\n            binding = self.tvar_scope.bind_new(name, tvar, scopename=defn.name)\n            defs.append(binding)\n\n        for name, tvar in typevars:\n            # update inner type vars\n            typ = get_proper_type(tvar.upper_bound)\n            # TODO: use a visitor to work properly\n            if isinstance(typ, Instance):\n                # We only `accept` `UnboundType` here to catch `TypeVar`s,\n                #  other things could be sus\n                typ.args = tuple(\n                    it.accept(self) if isinstance(it, UnboundType) else it for it in typ.args\n                )\n                # HACK: put tvar deps at the start of the arg list\n                for arg in reversed(typ.args):\n                    if isinstance(arg, TypeVarType):\n                        try:\n                            index = defs.index(arg)\n                        except ValueError:\n                            pass\n                        else:\n                            defs.insert(0, defs.pop(index))\n                            # re-id the typevars\n                            last_id = arg.id.raw_id\n                            for i, arg in enumerate(defs[:index]):\n                                arg.id.raw_id = defs[i + 1].id.raw_id\n                            defs[index].id.raw_id = last_id\n            if isinstance(typ, UnboundType):\n                tvar.upper_bound = tvar.upper_bound.accept(self)\n\n        return 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        old_report_invalid_types = self.report_invalid_types\n        self.report_invalid_types = True\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            self.report_invalid_types = old_report_invalid_types\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                scopename=var_def.scopename,\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 Unpack in a type is not allowed\", final_unpack)\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__(self, __msg: str, __ctx: Context, *, code: ErrorCode | None = None) -> 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        nongen_builtins = get_nongen_builtins(options.python_version)\n        if fullname in nongen_builtins:\n            typ = orig_type\n            # We use a dedicated error message for builtin generics (as the most common case).\n            alternative = nongen_builtins[fullname]\n            fail(\n                message_registry.IMPLICIT_GENERIC_ANY_BUILTIN.format(alternative),\n                typ,\n                code=codes.TYPE_ARG,\n            )\n        elif fullname not in {\"types.FunctionType\", \"types.BuiltinFunctionType\"}:\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            base_type = get_proper_type(orig_type)\n            base_fullname = (\n                base_type.type.fullname if isinstance(base_type, Instance) else fullname\n            )\n            # Ideally, we'd check whether the type is quoted or `from __future__ annotations`\n            # is set before issuing this note\n            if (\n                options.python_version < (3, 9)\n                and base_fullname in GENERIC_STUB_NOT_AT_RUNTIME_TYPES\n            ):\n                # Recommend `from __future__ import annotations` or to put type in quotes\n                # (string literal escaping) for classes not generic at runtime\n                note(\n                    \"Subscripting classes that are not generic at runtime may require \"\n                    \"escaping, see https://kotlinisland.github.io/basedmypy/runtime_troubles.html\"\n                    \"#not-generic-runtime\",\n                    typ,\n                    code=codes.TYPE_ARG,\n                )\n        else:\n            typ = orig_type\n\n        any_type = UntypedType(TypeOfAny.from_omitted_generics, line=typ.line, column=typ.column)\n    else:\n        any_type = UntypedType(\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        arg_count = 0\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    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        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:\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(TypeQuery[bool]):\n    def __init__(self) -> None:\n        super().__init__(any)\n\n    def visit_any(self, t: AnyType) -> bool:\n        return t.type_of_any == TypeOfAny.explicit and not isinstance(t, UntypedType)\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 __init__(self) -> None:\n        super().__init__(self.combine_lists_strategy)\n\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    @classmethod\n    def combine_lists_strategy(cls, it: Iterable[list[Type]]) -> list[Type]:\n        return list(itertools.chain.from_iterable(it))\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, empty_tuple_index: 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    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 and (arg_count < min_tv_count or arg_count > max_tv_count):\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            t.invalid = True\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.seen_aliases: set[TypeAliasType] | None = None\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])\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_intersection_type(self, t: IntersectionType) -> None:\n        self.process_types(t.items)\n\n    def visit_overloaded(self, t: Overloaded) -> None:\n        self.process_types(t.items)  # type: ignore[arg-type]\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        # Skip type aliases in already visited types to avoid infinite recursion.\n        if self.seen_aliases is None:\n            self.seen_aliases = set()\n        elif t in self.seen_aliases:\n            return\n        self.seen_aliases.add(t)\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"
  },
  {
    "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 Iterable, Sequence\nfrom typing import Any, TypeVar, cast\n\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_OPT,\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    TypeInfo,\n    Var,\n)\nfrom mypy.state import state\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    ExtraAttrs,\n    FormalArgument,\n    FunctionLike,\n    Instance,\n    IntersectionType,\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    UntypedType,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n)\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, default_self: Instance | TupleType) -> Type | None:\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_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    default_self = fill_typevars(info)\n    if not is_new and not info.is_newtype:\n        orig_self_types = [get_self_type(it, default_self) 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=default_self,\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))\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    fallback: Instance | None = None,\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    from mypy.typeanal import CALLABLE_TYPE\n\n    assert CALLABLE_TYPE\n    if not fallback:\n        fallback = CALLABLE_TYPE\n    if isinstance(method, Overloaded):\n        items = []\n        original_type = get_proper_type(original_type)\n        for c in method.items:\n            if isinstance(original_type, Instance):\n                # Filter based on whether declared self type can match actual object type.\n                # For example, if self has type C[int] and method is accessed on a C[str] value,\n                # omit this item. This is best effort since bind_self can be called in many\n                # contexts, and doing complete validation might trigger infinite recursion.\n                #\n                # Note that overload item filtering normally happens elsewhere. This is needed\n                # at least during constraint inference.\n                keep = is_valid_self_type_best_effort(c, original_type)\n            else:\n                keep = True\n            if keep:\n                items.append(bind_self(c, original_type, is_classmethod, ignore_instances))\n        if len(items) == 0:\n            # If no item matches, returning all items helps avoid some spurious errors\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 = method\n    if not func.arg_types:\n        # Invalid method, return something.\n        return cast(F, func.copy_modified(fallback=fallback))\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        # TODO: MethodType\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 cast(F, func.copy_modified(fallback=fallback))\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    original_type = get_proper_type(original_type)\n    if isinstance(original_type, CallableType) and original_type.is_type_obj():\n        original_type = TypeType.make_normalized(original_type.ret_type)\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        bound_args=[original_type],\n        fallback=fallback,\n    )\n    return cast(F, res)\n\n\ndef is_valid_self_type_best_effort(c: CallableType, self_type: Instance) -> bool:\n    \"\"\"Quickly check if self_type might match the self in a callable.\n\n    Avoid performing any complex type operations. This is performance-critical.\n\n    Default to returning True if we don't know (or it would be too expensive).\n    \"\"\"\n    if (\n        self_type.args\n        and c.arg_types\n        and isinstance((arg_type := get_proper_type(c.arg_types[0])), Instance)\n        and c.arg_kinds[0] in (ARG_POS, ARG_OPT)\n        and arg_type.args\n        and self_type.type.fullname != \"functools._SingleDispatchCallable\"\n    ):\n        if self_type.type is not arg_type.type:\n            # We can't map to supertype, since it could trigger expensive checks for\n            # protocol types, so we consevatively assume this is fine.\n            return True\n\n        # Fast path: no explicit annotation on self\n        if all(\n            (\n                type(arg) is TypeVarType\n                and type(arg.upper_bound) is Instance\n                and arg.upper_bound.type.fullname == \"builtins.object\"\n            )\n            for arg in arg_type.args\n        ):\n            return True\n\n        from mypy.meet import is_overlapping_types\n\n        return is_overlapping_types(self_type, c.arg_types[0])\n    return True\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)\n    return t\n\n\ndef callable_corresponding_argument(\n    typ: NormalizedCallableType | Parameters, model: FormalArgument\n) -> FormalArgument | None:\n    \"\"\"Return the argument 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(__a: int = ..., *, a: int = ...) -> None: ...\n        from mypy.subtypes import is_equivalent\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            and is_equivalent(by_name.typ, by_pos.typ)\n        ):\n            return FormalArgument(by_name.name, by_pos.pos, by_name.typ, False)\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        if extra_attrs_set is not None and len(extra_attrs_set) > 1:\n            fallback = try_getting_instance_fallback(result)\n            if fallback:\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                    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(tj, Instance)\n                        and tj.last_known_value is not None\n                        and not (\n                            isinstance(proper_ti, Instance)\n                            and 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 make_simplified_intersection(\n    items: Sequence[Type], line: int = -1, column: int = -1, *, keep_erased: bool = False\n) -> ProperType:\n    \"\"\"Build intersection type with redundant intersection items removed.\n\n    If only a single item remains, this may return a non-intersection type.\n\n    Examples:\n\n    * [int, str] -> Intersection[int, str]\n    * [int, object] -> int\n    * [int, int] -> int\n    * [int, Any] -> Intersection[int, Any] (Any types are not simplified away!)\n    * [Any, Any] -> Any\n    * [int, Intersection[bytes, str]] -> Intersection[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 intersection types\n    containing type variables. If set to True, keep all ErasedType items.\n    \"\"\"\n    # Step 1: expand all nested unions\n    items = flatten_nested_unions(items, type_type=IntersectionType)\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 intersections\n    simplified_set: Sequence[Type] = _remove_redundant_intersection_items(items, keep_erased)\n\n    result = get_proper_type(IntersectionType.make_intersection(simplified_set, line, column))\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    if extra_attrs_set is not None and len(extra_attrs_set) > 1:\n        fallback = try_getting_instance_fallback(result)\n        if fallback:\n            fallback.extra_attrs = None\n\n    return result\n\n\ndef _remove_redundant_intersection_items(items: list[Type], keep_erased: bool) -> list[Type]:\n    from mypy.subtypes import is_proper_subtype\n\n    removed: set[int] = set()\n\n    for outer_i in range(len(items)):\n        proper_outer = get_proper_type(items[outer_i])\n        for inner_i in range(outer_i + 1, len(items)):\n            if inner_i in removed:\n                continue\n            proper_inner = get_proper_type(items[inner_i])\n            if is_proper_subtype(\n                proper_outer, proper_inner, keep_erased_types=keep_erased, ignore_promotions=True\n            ):\n                removed.add(inner_i)\n            elif is_proper_subtype(\n                proper_inner, proper_outer, keep_erased_types=keep_erased, ignore_promotions=True\n            ):\n                removed.add(outer_i)\n\n    return [items[i] for i in range(len(items)) if i not in removed]\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:\n                return UninhabitedType(line=t.line)\n        elif isinstance(t, LiteralType) and t.is_enum_literal():\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            # Broken overloads can have self.type set to None.\n            # TODO: should we instead always set the type in semantic analyzer?\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 (not fdef.is_static or fdef.name == \"__new__\") 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] + [UntypedType()] * (len(fdef.arg_names) - 1)\n    else:\n        args = [UntypedType()] * len(fdef.arg_names)\n\n    return CallableType(\n        args,\n        fdef.arg_kinds,\n        fdef.arg_names,\n        ret_type or UntypedType(),\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_type(typ: Type) -> bool:\n    \"\"\"Returns 'true' if this type is a \"singleton type\" -- if there exists\n    exactly only one runtime value associated with this type.\n\n    That is, given two values 'a' and 'b' that have the same type 't',\n    'is_singleton_type(t)' returns True if and only if the expression 'a is b' is\n    always true.\n\n    Currently, this returns True when given NoneTypes, enum LiteralTypes,\n    enum types with a single value and ... (Ellipses).\n\n    Note that other kinds of LiteralTypes cannot count as singleton types. For\n    example, suppose we do 'a = 100000 + 1' and 'b = 100001'. It is not guaranteed\n    that 'a is b' will always be true -- some implementations of Python will end up\n    constructing two distinct instances of 100001.\n    \"\"\"\n    typ = get_proper_type(typ)\n    return typ.is_singleton_type()\n\n\ndef try_expanding_sum_type_to_union(typ: Type, target_fullname: str) -> ProperType:\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_enum_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        items = [\n            try_expanding_sum_type_to_union(item, target_fullname) for item in typ.relevant_items()\n        ]\n        return make_simplified_union(items, contract_literals=False)\n\n    if isinstance(typ, Instance) and typ.type.fullname == target_fullname:\n        if typ.type.fullname == \"builtins.bool\":\n            items = [LiteralType(True, typ), LiteralType(False, typ)]\n            return make_simplified_union(items, contract_literals=False)\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 make_simplified_union(items, contract_literals=False)\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    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__(self._merge)\n        self.include_all = include_all\n\n    def _merge(self, iter: Iterable[list[TypeVarLikeType]]) -> list[TypeVarLikeType]:\n        out = []\n        for item in iter:\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 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, IntersectionType):\n        return any(custom_special_method(t, name, check_all) 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, 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):\n        return None  # Fast path for None, which is common\n    elif isinstance(typ, FunctionLike):\n        return typ.fallback\n    elif isinstance(typ, TupleType):\n        return typ.partial_fallback\n    elif isinstance(typ, TypedDictType):\n        return typ.fallback\n    elif isinstance(typ, TypeVarType):\n        return try_getting_instance_fallback(typ.upper_bound)\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(left: Instance, member: str, class_obj: bool) -> ProperType | None:\n    if member == \"__call__\" and class_obj:\n        # Special case: class objects always have __call__ that is just the constructor.\n        from mypy.checkmember import type_object_type\n\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():\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    return get_proper_type(find_member(member, left, left, class_obj=class_obj))\n\n\nclass _get_type_type_item_Exception(Exception):  # noqa: N801\n    \"\"\"Would prefer this to be defined within the function, but mypyc doesn't support that.\"\"\"\n\n\ndef get_type_type_item(t: ProperType) -> Type | None:\n    def inner(t: Type) -> Type:\n        proper_t = get_proper_type(t)\n        if isinstance(proper_t, UnionType):\n            return UnionType([inner(it) for it in proper_t.items])\n        elif isinstance(proper_t, IntersectionType):\n            return IntersectionType([inner(it) for it in proper_t.items])\n        elif isinstance(proper_t, TypeType):\n            return proper_t.item\n        raise _get_type_type_item_Exception\n\n    try:\n        return inner(t)\n    except _get_type_type_item_Exception:\n        return None\n\n\ndef is_callable(t: ProperType) -> t is FunctionLike | Instance if True else False:\n    return isinstance(t, FunctionLike) or isinstance(t, Instance) and \"__call__\" in t.type.names\n"
  },
  {
    "path": "mypy/types.py",
    "content": "\"\"\"Classes for representing mypy types.\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport sys\nfrom abc import abstractmethod\nfrom collections.abc import Generator, Iterable, Sequence\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    ClassVar,\n    Final,\n    NamedTuple,\n    NewType,\n    Optional,\n    TypeVar,\n    Union,\n    cast,\n    overload,\n)\nfrom typing_extensions import Self, TypeAlias as _TypeAlias\n\nimport mypy.nodes\nimport mypy.options\nfrom mypy.bogus_type import Bogus\nfrom mypy.nodes import (\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    INVARIANT,\n    ArgKind,\n    FakeInfo,\n    FuncDef,\n    SymbolNode,\n)\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 = Union[int, str, bool, float]\n\n\n# If we only import type_visitor in the middle of the file, mypy\n# breaks, and if we do it at the top, it breaks at runtime because of\n# import cycle issues, so we do it at the top while typechecking and\n# then again in the middle at runtime.\n# We should be able to remove this once we are switched to the new\n# semantic analyzer!\nif TYPE_CHECKING:\n    from mypy.type_visitor import (\n        SyntheticTypeVisitor as SyntheticTypeVisitor,\n        TypeVisitor as TypeVisitor,\n    )\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 @deprecated type names\nDEPRECATED_TYPE_NAMES: Final = (\"warnings.deprecated\", \"typing_extensions.deprecated\")\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\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 is_singleton_type(self) -> bool:\n        return False\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 = {v.id: s for (v, s) in zip(self.alias.alias_tvars, self.args)}\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        new_tp = self.alias.target.accept(InstantiateAliasVisitor(mapping))\n        new_tp.accept(LocationSetter(self.line, self.column))\n        new_tp.line = self.line\n        new_tp.column = self.column\n        return new_tp\n\n    def _partial_expansion(self, nothing_args: bool = False) -> tuple[ProperType, bool]:\n        # Private method mostly for debugging and testing.\n        unroller = UnrollAliasVisitor(set(), {})\n        if nothing_args:\n            alias = self.copy_modified(args=[UninhabitedType()] * len(self.args))\n        else:\n            alias = self\n        unrolled = alias.accept(unroller)\n        assert isinstance(unrolled, ProperType)\n        return unrolled, unroller.recursed\n\n    def expand_all_if_possible(self, nothing_args: bool = False) -> ProperType | None:\n        \"\"\"Attempt a full expansion of the type alias (including nested aliases).\n\n        If the expansion is not possible, i.e. the alias is (mutually-)recursive,\n        return None. If nothing_args is True, replace all type arguments with an\n        UninhabitedType() (used to detect recursively defined aliases).\n        \"\"\"\n        unrolled, recursed = self._partial_expansion(nothing_args=nothing_args)\n        if recursed:\n            return None\n        return unrolled\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.expand_all_if_possible(nothing_args=True) is None\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 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 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\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\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: 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        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 hash((self.raw_id, self.meta_level, 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\nclass TypeVarType(TypeVarLikeType):\n    \"\"\"Type that refers to a type variable.\"\"\"\n\n    __slots__ = (\"values\", \"variance\", \"scopename\")\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        scopename: str | None = None,\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        self.scopename = scopename\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        scopename: Bogus[str | None] = _dummy,\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            scopename=self.scopename if scopename == _dummy else scopename,\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            \"scopename\": self.scopename,\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            scopename=data[\"scopename\"],\n        )\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\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 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        \"expression\",\n    )\n\n    def __init__(\n        self,\n        name: str,\n        args: Sequence[Type] | None = None,\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        expression=False,\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        self.expression = expression\n        \"\"\"This is used to ban bare Enum literals from expressions like ``TypeAlias``es\"\"\"\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        if self.original_str_expr and hasattr(visitor, \"string_type\"):\n            with visitor.string_type():\n                return visitor.visit_unbound_type(self)\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\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    @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\": type(self).__name__,\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\"] == cls.__name__\n        source = data[\"source_any\"]\n        return cls(\n            type_of_any=data[\"type_of_any\"],\n            source_any=cast(AnyType, deserialize_type(source)) if source is not None else None,\n            missing_import_name=data[\"missing_import_name\"],\n        )\n\n    def describe(self) -> str:\n        if not mypy.options._based:\n            return \"Any\"\n\n        def describe_type_of_any(type_of_any: int = self.type_of_any) -> str | None:\n            if type_of_any == TypeOfAny.unannotated:\n                return \"unannotated\"\n            elif type_of_any == TypeOfAny.explicit:\n                return None\n            elif type_of_any == TypeOfAny.from_unimported_type:\n                return \"from unimported type\"\n            elif type_of_any == TypeOfAny.from_omitted_generics:\n                return \"from omitted generics\"\n            elif type_of_any == TypeOfAny.from_error:\n                return \"from error\"\n            elif type_of_any == TypeOfAny.special_form:\n                return None\n            elif type_of_any == TypeOfAny.from_another_any:\n                return (\n                    describe_type_of_any(self.source_any.type_of_any) if self.source_any else None\n                )\n            elif type_of_any == TypeOfAny.implementation_artifact:\n                return \"from a limitation\"\n            elif type_of_any == TypeOfAny.suggestion_engine:\n                return \"from a suggestion\"\n            assert False, f\"unreachable: {type_of_any}\"\n\n        description = self.__class__.__name__.split(\"Type\")[0]\n        type_of = describe_type_of_any()\n        if type_of:\n            return f\"{description} ({type_of})\"\n        return description\n\n\nclass UntypedType(AnyType):\n    def __init__(\n        self,\n        type_of_any: int = TypeOfAny.unannotated,\n        source_any: AnyType | None = None,\n        missing_import_name: str | None = None,\n        line: int = -1,\n        column: int = -1,\n    ):\n        super().__init__(\n            type_of_any,\n            source_any=source_any,\n            missing_import_name=missing_import_name,\n            line=line,\n            column=column,\n        )\n\n    def describe(self) -> str:\n        if not mypy.options._based:\n            return super().describe()\n        return \"Untyped\"\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)\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, UninhabitedType)\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\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 is_singleton_type(self) -> bool:\n        return True\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\nclass TypeGuardType(ProperType):\n    \"\"\"Based\"\"\"\n\n    __slots__ = (\n        \"target\",\n        \"type_guard\",\n        \"is_evaluated\",\n        \"only_true\",\n        \"original_str_expr\",\n        \"original_str_fallback\",\n    )\n\n    def __init__(self, target: str | int, type_guard: Type, is_evaluated=True, only_true=False):\n        super().__init__(line=type_guard.line, column=type_guard.column)\n        self.target = target\n        self.type_guard = type_guard\n        self.is_evaluated = is_evaluated\n        self.only_true = only_true\n        self.original_str_expr: str | None = None\n        self.original_str_fallback: str | None = None\n\n    def __repr__(self) -> str:\n        result = f\"{self.target_desc} is {self.type_guard}\"\n        if self.only_true:\n            result += \" if True else False\"\n        return result\n\n    def copy_modified(self, type_guard: Bogus[Type] = _dummy) -> TypeGuardType:\n        return TypeGuardType(\n            self.target,\n            type_guard if type_guard is not _dummy else self.type_guard,\n            self.is_evaluated,\n            self.only_true,\n        )\n\n    @property\n    def target_desc(self) -> str | int:\n        \"\"\"User message representation of the target\"\"\"\n        if isinstance(self.target_value, int):\n            if self.target_is_self:\n                return \"instance argument\"\n            elif self.target_is_class:\n                return \"class argument\"\n            return f\"argument {self.target_value + 1}\"\n        return self.target_value\n\n    @property\n    def target_value(self) -> int | str:\n        \"\"\"arg name representation of the target\"\"\"\n        if self.target_is_class:\n            assert isinstance(self.target, str)\n            result = self.target[len(\"class@\") :]\n            if result.isnumeric():\n                return int(result)\n            return result\n        elif self.target_is_self:\n            assert isinstance(self.target, str)\n            result = self.target[len(\"self@\") :]\n            if result.isnumeric():\n                return int(result)\n            return result\n        return self.target\n\n    @property\n    def target_is_class(self) -> bool:\n        return isinstance(self.target, str) and self.target.startswith(\"class@\")\n\n    @property\n    def target_is_self(self) -> bool:\n        return isinstance(self.target, str) and self.target.startswith(\"self@\")\n\n    @property\n    def target_is_positional(self) -> bool:\n        return isinstance(self.target_value, int) or self.target_value[0].isdigit()\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        try:\n            return visitor.visit_typeguard_type(self)\n        except NotImplementedError:\n            return self.type_guard.accept(visitor)\n\n    def serialize(self) -> JsonDict | str:\n        return {\n            \".class\": \"TypeGuardType\",\n            \"target\": self.target,\n            \"type_guard\": self.type_guard.serialize(),\n            \"only_true\": self.only_true,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeGuardType:\n        assert data[\".class\"] == \"TypeGuardType\"\n        return TypeGuardType(\n            data[\"target\"], deserialize_type(data[\"type_guard\"]), only_true=data[\"only_true\"]\n        )\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\": list(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\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__ = (\n        \"type\",\n        \"args\",\n        \"invalid\",\n        \"type_ref\",\n        \"last_known_value\",\n        \"_hash\",\n        \"extra_attrs\",\n        \"metadata\",\n    )\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        # True if recovered after incorrect number of type arguments error\n        self.invalid = False\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        self.metadata: dict[str, object] = {}\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:\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 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        # We intentionally don't copy the extra_attrs here, so they will be erased.\n        new.can_be_true = self.can_be_true\n        new.can_be_false = self.can_be_false\n        new.metadata = self.metadata.copy()\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    def is_singleton_type(self) -> bool:\n        # TODO:\n        # Also make this return True if the type corresponds to NotImplemented?\n        return (\n            self.type.is_enum\n            and len(self.type.enum_members) == 1\n            or self.type.fullname in {\"builtins.ellipsis\", \"types.EllipsisType\"}\n        )\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    @property\n    def prefix(self) -> str:\n        if self.is_function:\n            return \"def \"\n        elif self.is_method:\n            return \"MethodType \"\n        elif self.is_named:\n            return \"_NamedCallable & \"\n        return \"\"\n\n    @property\n    def fallback_name(self) -> str:\n        return self.fallback.type.fullname\n\n    @property\n    def is_callable(self) -> bool:\n        return self.fallback.type.fullname in {\"typing.Callable\", \"collections.abc.Callable\"}\n\n    @property\n    def is_function(self) -> bool:\n        return self.fallback.type.fullname in {\"builtins.function\", \"types.FunctionType\"}\n\n    @property\n    def is_method(self) -> bool:\n        return self.fallback.type.fullname == \"types.MethodType\"\n\n    @property\n    def is_named(self) -> bool:\n        return self.fallback.type.fullname == \"typing._NamedCallable\"\n\n\nclass FormalArgument(NamedTuple):\n    name: str | None\n    pos: int | None\n    typ: Type\n    required: bool\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            [ArgKind(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 __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, CallableType)):\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        \"bound_args\",  # Bound type args, mostly unused but may be useful for\n        # tools that consume mypy ASTs\n        \"def_extras\",  # Information about original definition we want to serialize.\n        # This is used for more detailed error messages.\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        \"fully_typed\",  # If all type positions are filled.\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        bound_args: Sequence[Type | None] = (),\n        def_extras: dict[str, Any] | None = None,\n        type_guard: TypeGuardType | 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        for t, k in zip(arg_types, arg_kinds):\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        if variables is None:\n            variables = []\n        self.arg_types = list(arg_types)\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        self.definition = definition\n        self.variables = 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        if not bound_args:\n            bound_args = ()\n        self.bound_args = bound_args\n        if def_extras:\n            self.def_extras = def_extras\n        elif isinstance(definition, FuncDef):\n            # This information would be lost if we don't have definition\n            # after serialization, but it is useful in error messages.\n            # TODO: decide how to add more info here (file, line, column)\n            # without changing interface hash.\n            first_arg: str | None = None\n            if definition.arg_names and definition.info and not definition.is_static:\n                if getattr(definition, \"arguments\", None):\n                    first_arg = definition.arguments[0].variable.name\n                else:\n                    first_arg = definition.arg_names[0]\n            self.def_extras = {\"first_arg\": first_arg}\n        else:\n            self.def_extras = {}\n        self.type_guard = type_guard\n        self.type_is = type_is\n        self.unpack_kwargs = unpack_kwargs\n        self.fully_typed = not (\n            any(is_unannotated_any(arg) for arg in arg_types) or is_unannotated_any(ret_type)\n        )\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] = _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        bound_args: Bogus[list[Type | None]] = _dummy,\n        def_extras: Bogus[dict[str, Any]] = _dummy,\n        type_guard: Bogus[TypeGuardType | 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            bound_args=bound_args if bound_args is not _dummy else self.bound_args,\n            def_extras=def_extras if def_extras is not _dummy else dict(self.def_extras),\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        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 = cast(Union[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-nomralized 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        # self.is_type_obj() will fail if self.fallback.type is a FakeInfo\n        if isinstance(self.fallback.type, FakeInfo):\n            is_type_obj = 2\n        else:\n            is_type_obj = self.is_type_obj()\n        return hash(\n            (\n                self.ret_type,\n                is_type_obj,\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_type_obj() == other.is_type_obj()\n                and self.is_ellipsis_args == other.is_ellipsis_args\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            \"bound_args\": [(None if t is None else t.serialize()) for t in self.bound_args],\n            \"def_extras\": dict(self.def_extras),\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        # TODO: Set definition to the containing SymbolNode?\n        return CallableType(\n            [deserialize_type(t) for t in data[\"arg_types\"]],\n            [ArgKind(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            bound_args=[(None if t is None else deserialize_type(t)) for t in data[\"bound_args\"]],\n            def_extras=data[\"def_extras\"],\n            type_guard=(\n                cast(TypeGuardType, deserialize_type(data[\"type_guard\"]))\n                if data[\"type_guard\"] is not None\n                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\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\nclass NamedOverloaded(Overloaded):\n    slots = (\"_name\",)\n\n    def __init__(self, items: list[CallableType], name: str):\n        self._name = name\n        super().__init__(items)\n\n    def get_name(self) -> str:\n        return self._name\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"NamedOverloaded\",\n            \"items\": [t.serialize() for t in self.items],\n            \"_name\": self._name,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> NamedOverloaded:\n        assert data[\".class\"] == \"NamedOverloaded\"\n        return NamedOverloaded([CallableType.deserialize(t) for t in data[\"items\"]], data[\"_name\"])\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 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    @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 as_anonymous(self) -> TypedDictType:\n        if self.is_anonymous():\n            return self\n        assert self.fallback.type.typeddict_type is not None\n        return self.fallback.type.typeddict_type.as_anonymous()\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 create_anonymous_fallback(self) -> Instance:\n        anonymous = self.as_anonymous()\n        return anonymous.fallback\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\", \"expression\")\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        expression=False,\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        self.expression = expression\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\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\", \"bare_literal\")\n\n    def __init__(\n        self,\n        value: LiteralValue,\n        fallback: Instance,\n        line: int = -1,\n        column: int = -1,\n        bare_literal=False,\n    ) -> None:\n        super().__init__(line, column)\n        self.value = value\n        self.fallback = fallback\n        self._hash = -1  # Cached hash value\n        self.bare_literal = bare_literal\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        if self._hash == -1:\n            self._hash = hash((self.value, self.fallback))\n        return self._hash\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, LiteralType):\n            return self.fallback == other.fallback and self.value == other.value\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 is_singleton_type(self) -> bool:\n        return self.is_enum_literal() or isinstance(self.value, bool)\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        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\nclass IntersectionType(ProperType):\n    \"\"\"Experimental intersection type\"\"\"\n\n    __slots__ = (\n        \"items\",\n        \"is_evaluated\",\n        \"uses_based_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        is_evaluated=True,\n        uses_based_syntax=False,\n    ):\n        super().__init__(line, column)\n        self.items = flatten_nested_unions(\n            items, type_type=IntersectionType, handle_type_alias_type=False\n        )\n        self.can_be_true = any(item.can_be_true for item in items)\n        self.can_be_false = any(item.can_be_false for item in items)\n        self.is_evaluated = is_evaluated\n        self.uses_based_syntax = uses_based_syntax\n\n        self.original_str_expr: str | None = None\n        self.original_str_fallback: str | None = None\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, IntersectionType):\n            return NotImplemented\n        return frozenset(self.items) == frozenset(other.items)\n\n    @overload\n    @staticmethod\n    def make_intersection(\n        items: Sequence[ProperType], line: int = ..., column: int = ...\n    ) -> ProperType: ...\n\n    @overload\n    @staticmethod\n    def make_intersection(items: Sequence[Type], line: int = ..., column: int = ...) -> Type: ...\n\n    @staticmethod\n    def make_intersection(items: Sequence[Type], line: int = -1, column: int = -1) -> Type:\n        if len(items) > 1:\n            return IntersectionType(items, line, column)\n        elif len(items) == 1:\n            return items[0]\n        else:\n            return UninhabitedType()\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_intersection_type(self)\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"IntersectionType\", \"items\": [t.serialize() for t in self.items]}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> IntersectionType:\n        assert data[\".class\"] == \"IntersectionType\"\n        return IntersectionType([deserialize_type(t) for t in data[\"items\"]])\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].\n\n    This annotates variables that are class objects, constrained by\n    the type argument.  See PEP 484 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\",)\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    def __init__(\n        self,\n        item: Bogus[Instance | AnyType | TypeVarType | TupleType | NoneType | CallableType],\n        *,\n        line: int = -1,\n        column: int = -1,\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\n    @staticmethod\n    def make_normalized(item: Type, *, line: int = -1, column: int = -1) -> ProperType:\n        item = get_proper_type(item)\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        if isinstance(item, IntersectionType):\n            return IntersectionType.make_intersection(\n                [TypeType.make_normalized(intersection_item) for intersection_item in item.items],\n                line=line,\n                column=column,\n            )\n        return TypeType(item, line=line, column=column)  # 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\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"TypeType\", \"item\": self.item.serialize()}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Type:\n        assert data[\".class\"] == \"TypeType\"\n        return TypeType.make_normalized(deserialize_type(data[\"item\"]))\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    if isinstance(typ, TypeGuardedType):  # type: ignore[misc]\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(\n            isinstance(t, (TypeAliasType, TypeGuardedType)) for t in typelist  # type: ignore[misc]\n        ):\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)\nfrom mypy.typetraverser import TypeTraverserVisitor\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    \"\"\"\n\n    def __init__(self, id_mapper: IdMapper | None = None, *, options: Options) -> None:\n        self.id_mapper = id_mapper\n        self.any_as_dots = False\n        self.options = options\n        self._own_type_vars: Sequence[TypeVarLikeType] = []\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        if self.any_as_dots and t.type_of_any == TypeOfAny.special_form:\n            return \"...\"\n        return t.describe()\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        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            if mypy.options._based:\n                s = str(t.last_known_value.accept(self))\n            else:\n                s = f\"{t.last_known_value.accept(self)}?\"\n        else:\n            s = t.type.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\n        return self.strip_builtins(s)\n\n    @staticmethod\n    def strip_builtins(s: str) -> str:\n        if mypy.options._based:\n            if s.startswith(\"builtins.\"):\n                return s.partition(\".\")[2]\n        return s\n\n    @contextlib.contextmanager\n    def own_type_vars(\n        self, type_vars: Sequence[TypeVarLikeType] | None\n    ) -> Generator[None, None, None]:\n        if not mypy.options._based:\n            yield\n        else:\n            previous = self._own_type_vars\n            self._own_type_vars = type_vars or []\n            yield\n            self._own_type_vars = previous\n\n    def visit_type_var(self, t: TypeVarType, /) -> str:\n        if t.name is None:\n            # Anonymous type variable type (only numeric id).\n            s = f\"`{t.id}\"\n        else:\n            # Named type variable type.\n            if mypy.options._based:\n                if t.scopename:\n                    if t in self._own_type_vars:\n                        s = t.name\n                    else:\n                        s = f\"{t.name}@{t.scopename}\"\n                else:\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():\n            s += f\" = {t.default.accept(self)}\"\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 t.name is None:\n            # Anonymous type variable type (only numeric id).\n            s += f\"`{t.id}\"\n        else:\n            # Named type variable type.\n            s += f\"{t.name_with_suffix()}`{t.id}\"\n        if t.prefix.arg_types:\n            s += \"]\"\n        if t.has_default():\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 t.name is None:\n            # Anonymous type variable type (only numeric id).\n            s = f\"`{t.id}\"\n        else:\n            # Named type variable type.\n            s = f\"{t.name}`{t.id}\"\n        if t.has_default():\n            s += f\" = {t.default.accept(self)}\"\n        return s\n\n    def visit_callable_type(self, t: CallableType, /) -> str:\n        if t.fallback.type and t.fallback_name == \"types.BuiltinFunctionType\":\n            # ah yes\n            return self.visit_instance(\n                t.fallback.copy_modified(\n                    args=[Parameters(t.arg_types, t.arg_kinds, t.arg_names), t.ret_type]\n                )\n            )\n        with self.own_type_vars(t.variables):\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 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                    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                    if mypy.options._based:\n                        s += f\" -> {t.type_guard.target_desc} is {t.type_guard.type_guard.accept(self)}\"\n                        if t.type_guard.only_true:\n                            s += \" if True else False\"\n                    else:\n                        s += f\" -> TypeGuard[{t.type_guard.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            elif mypy.options._based:\n                s += \" -> None\"\n\n            s = self.render_callable_type_params(t, lambda x: x.accept(self)) + s\n\n            if not mypy.options._based:\n                return f\"def {s}\"\n            if not t.fallback.type:\n                # stupid test case moment\n                return \"def \" + s\n            return t.prefix + s\n\n    def render_callable_type_params(self, t: CallableType, renderer: Callable[[Type], str]) -> str:\n        if not t.variables:\n            return \"\"\n        vs = []\n        for var in t.variables:\n            if isinstance(var, TypeVarType):\n                # We reimplement TypeVarType.__repr__ here in order to support id_mapper.\n                if (\n                    mypy.options._based\n                    and var.scopename\n                    and t.name\n                    and var.scopename != t.name.split(\" \")[0]\n                ):\n                    name = f\"{var.name} (from {var.scopename})\"\n                else:\n                    name = var.name\n                if var.values:\n                    vals = f\"({', '.join(renderer(val) for val in var.values)})\"\n                    vs.append(f\"{name} in {vals}\")\n                elif not is_named_instance(var.upper_bound, \"builtins.object\"):\n                    if mypy.options._based:\n                        sep = \":\"\n                    else:\n                        sep = \" <:\"\n                    vs.append(\n                        f\"{name}{sep} {renderer(var.upper_bound)}{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        return f\"[{', '.join(vs)}] \"\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)\n        tuple_name = \"tuple\" if self.options.use_lowercase_names() else \"Tuple\"\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_name}[{s or '()'}, fallback={t.partial_fallback.accept(self)}]\"\n        if not mypy.options._based:\n            return f\"{tuple_name}[{s or '()'}]\"\n        return f\"({s})\" if len(t.items) != 1 else f\"({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                prefix = repr(t.fallback.type.fullname) + \", \"\n        return f\"TypedDict({prefix}{s})\"\n\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> str:\n        return repr(t.literal_value)\n\n    def visit_literal_type(self, t: LiteralType, /) -> str:\n        if mypy.options._based:\n            return t.value_repr()\n        return f\"Literal[{t.value_repr()}]\"\n\n    def visit_union_type(self, t: UnionType, /) -> str:\n        if not mypy.options._based:\n            s = self.list_str(t.items)\n            return f\"Union[{s}]\"\n        return self.union_str(t.items)\n\n    def visit_intersection_type(self, t: IntersectionType) -> str:\n        return \" & \".join(t.accept(self) for t in t.items)\n\n    def visit_partial_type(self, t: PartialType, /) -> str:\n        if t.type is None:\n            return \"partially defined: ? | None\"\n        else:\n            return \"partially defined: {}[{}]\".format(\n                t.type.name, \", \".join([\"?\"] * len(t.type.type_vars))\n            )\n\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> str:\n        return \"...\"\n\n    def visit_type_type(self, t: TypeType, /) -> str:\n        if self.options.use_lowercase_names():\n            type_name = \"type\"\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 not None:\n            unrolled, recursed = t._partial_expansion()\n            self.any_as_dots = recursed\n            type_str = unrolled.accept(self)\n            self.any_as_dots = False\n            return type_str\n        return \"<alias (unfixed)>\"\n\n    def visit_unpack_type(self, t: UnpackType, /) -> str:\n        return f\"Unpack[{t.type.accept(self)}]\"\n\n    def list_str(self, a: Iterable[Type]) -> 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            res.append(t.accept(self))\n        return \", \".join(res)\n\n    def union_str(self, a: Iterable[Type]) -> 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            res.append(t.accept(self))\n        if not mypy.options._based:\n            return f\"Union[{self.list_str(a)}]\"\n        return \" | \".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 UnrollAliasVisitor(TrivialSyntheticTypeTranslator):\n    def __init__(\n        self, initial_aliases: set[TypeAliasType], cache: dict[Type, Type] | None\n    ) -> None:\n        assert cache is not None\n        super().__init__(cache)\n        self.recursed = False\n        self.initial_aliases = initial_aliases\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        if t in self.initial_aliases:\n            self.recursed = True\n            return AnyType(TypeOfAny.special_form)\n        # Create a new visitor on encountering a new type alias, so that an alias like\n        #     A = Tuple[B, B]\n        #     B = int\n        # will not be detected as recursive on the second encounter of B.\n        subvisitor = UnrollAliasVisitor(self.initial_aliases | {t}, self.cache)\n        result = get_proper_type(t).accept(subvisitor)\n        if subvisitor.recursed:\n            self.recursed = True\n        return result\n\n\ndef is_named_instance(\n    t: Type, fullnames: str | tuple[str, ...]\n) -> t is Instance if True else False:\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 LocationSetter(TypeTraverserVisitor):\n    # TODO: Should we update locations of other Type subclasses?\n    def __init__(self, line: int, column: int) -> None:\n        self.line = line\n        self.column = column\n\n    def visit_instance(self, typ: Instance) -> None:\n        typ.line = self.line\n        typ.column = self.column\n        super().visit_instance(typ)\n\n    def visit_type_alias_type(self, typ: TypeAliasType) -> None:\n        typ.line = self.line\n        typ.column = self.column\n        super().visit_type_alias_type(typ)\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],\n    *,\n    handle_type_alias_type: bool = True,\n    handle_recursive: bool = True,\n    type_type: type[UnionType | IntersectionType] = UnionType,\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, type_type)) 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:\n            if not handle_recursive and isinstance(t, TypeAliasType) 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, type_type):\n            flat_items.extend(\n                flatten_nested_unions(\n                    cast(Union[UnionType, IntersectionType], tp).items,\n                    handle_type_alias_type=handle_type_alias_type,\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 = cast(Optional[int], 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: Sequence[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        res.extend(flatten_nested_tuples(p_type.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 is_unannotated_any(t: Type) -> t is AnyType if True else False:\n    if not isinstance(t, ProperType):\n        return False\n    return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated\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# 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 Iterable\nfrom typing import Callable, 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    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    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-\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_dummy_thread: 3.0-3.8\n_dummy_threading: 3.0-3.8\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-\nabc: 3.0-\naifc: 3.0-3.12\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.mixins: 3.10-\nasyncio.runners: 3.7-\nasyncio.staggered: 3.8-\nasyncio.taskgroups: 3.11-\nasyncio.threads: 3.9-\nasyncio.timeouts: 3.11-\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-\nconcurrent: 3.2-\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-\ndummy_threading: 3.0-3.8\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-\nencodings.mac_centeuro: 3.0-3.8\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-\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-\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-\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": "from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\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 Literal\n\nif sys.version_info >= (3, 12):\n    from ast import ParamSpec as ParamSpec, TypeVar as TypeVar, TypeVarTuple as TypeVarTuple, type_param as type_param\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        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\nif sys.version_info < (3, 9):\n    from ast import (\n        AugLoad as AugLoad,\n        AugStore as AugStore,\n        ExtSlice as ExtSlice,\n        Index as Index,\n        Param as Param,\n        Suite as Suite,\n        slice as slice,\n    )\n\nPyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192]\nPyCF_ONLY_AST: Literal[1024]\nPyCF_TYPE_COMMENTS: Literal[4096]\n\nif sys.version_info >= (3, 13):\n    PyCF_OPTIMIZED_AST: Literal[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\nfrom typing import Any, Literal, TextIO, TypeVar\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_TaskYieldType: TypeAlias = Future[object] | None\n\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: ...\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    if sys.version_info >= (3, 9):\n        def cancel(self, msg: Any | None = None) -> bool: ...\n    else:\n        def cancel(self) -> bool: ...\n\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 12):\n    _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co]\nelif sys.version_info >= (3, 9):\n    _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co]\nelse:\n    _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_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.\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 = ...,\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 = ...,\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 = ...\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    if sys.version_info < (3, 9):\n        @classmethod\n        def current_task(cls, loop: AbstractEventLoop | None = None) -> Task[Any] | None: ...\n        @classmethod\n        def all_tasks(cls, loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ...\n    if sys.version_info >= (3, 9):\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"
  },
  {
    "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\nfrom typing_extensions import Self\n\nBLAKE2B_MAX_DIGEST_SIZE: int = 64\nBLAKE2B_MAX_KEY_SIZE: int = 64\nBLAKE2B_PERSON_SIZE: int = 16\nBLAKE2B_SALT_SIZE: int = 16\nBLAKE2S_MAX_DIGEST_SIZE: int = 32\nBLAKE2S_MAX_KEY_SIZE: int = 32\nBLAKE2S_PERSON_SIZE: int = 8\nBLAKE2S_SALT_SIZE: int = 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, 9):\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    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        ) -> 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, 9):\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    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        ) -> 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]: ...\n\nif sys.version_info >= (3, 9):\n    def raw_unicode_escape_decode(\n        data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /\n    ) -> tuple[str, int]: ...\n\nelse:\n    def raw_unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\n\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]: ...\n\nif sys.version_info >= (3, 9):\n    def unicode_escape_decode(\n        data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /\n    ) -> tuple[str, int]: ...\n\nelse:\n    def unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\n\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\n    AbstractSet as Set,\n    AsyncGenerator as AsyncGenerator,\n    AsyncIterable as AsyncIterable,\n    AsyncIterator as AsyncIterator,\n    Awaitable as Awaitable,\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]\nif sys.version_info < (3, 14):\n    from typing import ByteString as ByteString  # noqa: Y057\n\n    __all__ += [\"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: ...   # type: ignore[override]\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: ...   # type: ignore[override]\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        @abstractmethod\n        def __buffer__(self, flags: int, /) -> memoryview: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_compat_pickle.pyi",
    "content": "IMPORT_MAPPING: dict[str, str]\nNAME_MAPPING: dict[tuple[str, str], tuple[str, str]]\nPYTHON2_EXCEPTIONS: tuple[str, ...]\nMULTIPROCESSING_EXCEPTIONS: tuple[str, ...]\nREVERSE_IMPORT_MAPPING: dict[str, str]\nREVERSE_NAME_MAPPING: dict[tuple[str, str], tuple[str, str]]\nPYTHON3_OSERROR_EXCEPTIONS: tuple[str, ...]\nPYTHON3_IMPORTERROR_EXCEPTIONS: tuple[str, ...]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_compression.pyi",
    "content": "from _typeshed import WriteableBuffer\nfrom collections.abc import Callable\nfrom io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase\nfrom typing import Any, Protocol\n\nBUFFER_SIZE = DEFAULT_BUFFER_SIZE\n\nclass _Reader(Protocol):\n    def read(self, n: int, /) -> bytes: ...\n    def seekable(self) -> bool: ...\n    def seek(self, n: int, /) -> Any: ...\n\nclass BaseStream(BufferedIOBase): ...\n\nclass DecompressReader(RawIOBase):\n    def __init__(\n        self,\n        fp: _Reader,\n        decomp_factory: Callable[..., object],\n        trailing_error: type[Exception] | tuple[type[Exception], ...] = (),\n        **decomp_args: Any,\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 typing import Any, ClassVar, Generic, TypeVar, final, overload\nfrom typing_extensions import ParamSpec, Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    if sys.version_info >= (3, 9):\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\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  # type: ignore[override]\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, type_check_only\nfrom typing_extensions import Self, TypeAlias\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\n# Ideally this would be `QUOTE_ALL | QUOTE_MINIMAL | QUOTE_NONE | QUOTE_NONNUMERIC`\n# However, using literals in situations like these can cause false-positives (see #7258)\n_QuotingType: TypeAlias = int\n\nclass Error(Exception): ...\n\n_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect]\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 __new__(\n        cls,\n        dialect: _DialectLike | 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    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    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    csvfile: SupportsWrite[str],\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    csvfile: Iterable[str],\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    dialect: type[Dialect | csv.Dialect] = ...,\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 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 typing import Any, ClassVar, Generic, TypeVar, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n_T = TypeVar(\"_T\")\n_CT = TypeVar(\"_CT\", bound=_CData)\n\nFUNCFLAG_CDECL: int\nFUNCFLAG_PYTHONAPI: int\nFUNCFLAG_USE_ERRNO: int\nFUNCFLAG_USE_LASTERROR: int\nRTLD_GLOBAL: int\nRTLD_LOCAL: int\n\nif sys.version_info >= (3, 11):\n    CTYPES_MAX_ARGCOUNT: int\n\nif sys.version_info >= (3, 12):\n    SIZEOF_TIME_T: 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: int\n    FUNCFLAG_STDCALL: int\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\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\nclass _CanCastTo(_CData): ...\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: Any, /) -> 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, /) -> list[Any]: ...\n    def __setitem__(self, key: int, value: Any, /) -> None: ...\n\n@overload\ndef POINTER(type: None, /) -> type[c_void_p]: ...\n@overload\ndef POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ...\ndef 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\ndef byref(obj: _CData | _CDataType, offset: int = ...) -> _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\n# This class is not exposed. It calls itself _ctypes.CField.\n@final\n@type_check_only\nclass _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    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, /) -> list[Any]: ...\n    @overload\n    def __setitem__(self, key: int, value: Any, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice, 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    if sys.version_info >= (3, 9):\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, 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: int\nACS_BLOCK: int\nACS_BOARD: int\nACS_BSBS: int\nACS_BSSB: int\nACS_BSSS: int\nACS_BTEE: int\nACS_BULLET: int\nACS_CKBOARD: int\nACS_DARROW: int\nACS_DEGREE: int\nACS_DIAMOND: int\nACS_GEQUAL: int\nACS_HLINE: int\nACS_LANTERN: int\nACS_LARROW: int\nACS_LEQUAL: int\nACS_LLCORNER: int\nACS_LRCORNER: int\nACS_LTEE: int\nACS_NEQUAL: int\nACS_PI: int\nACS_PLMINUS: int\nACS_PLUS: int\nACS_RARROW: int\nACS_RTEE: int\nACS_S1: int\nACS_S3: int\nACS_S7: int\nACS_S9: int\nACS_SBBS: int\nACS_SBSB: int\nACS_SBSS: int\nACS_SSBB: int\nACS_SSBS: int\nACS_SSSB: int\nACS_SSSS: int\nACS_STERLING: int\nACS_TTEE: int\nACS_UARROW: int\nACS_ULCORNER: int\nACS_URCORNER: int\nACS_VLINE: int\nALL_MOUSE_EVENTS: int\nA_ALTCHARSET: int\nA_ATTRIBUTES: int\nA_BLINK: int\nA_BOLD: int\nA_CHARTEXT: int\nA_COLOR: int\nA_DIM: int\nA_HORIZONTAL: int\nA_INVIS: int\nA_ITALIC: int\nA_LEFT: int\nA_LOW: int\nA_NORMAL: int\nA_PROTECT: int\nA_REVERSE: int\nA_RIGHT: int\nA_STANDOUT: int\nA_TOP: int\nA_UNDERLINE: int\nA_VERTICAL: int\nBUTTON1_CLICKED: int\nBUTTON1_DOUBLE_CLICKED: int\nBUTTON1_PRESSED: int\nBUTTON1_RELEASED: int\nBUTTON1_TRIPLE_CLICKED: int\nBUTTON2_CLICKED: int\nBUTTON2_DOUBLE_CLICKED: int\nBUTTON2_PRESSED: int\nBUTTON2_RELEASED: int\nBUTTON2_TRIPLE_CLICKED: int\nBUTTON3_CLICKED: int\nBUTTON3_DOUBLE_CLICKED: int\nBUTTON3_PRESSED: int\nBUTTON3_RELEASED: int\nBUTTON3_TRIPLE_CLICKED: int\nBUTTON4_CLICKED: int\nBUTTON4_DOUBLE_CLICKED: int\nBUTTON4_PRESSED: int\nBUTTON4_RELEASED: int\nBUTTON4_TRIPLE_CLICKED: int\n# Darwin ncurses doesn't provide BUTTON5_* constants\nif sys.version_info >= (3, 10) and sys.platform != \"darwin\":\n    BUTTON5_PRESSED: int\n    BUTTON5_RELEASED: int\n    BUTTON5_CLICKED: int\n    BUTTON5_DOUBLE_CLICKED: int\n    BUTTON5_TRIPLE_CLICKED: int\nBUTTON_ALT: int\nBUTTON_CTRL: int\nBUTTON_SHIFT: int\nCOLOR_BLACK: int\nCOLOR_BLUE: int\nCOLOR_CYAN: int\nCOLOR_GREEN: int\nCOLOR_MAGENTA: int\nCOLOR_RED: int\nCOLOR_WHITE: int\nCOLOR_YELLOW: int\nERR: int\nKEY_A1: int\nKEY_A3: int\nKEY_B2: int\nKEY_BACKSPACE: int\nKEY_BEG: int\nKEY_BREAK: int\nKEY_BTAB: int\nKEY_C1: int\nKEY_C3: int\nKEY_CANCEL: int\nKEY_CATAB: int\nKEY_CLEAR: int\nKEY_CLOSE: int\nKEY_COMMAND: int\nKEY_COPY: int\nKEY_CREATE: int\nKEY_CTAB: int\nKEY_DC: int\nKEY_DL: int\nKEY_DOWN: int\nKEY_EIC: int\nKEY_END: int\nKEY_ENTER: int\nKEY_EOL: int\nKEY_EOS: int\nKEY_EXIT: int\nKEY_F0: int\nKEY_F1: int\nKEY_F10: int\nKEY_F11: int\nKEY_F12: int\nKEY_F13: int\nKEY_F14: int\nKEY_F15: int\nKEY_F16: int\nKEY_F17: int\nKEY_F18: int\nKEY_F19: int\nKEY_F2: int\nKEY_F20: int\nKEY_F21: int\nKEY_F22: int\nKEY_F23: int\nKEY_F24: int\nKEY_F25: int\nKEY_F26: int\nKEY_F27: int\nKEY_F28: int\nKEY_F29: int\nKEY_F3: int\nKEY_F30: int\nKEY_F31: int\nKEY_F32: int\nKEY_F33: int\nKEY_F34: int\nKEY_F35: int\nKEY_F36: int\nKEY_F37: int\nKEY_F38: int\nKEY_F39: int\nKEY_F4: int\nKEY_F40: int\nKEY_F41: int\nKEY_F42: int\nKEY_F43: int\nKEY_F44: int\nKEY_F45: int\nKEY_F46: int\nKEY_F47: int\nKEY_F48: int\nKEY_F49: int\nKEY_F5: int\nKEY_F50: int\nKEY_F51: int\nKEY_F52: int\nKEY_F53: int\nKEY_F54: int\nKEY_F55: int\nKEY_F56: int\nKEY_F57: int\nKEY_F58: int\nKEY_F59: int\nKEY_F6: int\nKEY_F60: int\nKEY_F61: int\nKEY_F62: int\nKEY_F63: int\nKEY_F7: int\nKEY_F8: int\nKEY_F9: int\nKEY_FIND: int\nKEY_HELP: int\nKEY_HOME: int\nKEY_IC: int\nKEY_IL: int\nKEY_LEFT: int\nKEY_LL: int\nKEY_MARK: int\nKEY_MAX: int\nKEY_MESSAGE: int\nKEY_MIN: int\nKEY_MOUSE: int\nKEY_MOVE: int\nKEY_NEXT: int\nKEY_NPAGE: int\nKEY_OPEN: int\nKEY_OPTIONS: int\nKEY_PPAGE: int\nKEY_PREVIOUS: int\nKEY_PRINT: int\nKEY_REDO: int\nKEY_REFERENCE: int\nKEY_REFRESH: int\nKEY_REPLACE: int\nKEY_RESET: int\nKEY_RESIZE: int\nKEY_RESTART: int\nKEY_RESUME: int\nKEY_RIGHT: int\nKEY_SAVE: int\nKEY_SBEG: int\nKEY_SCANCEL: int\nKEY_SCOMMAND: int\nKEY_SCOPY: int\nKEY_SCREATE: int\nKEY_SDC: int\nKEY_SDL: int\nKEY_SELECT: int\nKEY_SEND: int\nKEY_SEOL: int\nKEY_SEXIT: int\nKEY_SF: int\nKEY_SFIND: int\nKEY_SHELP: int\nKEY_SHOME: int\nKEY_SIC: int\nKEY_SLEFT: int\nKEY_SMESSAGE: int\nKEY_SMOVE: int\nKEY_SNEXT: int\nKEY_SOPTIONS: int\nKEY_SPREVIOUS: int\nKEY_SPRINT: int\nKEY_SR: int\nKEY_SREDO: int\nKEY_SREPLACE: int\nKEY_SRESET: int\nKEY_SRIGHT: int\nKEY_SRSUME: int\nKEY_SSAVE: int\nKEY_SSUSPEND: int\nKEY_STAB: int\nKEY_SUNDO: int\nKEY_SUSPEND: int\nKEY_UNDO: int\nKEY_UP: int\nOK: int\nREPORT_MOUSE_POSITION: int\n_C_API: Any\nversion: 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: ...\n\nif sys.version_info >= (3, 9):\n    def get_escdelay() -> int: ...\n    def get_tabsize() -> int: ...\n\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\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 = ..., begin_x: int = ..., /) -> 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: ...\n\nif sys.version_info >= (3, 9):\n    def set_escdelay(ms: int, /) -> None: ...\n    def set_tabsize(size: int, /) -> None: ...\n\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 = ..., /) -> None: ...\n    def bkgdset(self, ch: _ChType, attr: int = ..., /) -> 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 = ..., horch: _ChType = ...) -> 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 = ..., /) -> 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 = ...) -> bytes: ...\n    @overload\n    def instr(self, y: int, x: int, n: int = ...) -> 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 = ...) -> 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 = ...) -> 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\n\n__version__: str\nversion: 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 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: 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 = ..., /) -> 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[str]\nROUND_HALF_UP: Final[str]\nROUND_HALF_EVEN: Final[str]\nROUND_CEILING: Final[str]\nROUND_FLOOR: Final[str]\nROUND_UP: Final[str]\nROUND_HALF_DOWN: Final[str]\nROUND_05UP: Final[str]\nHAVE_CONTEXTVAR: Final[bool]\nHAVE_THREADS: Final[bool]\nMAX_EMAX: Final[int]\nMAX_PREC: Final[int]\nMIN_EMIN: Final[int]\nMIN_ETINY: 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 = ...,\n        rounding: str | None = ...,\n        Emin: int | None = ...,\n        Emax: int | None = ...,\n        capitals: int | None = ...,\n        clamp: int | None = ...,\n        traps: dict[_TrapType, bool] | None = ...,\n        flags: dict[_TrapType, bool] | None = ...,\n    ) -> _ContextManager: ...\n\nelse:\n    def localcontext(ctx: Context | None = None) -> _ContextManager: ...\n\nDefaultContext: Context\nBasicContext: Context\nExtendedContext: Context\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_dummy_thread.pyi",
    "content": "from collections.abc import Callable\nfrom types import TracebackType\nfrom typing import Any, NoReturn, overload\nfrom typing_extensions import TypeVarTuple, Unpack\n\n__all__ = [\"error\", \"start_new_thread\", \"exit\", \"get_ident\", \"allocate_lock\", \"interrupt_main\", \"LockType\", \"RLock\"]\n\n_Ts = TypeVarTuple(\"_Ts\")\n\nTIMEOUT_MAX: int\nerror = RuntimeError\n\n@overload\ndef start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]]) -> None: ...\n@overload\ndef start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: ...\ndef exit() -> NoReturn: ...\ndef get_ident() -> int: ...\ndef allocate_lock() -> LockType: ...\ndef stack_size(size: int | None = None) -> int: ...\n\nclass LockType:\n    locked_status: bool\n    def acquire(self, waitflag: bool | None = None, timeout: int = -1) -> bool: ...\n    def __enter__(self, waitflag: bool | None = None, timeout: int = -1) -> bool: ...\n    def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ...\n    def release(self) -> bool: ...\n    def locked(self) -> bool: ...\n\nclass RLock(LockType):\n    def release(self) -> None: ...  # type: ignore[override]\n\ndef interrupt_main() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_dummy_threading.pyi",
    "content": "from _threading_local import local as local\nfrom _typeshed import ProfileFunction, TraceFunction\nfrom threading import (\n    TIMEOUT_MAX as TIMEOUT_MAX,\n    Barrier as Barrier,\n    BoundedSemaphore as BoundedSemaphore,\n    BrokenBarrierError as BrokenBarrierError,\n    Condition as Condition,\n    Event as Event,\n    ExceptHookArgs as ExceptHookArgs,\n    Lock as Lock,\n    RLock as RLock,\n    Semaphore as Semaphore,\n    Thread as Thread,\n    ThreadError as ThreadError,\n    Timer as Timer,\n    _DummyThread as _DummyThread,\n    _RLock as _RLock,\n    excepthook as excepthook,\n)\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    \"setprofile\",\n    \"settrace\",\n    \"local\",\n    \"stack_size\",\n    \"ExceptHookArgs\",\n    \"excepthook\",\n]\n\ndef active_count() -> int: ...\ndef current_thread() -> Thread: ...\ndef currentThread() -> Thread: ...\ndef get_ident() -> int: ...\ndef enumerate() -> list[Thread]: ...\ndef main_thread() -> Thread: ...\ndef settrace(func: TraceFunction) -> None: ...\ndef setprofile(func: ProfileFunction | None) -> None: ...\ndef stack_size(size: int | None = None) -> int: ...\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\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] = (),\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        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        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        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        def module_repr(m: types.ModuleType) -> str: ... # type: ignore[override]  # method/static moment\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, Literal\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: bytes\n\ndef cache_from_source(path: str, debug_override: bool | None = None, *, optimization: Any | None = None) -> str: ...\ndef source_from_cache(path: str) -> 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\nclass WindowsRegistryFinder(importlib.abc.MetaPathFinder):\n    if sys.version_info < (3, 12):\n        @classmethod\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        def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...\n\nSOURCE_SUFFIXES: list[str]\nDEBUG_BYTECODE_SUFFIXES: list[str]\nOPTIMIZED_BYTECODE_SUFFIXES: list[str]\nBYTECODE_SUFFIXES: list[str]\nEXTENSION_SUFFIXES: 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: ReadableBuffer | 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, name: str | None = None) -> str: ...\n    def load_module(self, name: 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\nclass SourcelessFileLoader(importlib.abc.FileLoader, FileLoader, _LoaderBasics):  # type: ignore[misc]  # incompatible method names in base classes\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):  # type: ignore[misc]  # incompatible method names in base classes\n    def __init__(self, name: str, path: str) -> None: ...\n    def get_filename(self, name: str | None = None) -> str: ...  # type: ignore[override]  # incompatible method names\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(\"load_module() is deprecated; 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(\"module_repr() is deprecated, and has been removed in Python 3.12\")\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        @deprecated(\"load_module() is deprecated; use exec_module() instead\")\n        def load_module(self, fullname: str) -> types.ModuleType: ...\n        if sys.version_info >= (3, 10):\n            @staticmethod\n            @deprecated(\"module_repr() is deprecated, and has been removed in Python 3.12\")\n            def module_repr(module: types.ModuleType) -> str: ...\n            def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...\n        else:\n            @classmethod\n            @deprecated(\"module_repr() is deprecated, and has been removed in Python 3.12\")\n            def module_repr(cls, module: types.ModuleType) -> str: ...\n\nif sys.version_info >= (3, 13):\n    class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): ...  # type: ignore[misc]  # incompatible method names in base classes\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_gdbm.pyi",
    "content": "import sys\nfrom _typeshed import ReadOnlyBuffer, StrOrBytesPath\nfrom types import TracebackType\nfrom typing import TypeVar, overload\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    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, final, overload\nfrom typing_extensions import Self, TypeAlias\n\n_DigestMod: TypeAlias = str | Callable[[], HASH] | ModuleType | None\n\nopenssl_md_meth_names: frozenset[str]\n\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\nif sys.version_info >= (3, 9):\n    class 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\n    class 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\n    def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ...\n    @overload\n    def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ...\n    def get_fips_mode() -> int: ...\n    def hmac_new(key: bytes | bytearray, msg: ReadableBuffer = b\"\", digestmod: _DigestMod = None) -> HMAC: ...\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\nelse:\n    def new(name: str, string: ReadableBuffer = b\"\") -> HASH: ...\n    def openssl_md5(string: ReadableBuffer = b\"\") -> HASH: ...\n    def openssl_sha1(string: ReadableBuffer = b\"\") -> HASH: ...\n    def openssl_sha224(string: ReadableBuffer = b\"\") -> HASH: ...\n    def openssl_sha256(string: ReadableBuffer = b\"\") -> HASH: ...\n    def openssl_sha384(string: ReadableBuffer = b\"\") -> HASH: ...\n    def openssl_sha512(string: ReadableBuffer = b\"\") -> HASH: ...\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": "from typing import Any, Final, TypeVar\n\n_T = TypeVar(\"_T\")\n\n__about__: Final[str]\n\ndef heapify(heap: list[Any], /) -> 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"
  },
  {
    "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\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, Mapping\nfrom typing import Final, Literal, SupportsIndex\nfrom typing_extensions import TypeAlias\n\n_Configs: TypeAlias = Literal[\"default\", \"isolated\", \"legacy\", \"empty\", \"\"]\n\nclass InterpreterError(Exception): ...\nclass InterpreterNotFoundError(InterpreterError): ...\nclass NotShareableError(ValueError): ...\n\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) -> list[tuple[int, int]]: ...\ndef get_current() -> tuple[int, int]: ...\ndef get_main() -> tuple[int, int]: ...\ndef is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: ...\ndef get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: ...\ndef whence(id: SupportsIndex) -> int: ...\ndef exec(\n    id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False\n) -> None | types.SimpleNamespace: ...\ndef call(\n    id: SupportsIndex,\n    callable: Callable[..., object],\n    args: tuple[object, ...] | None = None,\n    kwargs: dict[str, object] | None = None,\n    *,\n    restrict: bool = False,\n) -> object: ...\ndef run_string(\n    id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False\n) -> None: ...\ndef run_func(\n    id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False\n) -> None: ...\ndef set___main___attrs(id: SupportsIndex, updates: Mapping[str, object], *, 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: ...\ndef capture_exception(exc: BaseException | None = None) -> types.SimpleNamespace: ...\n\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\n\n_T = TypeVar(\"_T\")\n\nDEFAULT_BUFFER_SIZE: Final = 8192\n\nopen = builtins.open\n\ndef open_code(path: str) -> IO[bytes]: ...\n\nBlockingIOError = builtins.BlockingIOError\n\nclass _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\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\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\nclass BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO):  # type: ignore[misc]  # incompatible definitions of methods in the base classes\n    raw: RawIOBase\n    def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...\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\nclass BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO):  # type: ignore[misc]  # incompatible definitions of writelines in the base classes\n    raw: RawIOBase\n    def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...\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\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    def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...\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\nclass BufferedRWPair(BufferedIOBase, _BufferedIOBase):\n    def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = 8192, /) -> None: ...\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, see the comments on TextIOWrapper.name and\n    # TextIO.name.\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\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\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\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) -> int | 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: int | 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 = ...) -> 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\n\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: 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: int  # v big number\n\n@final\nclass LZMADecompressor:\n    if sys.version_info >= (3, 12):\n        def __new__(cls, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> Self: ...\n    else:\n        def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | 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 | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ...\n        ) -> Self: ...\n    else:\n        def __init__(\n            self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | 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: int = 1) -> int: ...  # undocumented\n    def parse_declaration(self, i: int) -> int: ...  # undocumented\n    def parse_marked_section(self, i: int, report: int = 1) -> 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\n\nif sys.platform == \"win32\":\n    class MSIError(Exception): ...\n    # Actual typename View, not exposed by the implementation\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    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    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    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: int\n    MSICOLINFO_TYPES: int\n    MSIDBOPEN_CREATE: int\n    MSIDBOPEN_CREATEDIRECT: int\n    MSIDBOPEN_DIRECT: int\n    MSIDBOPEN_PATCHFILE: int\n    MSIDBOPEN_READONLY: int\n    MSIDBOPEN_TRANSACT: int\n    MSIMODIFY_ASSIGN: int\n    MSIMODIFY_DELETE: int\n    MSIMODIFY_INSERT: int\n    MSIMODIFY_INSERT_TEMPORARY: int\n    MSIMODIFY_MERGE: int\n    MSIMODIFY_REFRESH: int\n    MSIMODIFY_REPLACE: int\n    MSIMODIFY_SEEK: int\n    MSIMODIFY_UPDATE: int\n    MSIMODIFY_VALIDATE: int\n    MSIMODIFY_VALIDATE_DELETE: int\n    MSIMODIFY_VALIDATE_FIELD: int\n    MSIMODIFY_VALIDATE_NEW: int\n\n    PID_APPNAME: int\n    PID_AUTHOR: int\n    PID_CHARCOUNT: int\n    PID_CODEPAGE: int\n    PID_COMMENTS: int\n    PID_CREATE_DTM: int\n    PID_KEYWORDS: int\n    PID_LASTAUTHOR: int\n    PID_LASTPRINTED: int\n    PID_LASTSAVE_DTM: int\n    PID_PAGECOUNT: int\n    PID_REVNUMBER: int\n    PID_SECURITY: int\n    PID_SUBJECT: int\n    PID_TEMPLATE: int\n    PID_TITLE: int\n    PID_WORDCOUNT: 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\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\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\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\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\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\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\nclass _SupportsDunderLT(Protocol):\n    def __lt__(self, other: Any, /) -> Any: ...\n\nclass _SupportsDunderGT(Protocol):\n    def __gt__(self, other: Any, /) -> Any: ...\n\nclass _SupportsDunderLE(Protocol):\n    def __le__(self, other: Any, /) -> Any: ...\n\nclass _SupportsDunderGE(Protocol):\n    def __ge__(self, other: Any, /) -> Any: ...\n\n_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT\n\nclass _SupportsInversion(Protocol[_T_co]):\n    def __invert__(self) -> _T_co: ...\n\nclass _SupportsNeg(Protocol[_T_co]):\n    def __neg__(self) -> _T_co: ...\n\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: SupportsIndex, /) -> None: ...\n@overload\ndef delitem(a: MutableSequence[Any], b: slice, /) -> None: ...\n@overload\ndef delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ...\n@overload\ndef getitem(a: Sequence[_T], b: slice, /) -> 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: SupportsIndex, c: _T, /) -> None: ...\n@overload\ndef setitem(a: MutableSequence[_T], b: slice, 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": "import sys\nfrom _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\n\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\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    if sys.version_info >= (3, 13):\n        def persistent_id(self, obj: Any, /) -> Any: ...\n    else:\n        persistent_id: Callable[[Any], Any]\n\n@type_check_only\nclass UnpicklerMemoProxy:\n    def clear(self, /) -> None: ...\n    def copy(self, /) -> dict[int, tuple[int, Any]]: ...\n\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    if sys.version_info >= (3, 13):\n        def persistent_load(self, pid: Any, /) -> Any: ...\n    else:\n        persistent_load: Callable[[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    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        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\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"
  },
  {
    "path": "mypy/typeshed/stdlib/_queue.pyi",
    "content": "import sys\nfrom typing import Any, Generic, TypeVar\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n_T = TypeVar(\"_T\")\n\nclass Empty(Exception): ...\n\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_random.pyi",
    "content": "from typing_extensions import TypeAlias\n\n# Actually Tuple[(int,) * 625]\n_State: TypeAlias = tuple[int, ...]\n\nclass Random:\n    def __init__(self, seed: object = ...) -> None: ...\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, SupportsIndex, overload\nfrom typing_extensions import CapsuleType, TypeAlias\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: int\n\nAF_INET: int\nAF_INET6: int\n\nAF_UNSPEC: int\n\nSOCK_STREAM: int\nSOCK_DGRAM: int\nSOCK_RAW: int\nSOCK_RDM: int\nSOCK_SEQPACKET: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.27\n    SOCK_CLOEXEC: int\n    SOCK_NONBLOCK: 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: int\nSO_BROADCAST: int\nSO_DEBUG: int\nSO_DONTROUTE: int\nSO_ERROR: int\nSO_KEEPALIVE: int\nSO_LINGER: int\nSO_OOBINLINE: int\nSO_RCVBUF: int\nSO_RCVLOWAT: int\nSO_RCVTIMEO: int\nSO_REUSEADDR: int\nSO_SNDBUF: int\nSO_SNDLOWAT: int\nSO_SNDTIMEO: int\nSO_TYPE: int\nif sys.platform != \"linux\":\n    SO_USELOOPBACK: int\nif sys.platform == \"win32\":\n    SO_EXCLUSIVEADDRUSE: int\nif sys.platform != \"win32\":\n    SO_REUSEPORT: int\n    if sys.platform != \"darwin\" or sys.version_info >= (3, 13):\n        SO_BINDTODEVICE: int\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    SO_DOMAIN: int\n    SO_MARK: int\n    SO_PASSCRED: int\n    SO_PASSSEC: int\n    SO_PEERCRED: int\n    SO_PEERSEC: int\n    SO_PRIORITY: int\n    SO_PROTOCOL: int\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    SO_SETFIB: int\nif sys.platform == \"linux\" and sys.version_info >= (3, 13):\n    SO_BINDTOIFINDEX: int\n\nSOMAXCONN: int\n\nMSG_CTRUNC: int\nMSG_DONTROUTE: int\nMSG_OOB: int\nMSG_PEEK: int\nMSG_TRUNC: int\nMSG_WAITALL: int\nif sys.platform != \"win32\":\n    MSG_DONTWAIT: int\n    MSG_EOR: int\n    MSG_NOSIGNAL: int  # Sometimes this exists on darwin, sometimes not\nif sys.platform != \"darwin\":\n    MSG_ERRQUEUE: int\nif sys.platform == \"win32\":\n    MSG_BCAST: int\n    MSG_MCAST: int\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    MSG_CMSG_CLOEXEC: int\n    MSG_CONFIRM: int\n    MSG_FASTOPEN: int\n    MSG_MORE: int\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    MSG_EOF: int\nif sys.platform != \"win32\" and sys.platform != \"linux\" and sys.platform != \"darwin\":\n    MSG_NOTIFICATION: int\n    MSG_BTAG: int  # Not FreeBSD either\n    MSG_ETAG: int  # Not FreeBSD either\n\nSOL_IP: int\nSOL_SOCKET: int\nSOL_TCP: int\nSOL_UDP: 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: int\n    SOL_AX25: int\n    SOL_HCI: int\n    SOL_IPX: int\n    SOL_NETROM: int\n    SOL_ROSE: int\n\nif sys.platform != \"win32\":\n    SCM_RIGHTS: int\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    SCM_CREDENTIALS: int\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    SCM_CREDS: int\n\nIPPROTO_ICMP: int\nIPPROTO_IP: int\nIPPROTO_RAW: int\nIPPROTO_TCP: int\nIPPROTO_UDP: int\nIPPROTO_AH: int\nIPPROTO_DSTOPTS: int\nIPPROTO_EGP: int\nIPPROTO_ESP: int\nIPPROTO_FRAGMENT: int\nIPPROTO_HOPOPTS: int\nIPPROTO_ICMPV6: int\nIPPROTO_IDP: int\nIPPROTO_IGMP: int\nIPPROTO_IPV6: int\nIPPROTO_NONE: int\nIPPROTO_PIM: int\nIPPROTO_PUP: int\nIPPROTO_ROUTING: int\nIPPROTO_SCTP: int\nif sys.platform != \"linux\":\n    IPPROTO_GGP: int\n    IPPROTO_IPV4: int\n    IPPROTO_MAX: int\n    IPPROTO_ND: int\nif sys.platform == \"win32\":\n    IPPROTO_CBT: int\n    IPPROTO_ICLFXBM: int\n    IPPROTO_IGP: int\n    IPPROTO_L2TP: int\n    IPPROTO_PGM: int\n    IPPROTO_RDP: int\n    IPPROTO_ST: int\nif sys.platform != \"win32\":\n    IPPROTO_GRE: int\n    IPPROTO_IPIP: int\n    IPPROTO_RSVP: int\n    IPPROTO_TP: int\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    IPPROTO_EON: int\n    IPPROTO_HELLO: int\n    IPPROTO_IPCOMP: int\n    IPPROTO_XTP: int\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    IPPROTO_BIP: int  # Not FreeBSD either\n    IPPROTO_MOBILE: int  # Not FreeBSD either\n    IPPROTO_VRRP: int  # Not FreeBSD either\nif sys.version_info >= (3, 9) and sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.20, FreeBSD >= 10.1\n    IPPROTO_UDPLITE: int\nif sys.version_info >= (3, 10) and sys.platform == \"linux\":\n    IPPROTO_MPTCP: int\n\nIPPORT_RESERVED: int\nIPPORT_USERRESERVED: int\n\nINADDR_ALLHOSTS_GROUP: int\nINADDR_ANY: int\nINADDR_BROADCAST: int\nINADDR_LOOPBACK: int\nINADDR_MAX_LOCAL_GROUP: int\nINADDR_NONE: int\nINADDR_UNSPEC_GROUP: int\n\nIP_ADD_MEMBERSHIP: int\nIP_DROP_MEMBERSHIP: int\nIP_HDRINCL: int\nIP_MULTICAST_IF: int\nIP_MULTICAST_LOOP: int\nIP_MULTICAST_TTL: int\nIP_OPTIONS: int\nif sys.platform != \"linux\":\n    IP_RECVDSTADDR: int\nif sys.version_info >= (3, 10):\n    IP_RECVTOS: int\nIP_TOS: int\nIP_TTL: int\nif sys.platform != \"win32\":\n    IP_DEFAULT_MULTICAST_LOOP: int\n    IP_DEFAULT_MULTICAST_TTL: int\n    IP_MAX_MEMBERSHIPS: int\n    IP_RECVOPTS: int\n    IP_RECVRETOPTS: int\n    IP_RETOPTS: int\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    IP_TRANSPARENT: int\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.version_info >= (3, 11):\n    IP_BIND_ADDRESS_NO_PORT: int\nif sys.version_info >= (3, 12):\n    IP_ADD_SOURCE_MEMBERSHIP: int\n    IP_BLOCK_SOURCE: int\n    IP_DROP_SOURCE_MEMBERSHIP: int\n    IP_PKTINFO: int\n    IP_UNBLOCK_SOURCE: int\n\nIPV6_CHECKSUM: int\nIPV6_JOIN_GROUP: int\nIPV6_LEAVE_GROUP: int\nIPV6_MULTICAST_HOPS: int\nIPV6_MULTICAST_IF: int\nIPV6_MULTICAST_LOOP: int\nIPV6_RECVTCLASS: int\nIPV6_TCLASS: int\nIPV6_UNICAST_HOPS: int\nIPV6_V6ONLY: int\nif sys.version_info >= (3, 9) or sys.platform != \"darwin\":\n    IPV6_DONTFRAG: int\n    IPV6_HOPLIMIT: int\n    IPV6_HOPOPTS: int\n    IPV6_PKTINFO: int\n    IPV6_RECVRTHDR: int\n    IPV6_RTHDR: int\nif sys.platform != \"win32\":\n    IPV6_RTHDR_TYPE_0: int\n    if sys.version_info >= (3, 9) or sys.platform != \"darwin\":\n        IPV6_DSTOPTS: int\n        IPV6_NEXTHOP: int\n        IPV6_PATHMTU: int\n        IPV6_RECVDSTOPTS: int\n        IPV6_RECVHOPLIMIT: int\n        IPV6_RECVHOPOPTS: int\n        IPV6_RECVPATHMTU: int\n        IPV6_RECVPKTINFO: int\n        IPV6_RTHDRDSTOPTS: int\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    if sys.version_info >= (3, 9) or sys.platform != \"darwin\":\n        IPV6_USE_MIN_MTU: int\n\nEAI_AGAIN: int\nEAI_BADFLAGS: int\nEAI_FAIL: int\nEAI_FAMILY: int\nEAI_MEMORY: int\nEAI_NODATA: int\nEAI_NONAME: int\nEAI_SERVICE: int\nEAI_SOCKTYPE: int\nif sys.platform != \"win32\":\n    EAI_ADDRFAMILY: int\n    EAI_OVERFLOW: int\n    EAI_SYSTEM: int\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    EAI_BADHINTS: int\n    EAI_MAX: int\n    EAI_PROTOCOL: int\n\nAI_ADDRCONFIG: int\nAI_ALL: int\nAI_CANONNAME: int\nAI_NUMERICHOST: int\nAI_NUMERICSERV: int\nAI_PASSIVE: int\nAI_V4MAPPED: int\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    AI_DEFAULT: int\n    AI_MASK: int\n    AI_V4MAPPED_CFG: int\n\nNI_DGRAM: int\nNI_MAXHOST: int\nNI_MAXSERV: int\nNI_NAMEREQD: int\nNI_NOFQDN: int\nNI_NUMERICHOST: int\nNI_NUMERICSERV: int\nif sys.platform == \"linux\" and sys.version_info >= (3, 13):\n    NI_IDN: int\n\nTCP_FASTOPEN: int\nTCP_KEEPCNT: int\nTCP_KEEPINTVL: int\nTCP_MAXSEG: int\nTCP_NODELAY: int\nif sys.platform != \"win32\":\n    TCP_NOTSENT_LOWAT: int\nif sys.platform != \"darwin\":\n    TCP_KEEPIDLE: int\nif sys.version_info >= (3, 10) and sys.platform == \"darwin\":\n    TCP_KEEPALIVE: int\nif sys.version_info >= (3, 11) and sys.platform == \"darwin\":\n    TCP_CONNECTION_INFO: int\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    TCP_CONGESTION: int\n    TCP_CORK: int\n    TCP_DEFER_ACCEPT: int\n    TCP_INFO: int\n    TCP_LINGER2: int\n    TCP_QUICKACK: int\n    TCP_SYNCNT: int\n    TCP_USER_TIMEOUT: int\n    TCP_WINDOW_CLAMP: int\nif sys.platform == \"linux\" and sys.version_info >= (3, 12):\n    TCP_CC_INFO: int\n    TCP_FASTOPEN_CONNECT: int\n    TCP_FASTOPEN_KEY: int\n    TCP_FASTOPEN_NO_COOKIE: int\n    TCP_INQ: int\n    TCP_MD5SIG: int\n    TCP_MD5SIG_EXT: int\n    TCP_QUEUE_SEQ: int\n    TCP_REPAIR: int\n    TCP_REPAIR_OPTIONS: int\n    TCP_REPAIR_QUEUE: int\n    TCP_REPAIR_WINDOW: int\n    TCP_SAVED_SYN: int\n    TCP_SAVE_SYN: int\n    TCP_THIN_DUPACK: int\n    TCP_THIN_LINEAR_TIMEOUTS: int\n    TCP_TIMESTAMP: int\n    TCP_TX_DELAY: int\n    TCP_ULP: int\n    TCP_ZEROCOPY_RECEIVE: int\n\n# --------------------\n# Specifically documented constants\n# --------------------\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.25, NetBSD >= 8\n    AF_CAN: int\n    PF_CAN: int\n    SOL_CAN_BASE: int\n    SOL_CAN_RAW: int\n    CAN_EFF_FLAG: int\n    CAN_EFF_MASK: int\n    CAN_ERR_FLAG: int\n    CAN_ERR_MASK: int\n    CAN_RAW: int\n    CAN_RAW_FILTER: int\n    CAN_RAW_LOOPBACK: int\n    CAN_RAW_RECV_OWN_MSGS: int\n    CAN_RTR_FLAG: int\n    CAN_SFF_MASK: int\n    if sys.version_info < (3, 11):\n        CAN_RAW_ERR_FILTER: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.25\n    CAN_BCM: int\n    CAN_BCM_TX_SETUP: int\n    CAN_BCM_TX_DELETE: int\n    CAN_BCM_TX_READ: int\n    CAN_BCM_TX_SEND: int\n    CAN_BCM_RX_SETUP: int\n    CAN_BCM_RX_DELETE: int\n    CAN_BCM_RX_READ: int\n    CAN_BCM_TX_STATUS: int\n    CAN_BCM_TX_EXPIRED: int\n    CAN_BCM_RX_STATUS: int\n    CAN_BCM_RX_TIMEOUT: int\n    CAN_BCM_RX_CHANGED: int\n    CAN_BCM_SETTIMER: int\n    CAN_BCM_STARTTIMER: int\n    CAN_BCM_TX_COUNTEVT: int\n    CAN_BCM_TX_ANNOUNCE: int\n    CAN_BCM_TX_CP_CAN_ID: int\n    CAN_BCM_RX_FILTER_ID: int\n    CAN_BCM_RX_CHECK_DLC: int\n    CAN_BCM_RX_NO_AUTOTIMER: int\n    CAN_BCM_RX_ANNOUNCE_RESUME: int\n    CAN_BCM_TX_RESET_MULTI_IDX: int\n    CAN_BCM_RX_RTR_FRAME: int\n    CAN_BCM_CAN_FD_FRAME: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 3.6\n    CAN_RAW_FD_FRAMES: int\n\nif sys.platform == \"linux\" and sys.version_info >= (3, 9):\n    # Availability: Linux >= 4.1\n    CAN_RAW_JOIN_FILTERS: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.25\n    CAN_ISOTP: int\n\nif sys.platform == \"linux\" and sys.version_info >= (3, 9):\n    # Availability: Linux >= 5.4\n    CAN_J1939: int\n\n    J1939_MAX_UNICAST_ADDR: int\n    J1939_IDLE_ADDR: int\n    J1939_NO_ADDR: int\n    J1939_NO_NAME: int\n    J1939_PGN_REQUEST: int\n    J1939_PGN_ADDRESS_CLAIMED: int\n    J1939_PGN_ADDRESS_COMMANDED: int\n    J1939_PGN_PDU1_MAX: int\n    J1939_PGN_MAX: int\n    J1939_NO_PGN: int\n\n    SO_J1939_FILTER: int\n    SO_J1939_PROMISC: int\n    SO_J1939_SEND_PRIO: int\n    SO_J1939_ERRQUEUE: int\n\n    SCM_J1939_DEST_ADDR: int\n    SCM_J1939_DEST_NAME: int\n    SCM_J1939_PRIO: int\n    SCM_J1939_ERRQUEUE: int\n\n    J1939_NLA_PAD: int\n    J1939_NLA_BYTES_ACKED: int\n    J1939_EE_INFO_NONE: int\n    J1939_EE_INFO_TX_ABORT: int\n    J1939_FILTER_MAX: 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: int\n    PF_DIVERT: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.2\n    AF_PACKET: int\n    PF_PACKET: int\n    PACKET_BROADCAST: int\n    PACKET_FASTROUTE: int\n    PACKET_HOST: int\n    PACKET_LOOPBACK: int\n    PACKET_MULTICAST: int\n    PACKET_OTHERHOST: int\n    PACKET_OUTGOING: int\n\nif sys.version_info >= (3, 12) and sys.platform == \"linux\":\n    ETH_P_ALL: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.30\n    AF_RDS: int\n    PF_RDS: int\n    SOL_RDS: int\n    # These are present in include/linux/rds.h but don't always show up\n    # here.\n    RDS_CANCEL_SENT_TO: int\n    RDS_CMSG_RDMA_ARGS: int\n    RDS_CMSG_RDMA_DEST: int\n    RDS_CMSG_RDMA_MAP: int\n    RDS_CMSG_RDMA_STATUS: int\n    RDS_CONG_MONITOR: int\n    RDS_FREE_MR: int\n    RDS_GET_MR: int\n    RDS_GET_MR_FOR_DEST: int\n    RDS_RDMA_DONTWAIT: int\n    RDS_RDMA_FENCE: int\n    RDS_RDMA_INVALIDATE: int\n    RDS_RDMA_NOTIFY_ME: int\n    RDS_RDMA_READWRITE: int\n    RDS_RDMA_SILENT: int\n    RDS_RDMA_USE_ONCE: int\n    RDS_RECVERR: 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: int\n\nif sys.platform == \"win32\":\n    SIO_RCVALL: int\n    SIO_KEEPALIVE_VALS: int\n    SIO_LOOPBACK_FAST_PATH: int\n    RCVALL_MAX: int\n    RCVALL_OFF: int\n    RCVALL_ON: int\n    RCVALL_SOCKETLEVELONLY: int\n\nif sys.platform == \"linux\":\n    AF_TIPC: int\n    SOL_TIPC: int\n    TIPC_ADDR_ID: int\n    TIPC_ADDR_NAME: int\n    TIPC_ADDR_NAMESEQ: int\n    TIPC_CFG_SRV: int\n    TIPC_CLUSTER_SCOPE: int\n    TIPC_CONN_TIMEOUT: int\n    TIPC_CRITICAL_IMPORTANCE: int\n    TIPC_DEST_DROPPABLE: int\n    TIPC_HIGH_IMPORTANCE: int\n    TIPC_IMPORTANCE: int\n    TIPC_LOW_IMPORTANCE: int\n    TIPC_MEDIUM_IMPORTANCE: int\n    TIPC_NODE_SCOPE: int\n    TIPC_PUBLISHED: int\n    TIPC_SRC_DROPPABLE: int\n    TIPC_SUBSCR_TIMEOUT: int\n    TIPC_SUB_CANCEL: int\n    TIPC_SUB_PORTS: int\n    TIPC_SUB_SERVICE: int\n    TIPC_TOP_SRV: int\n    TIPC_WAIT_FOREVER: int\n    TIPC_WITHDRAWN: int\n    TIPC_ZONE_SCOPE: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.38\n    AF_ALG: int\n    SOL_ALG: int\n    ALG_OP_DECRYPT: int\n    ALG_OP_ENCRYPT: int\n    ALG_OP_SIGN: int\n    ALG_OP_VERIFY: int\n    ALG_SET_AEAD_ASSOCLEN: int\n    ALG_SET_AEAD_AUTHSIZE: int\n    ALG_SET_IV: int\n    ALG_SET_KEY: int\n    ALG_SET_OP: int\n    ALG_SET_PUBKEY: int\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 4.8 (or maybe 3.9, CPython docs are confusing)\n    AF_VSOCK: int\n    IOCTL_VM_SOCKETS_GET_LOCAL_CID: int\n    VMADDR_CID_ANY: int\n    VMADDR_CID_HOST: int\n    VMADDR_PORT_ANY: int\n    SO_VM_SOCKETS_BUFFER_MAX_SIZE: int\n    SO_VM_SOCKETS_BUFFER_SIZE: int\n    SO_VM_SOCKETS_BUFFER_MIN_SIZE: int\n    VM_SOCKETS_INVALID_VERSION: int  # undocumented\n\nif sys.platform != \"win32\" or sys.version_info >= (3, 9):\n    # Documented as only available on BSD, macOS, but empirically sometimes\n    # available on Windows\n    if sys.platform != \"linux\":\n        AF_LINK: int\n\nhas_ipv6: bool\n\nif sys.platform != \"darwin\" and sys.platform != \"linux\":\n    if sys.platform != \"win32\" or sys.version_info >= (3, 9):\n        BDADDR_ANY: str\n        BDADDR_LOCAL: str\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    HCI_FILTER: int  # not in NetBSD or DragonFlyBSD\n    HCI_TIME_STAMP: int  # not in FreeBSD, NetBSD, or DragonFlyBSD\n    HCI_DATA_DIR: int  # not in FreeBSD, NetBSD, or DragonFlyBSD\n\nif sys.platform == \"linux\":\n    AF_QIPCRTR: 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: int\n    LOCAL_CREDS: int\n    LOCAL_CREDS_PERSISTENT: int\n\nif sys.version_info >= (3, 11) and sys.platform == \"linux\":\n    SO_INCOMING_CPU: int  # Availability: Linux >= 3.9\n\nif sys.version_info >= (3, 12) and sys.platform == \"win32\":\n    # Availability: Windows\n    AF_HYPERV: int\n    HV_PROTOCOL_RAW: int\n    HVSOCKET_CONNECT_TIMEOUT: int\n    HVSOCKET_CONNECT_TIMEOUT_MAX: int\n    HVSOCKET_CONNECTED_SUSPEND: int\n    HVSOCKET_ADDRESS_FLAG_PASSTHRU: int\n    HV_GUID_ZERO: str\n    HV_GUID_WILDCARD: str\n    HV_GUID_BROADCAST: str\n    HV_GUID_CHILDREN: str\n    HV_GUID_LOOPBACK: str\n    HV_GUID_PARENT: str\n\nif sys.version_info >= (3, 12):\n    if sys.platform != \"win32\":\n        # Availability: Linux, FreeBSD, macOS\n        ETHERTYPE_ARP: int\n        ETHERTYPE_IP: int\n        ETHERTYPE_IPV6: int\n        ETHERTYPE_VLAN: 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: int\n    NETLINK_CRYPTO: int\n    NETLINK_DNRTMSG: int\n    NETLINK_FIREWALL: int\n    NETLINK_IP6_FW: int\n    NETLINK_NFLOG: int\n    NETLINK_ROUTE: int\n    NETLINK_USERSOCK: int\n    NETLINK_XFRM: int\n    # Technically still supported by CPython\n    # NETLINK_ARPD: int  # linux 2.0 to 2.6.12 (EOL August 2005)\n    # NETLINK_ROUTE6: int  # linux 2.2 to 2.6.12 (EOL August 2005)\n    # NETLINK_SKIP: int  # linux 2.0 to 2.6.12 (EOL August 2005)\n    # NETLINK_TAPBASE: int  # linux 2.2 to 2.6.12 (EOL August 2005)\n    # NETLINK_TCPDIAG: int  # linux 2.6.0 to 2.6.13 (EOL December 2005)\n    # NETLINK_W1: int  # linux 2.6.13 to 2.6.17 (EOL October 2006)\n\nif sys.platform == \"darwin\":\n    PF_SYSTEM: int\n    SYSPROTO_CONTROL: int\n\nif sys.platform != \"darwin\" and sys.platform != \"linux\":\n    if sys.version_info >= (3, 9) or sys.platform != \"win32\":\n        AF_BLUETOOTH: int\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    # Linux and some BSD support is explicit in the docs\n    # Windows and macOS do not support in practice\n    BTPROTO_HCI: int\n    BTPROTO_L2CAP: int\n    BTPROTO_SCO: int  # not in FreeBSD\nif sys.platform != \"darwin\" and sys.platform != \"linux\":\n    if sys.version_info >= (3, 9) or sys.platform != \"win32\":\n        BTPROTO_RFCOMM: int\n\nif sys.version_info >= (3, 9) and sys.platform == \"linux\":\n    UDPLITE_RECV_CSCOV: int\n    UDPLITE_SEND_CSCOV: int\n\n# --------------------\n# Documented under socket.shutdown\n# --------------------\nSHUT_RD: int\nSHUT_RDWR: int\nSHUT_WR: int\n\n# --------------------\n# Undocumented constants\n# --------------------\n\n# Undocumented address families\nAF_APPLETALK: int\nAF_DECnet: int\nAF_IPX: int\nAF_SNA: int\n\nif sys.platform != \"win32\":\n    AF_ROUTE: int\n\nif sys.platform == \"darwin\":\n    AF_SYSTEM: int\n\nif sys.platform != \"darwin\":\n    AF_IRDA: int\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    AF_ASH: int\n    AF_ATMPVC: int\n    AF_ATMSVC: int\n    AF_AX25: int\n    AF_BRIDGE: int\n    AF_ECONET: int\n    AF_KEY: int\n    AF_LLC: int\n    AF_NETBEUI: int\n    AF_NETROM: int\n    AF_PPPOX: int\n    AF_ROSE: int\n    AF_SECURITY: int\n    AF_WANPIPE: int\n    AF_X25: int\n\n# Miscellaneous undocumented\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    LOCAL_PEERCRED: 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: int\n\n# ===== Classes =====\n\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 = ...\n        ) -> None: ...\n    else:\n        def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | 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 = ..., /) -> bytes: ...\n    def recvfrom(self, bufsize: int, flags: int = ..., /) -> tuple[bytes, _RetAddress]: ...\n    if sys.platform != \"win32\":\n        def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ...\n        def recvmsg_into(\n            self, buffers: Iterable[WriteableBuffer], ancbufsize: int = ..., flags: int = ..., /\n        ) -> tuple[int, list[_CMSG], int, Any]: ...\n\n    def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ...\n    def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: ...\n    def send(self, data: ReadableBuffer, flags: int = ..., /) -> int: ...\n    def sendall(self, data: ReadableBuffer, flags: int = ..., /) -> 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 = ...,\n            address: _Address | 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 = ...\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,\n    port: bytes | str | int | None,\n    family: int = ...,\n    type: int = ...,\n    proto: int = ...,\n    flags: int = ...,\n) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ...\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], 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 = ..., /) -> tuple[socket, socket]: ...\n\ndef if_nameindex() -> list[tuple[int, str]]: ...\ndef if_nametoindex(oname: str, /) -> int: ...\ndef 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)\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[int]\nPARSE_DECLTYPES: Final[int]\nSQLITE_ALTER_TABLE: Final[int]\nSQLITE_ANALYZE: Final[int]\nSQLITE_ATTACH: Final[int]\nSQLITE_CREATE_INDEX: Final[int]\nSQLITE_CREATE_TABLE: Final[int]\nSQLITE_CREATE_TEMP_INDEX: Final[int]\nSQLITE_CREATE_TEMP_TABLE: Final[int]\nSQLITE_CREATE_TEMP_TRIGGER: Final[int]\nSQLITE_CREATE_TEMP_VIEW: Final[int]\nSQLITE_CREATE_TRIGGER: Final[int]\nSQLITE_CREATE_VIEW: Final[int]\nSQLITE_CREATE_VTABLE: Final[int]\nSQLITE_DELETE: Final[int]\nSQLITE_DENY: Final[int]\nSQLITE_DETACH: Final[int]\nSQLITE_DONE: Final[int]\nSQLITE_DROP_INDEX: Final[int]\nSQLITE_DROP_TABLE: Final[int]\nSQLITE_DROP_TEMP_INDEX: Final[int]\nSQLITE_DROP_TEMP_TABLE: Final[int]\nSQLITE_DROP_TEMP_TRIGGER: Final[int]\nSQLITE_DROP_TEMP_VIEW: Final[int]\nSQLITE_DROP_TRIGGER: Final[int]\nSQLITE_DROP_VIEW: Final[int]\nSQLITE_DROP_VTABLE: Final[int]\nSQLITE_FUNCTION: Final[int]\nSQLITE_IGNORE: Final[int]\nSQLITE_INSERT: Final[int]\nSQLITE_OK: Final[int]\nSQLITE_PRAGMA: Final[int]\nSQLITE_READ: Final[int]\nSQLITE_RECURSIVE: Final[int]\nSQLITE_REINDEX: Final[int]\nSQLITE_SAVEPOINT: Final[int]\nSQLITE_SELECT: Final[int]\nSQLITE_TRANSACTION: Final[int]\nSQLITE_UPDATE: Final[int]\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[int]\n    SQLITE_DBCONFIG_DEFENSIVE: Final[int]\n    SQLITE_DBCONFIG_DQS_DDL: Final[int]\n    SQLITE_DBCONFIG_DQS_DML: Final[int]\n    SQLITE_DBCONFIG_ENABLE_FKEY: Final[int]\n    SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final[int]\n    SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final[int]\n    SQLITE_DBCONFIG_ENABLE_QPSG: Final[int]\n    SQLITE_DBCONFIG_ENABLE_TRIGGER: Final[int]\n    SQLITE_DBCONFIG_ENABLE_VIEW: Final[int]\n    SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final[int]\n    SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final[int]\n    SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final[int]\n    SQLITE_DBCONFIG_RESET_DATABASE: Final[int]\n    SQLITE_DBCONFIG_TRIGGER_EQP: Final[int]\n    SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final[int]\n    SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final[int]\n\nif sys.version_info >= (3, 11):\n    SQLITE_ABORT: Final[int]\n    SQLITE_ABORT_ROLLBACK: Final[int]\n    SQLITE_AUTH: Final[int]\n    SQLITE_AUTH_USER: Final[int]\n    SQLITE_BUSY: Final[int]\n    SQLITE_BUSY_RECOVERY: Final[int]\n    SQLITE_BUSY_SNAPSHOT: Final[int]\n    SQLITE_BUSY_TIMEOUT: Final[int]\n    SQLITE_CANTOPEN: Final[int]\n    SQLITE_CANTOPEN_CONVPATH: Final[int]\n    SQLITE_CANTOPEN_DIRTYWAL: Final[int]\n    SQLITE_CANTOPEN_FULLPATH: Final[int]\n    SQLITE_CANTOPEN_ISDIR: Final[int]\n    SQLITE_CANTOPEN_NOTEMPDIR: Final[int]\n    SQLITE_CANTOPEN_SYMLINK: Final[int]\n    SQLITE_CONSTRAINT: Final[int]\n    SQLITE_CONSTRAINT_CHECK: Final[int]\n    SQLITE_CONSTRAINT_COMMITHOOK: Final[int]\n    SQLITE_CONSTRAINT_FOREIGNKEY: Final[int]\n    SQLITE_CONSTRAINT_FUNCTION: Final[int]\n    SQLITE_CONSTRAINT_NOTNULL: Final[int]\n    SQLITE_CONSTRAINT_PINNED: Final[int]\n    SQLITE_CONSTRAINT_PRIMARYKEY: Final[int]\n    SQLITE_CONSTRAINT_ROWID: Final[int]\n    SQLITE_CONSTRAINT_TRIGGER: Final[int]\n    SQLITE_CONSTRAINT_UNIQUE: Final[int]\n    SQLITE_CONSTRAINT_VTAB: Final[int]\n    SQLITE_CORRUPT: Final[int]\n    SQLITE_CORRUPT_INDEX: Final[int]\n    SQLITE_CORRUPT_SEQUENCE: Final[int]\n    SQLITE_CORRUPT_VTAB: Final[int]\n    SQLITE_EMPTY: Final[int]\n    SQLITE_ERROR: Final[int]\n    SQLITE_ERROR_MISSING_COLLSEQ: Final[int]\n    SQLITE_ERROR_RETRY: Final[int]\n    SQLITE_ERROR_SNAPSHOT: Final[int]\n    SQLITE_FORMAT: Final[int]\n    SQLITE_FULL: Final[int]\n    SQLITE_INTERNAL: Final[int]\n    SQLITE_INTERRUPT: Final[int]\n    SQLITE_IOERR: Final[int]\n    SQLITE_IOERR_ACCESS: Final[int]\n    SQLITE_IOERR_AUTH: Final[int]\n    SQLITE_IOERR_BEGIN_ATOMIC: Final[int]\n    SQLITE_IOERR_BLOCKED: Final[int]\n    SQLITE_IOERR_CHECKRESERVEDLOCK: Final[int]\n    SQLITE_IOERR_CLOSE: Final[int]\n    SQLITE_IOERR_COMMIT_ATOMIC: Final[int]\n    SQLITE_IOERR_CONVPATH: Final[int]\n    SQLITE_IOERR_CORRUPTFS: Final[int]\n    SQLITE_IOERR_DATA: Final[int]\n    SQLITE_IOERR_DELETE: Final[int]\n    SQLITE_IOERR_DELETE_NOENT: Final[int]\n    SQLITE_IOERR_DIR_CLOSE: Final[int]\n    SQLITE_IOERR_DIR_FSYNC: Final[int]\n    SQLITE_IOERR_FSTAT: Final[int]\n    SQLITE_IOERR_FSYNC: Final[int]\n    SQLITE_IOERR_GETTEMPPATH: Final[int]\n    SQLITE_IOERR_LOCK: Final[int]\n    SQLITE_IOERR_MMAP: Final[int]\n    SQLITE_IOERR_NOMEM: Final[int]\n    SQLITE_IOERR_RDLOCK: Final[int]\n    SQLITE_IOERR_READ: Final[int]\n    SQLITE_IOERR_ROLLBACK_ATOMIC: Final[int]\n    SQLITE_IOERR_SEEK: Final[int]\n    SQLITE_IOERR_SHMLOCK: Final[int]\n    SQLITE_IOERR_SHMMAP: Final[int]\n    SQLITE_IOERR_SHMOPEN: Final[int]\n    SQLITE_IOERR_SHMSIZE: Final[int]\n    SQLITE_IOERR_SHORT_READ: Final[int]\n    SQLITE_IOERR_TRUNCATE: Final[int]\n    SQLITE_IOERR_UNLOCK: Final[int]\n    SQLITE_IOERR_VNODE: Final[int]\n    SQLITE_IOERR_WRITE: Final[int]\n    SQLITE_LIMIT_ATTACHED: Final[int]\n    SQLITE_LIMIT_COLUMN: Final[int]\n    SQLITE_LIMIT_COMPOUND_SELECT: Final[int]\n    SQLITE_LIMIT_EXPR_DEPTH: Final[int]\n    SQLITE_LIMIT_FUNCTION_ARG: Final[int]\n    SQLITE_LIMIT_LENGTH: Final[int]\n    SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final[int]\n    SQLITE_LIMIT_SQL_LENGTH: Final[int]\n    SQLITE_LIMIT_TRIGGER_DEPTH: Final[int]\n    SQLITE_LIMIT_VARIABLE_NUMBER: Final[int]\n    SQLITE_LIMIT_VDBE_OP: Final[int]\n    SQLITE_LIMIT_WORKER_THREADS: Final[int]\n    SQLITE_LOCKED: Final[int]\n    SQLITE_LOCKED_SHAREDCACHE: Final[int]\n    SQLITE_LOCKED_VTAB: Final[int]\n    SQLITE_MISMATCH: Final[int]\n    SQLITE_MISUSE: Final[int]\n    SQLITE_NOLFS: Final[int]\n    SQLITE_NOMEM: Final[int]\n    SQLITE_NOTADB: Final[int]\n    SQLITE_NOTFOUND: Final[int]\n    SQLITE_NOTICE: Final[int]\n    SQLITE_NOTICE_RECOVER_ROLLBACK: Final[int]\n    SQLITE_NOTICE_RECOVER_WAL: Final[int]\n    SQLITE_OK_LOAD_PERMANENTLY: Final[int]\n    SQLITE_OK_SYMLINK: Final[int]\n    SQLITE_PERM: Final[int]\n    SQLITE_PROTOCOL: Final[int]\n    SQLITE_RANGE: Final[int]\n    SQLITE_READONLY: Final[int]\n    SQLITE_READONLY_CANTINIT: Final[int]\n    SQLITE_READONLY_CANTLOCK: Final[int]\n    SQLITE_READONLY_DBMOVED: Final[int]\n    SQLITE_READONLY_DIRECTORY: Final[int]\n    SQLITE_READONLY_RECOVERY: Final[int]\n    SQLITE_READONLY_ROLLBACK: Final[int]\n    SQLITE_ROW: Final[int]\n    SQLITE_SCHEMA: Final[int]\n    SQLITE_TOOBIG: Final[int]\n    SQLITE_WARNING: Final[int]\n    SQLITE_WARNING_AUTOINDEX: Final[int]\n    threadsafety: Final[int]\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: Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None = \"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: Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None,\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: Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None = \"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: Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None = \"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: Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None,\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: Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None = \"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, Literal, TypedDict, final, overload\nfrom typing_extensions import NotRequired, Self, TypeAlias\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\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 _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    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\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: str\n\n# SSL error numbers\nSSL_ERROR_ZERO_RETURN: int\nSSL_ERROR_WANT_READ: int\nSSL_ERROR_WANT_WRITE: int\nSSL_ERROR_WANT_X509_LOOKUP: int\nSSL_ERROR_SYSCALL: int\nSSL_ERROR_SSL: int\nSSL_ERROR_WANT_CONNECT: int\nSSL_ERROR_EOF: int\nSSL_ERROR_INVALID_ERROR_CODE: int\n\n# verify modes\nCERT_NONE: int\nCERT_OPTIONAL: int\nCERT_REQUIRED: int\n\n# verify flags\nVERIFY_DEFAULT: int\nVERIFY_CRL_CHECK_LEAF: int\nVERIFY_CRL_CHECK_CHAIN: int\nVERIFY_X509_STRICT: int\nVERIFY_X509_TRUSTED_FIRST: int\nif sys.version_info >= (3, 10):\n    VERIFY_ALLOW_PROXY_CERTS: int\n    VERIFY_X509_PARTIAL_CHAIN: int\n\n# alert descriptions\nALERT_DESCRIPTION_CLOSE_NOTIFY: int\nALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int\nALERT_DESCRIPTION_BAD_RECORD_MAC: int\nALERT_DESCRIPTION_RECORD_OVERFLOW: int\nALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int\nALERT_DESCRIPTION_HANDSHAKE_FAILURE: int\nALERT_DESCRIPTION_BAD_CERTIFICATE: int\nALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int\nALERT_DESCRIPTION_CERTIFICATE_REVOKED: int\nALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int\nALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int\nALERT_DESCRIPTION_ILLEGAL_PARAMETER: int\nALERT_DESCRIPTION_UNKNOWN_CA: int\nALERT_DESCRIPTION_ACCESS_DENIED: int\nALERT_DESCRIPTION_DECODE_ERROR: int\nALERT_DESCRIPTION_DECRYPT_ERROR: int\nALERT_DESCRIPTION_PROTOCOL_VERSION: int\nALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int\nALERT_DESCRIPTION_INTERNAL_ERROR: int\nALERT_DESCRIPTION_USER_CANCELLED: int\nALERT_DESCRIPTION_NO_RENEGOTIATION: int\nALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int\nALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int\nALERT_DESCRIPTION_UNRECOGNIZED_NAME: int\nALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int\nALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int\nALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int\n\n# protocol versions\nPROTOCOL_SSLv23: int\nPROTOCOL_TLS: int\nPROTOCOL_TLS_CLIENT: int\nPROTOCOL_TLS_SERVER: int\nPROTOCOL_TLSv1: int\nPROTOCOL_TLSv1_1: int\nPROTOCOL_TLSv1_2: int\n\n# protocol options\nOP_ALL: int\nOP_NO_SSLv2: int\nOP_NO_SSLv3: int\nOP_NO_TLSv1: int\nOP_NO_TLSv1_1: int\nOP_NO_TLSv1_2: int\nOP_NO_TLSv1_3: int\nOP_CIPHER_SERVER_PREFERENCE: int\nOP_SINGLE_DH_USE: int\nOP_NO_TICKET: int\nOP_SINGLE_ECDH_USE: int\nOP_NO_COMPRESSION: int\nOP_ENABLE_MIDDLEBOX_COMPAT: int\nOP_NO_RENEGOTIATION: int\nif sys.version_info >= (3, 11) or sys.platform == \"linux\":\n    OP_IGNORE_UNEXPECTED_EOF: int\nif sys.version_info >= (3, 12):\n    OP_LEGACY_SERVER_CONNECT: int\n    OP_ENABLE_KTLS: int\n\n# host flags\nHOSTFLAG_ALWAYS_CHECK_SUBJECT: int\nHOSTFLAG_NEVER_CHECK_SUBJECT: int\nHOSTFLAG_NO_WILDCARDS: int\nHOSTFLAG_NO_PARTIAL_WILDCARDS: int\nHOSTFLAG_MULTI_LABEL_WILDCARDS: int\nHOSTFLAG_SINGLE_LABEL_SUBDOMAINS: int\n\nif sys.version_info >= (3, 10):\n    # certificate file types\n    # Typed as Literal so the overload on Certificate.public_bytes can work properly.\n    ENCODING_PEM: Literal[1]\n    ENCODING_DER: Literal[2]\n\n# protocol versions\nPROTO_MINIMUM_SUPPORTED: int\nPROTO_MAXIMUM_SUPPORTED: int\nPROTO_SSLv3: int\nPROTO_TLSv1: int\nPROTO_TLSv1_1: int\nPROTO_TLSv1_2: int\nPROTO_TLSv1_3: int\n\n# feature support\nHAS_SNI: bool\nHAS_TLS_UNIQUE: bool\nHAS_ECDH: bool\nHAS_NPN: bool\nif sys.version_info >= (3, 13):\n    HAS_PSK: bool\nHAS_ALPN: bool\nHAS_SSLv2: bool\nHAS_SSLv3: bool\nHAS_TLSv1: bool\nHAS_TLSv1_1: bool\nHAS_TLSv1_2: bool\nHAS_TLSv1_3: bool\n\n# version info\nOPENSSL_VERSION_NUMBER: int\nOPENSSL_VERSION_INFO: tuple[int, int, int, int, int]\nOPENSSL_VERSION: str\n_OPENSSL_API_VERSION: 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\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\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\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\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        def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n        def release_lock(self) -> None: ...\n        def locked_lock(self) -> bool: ...\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        def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n        def release_lock(self) -> None: ...\n        def locked_lock(self) -> bool: ...\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\n# Obsolete synonym for start_new_thread()\n@overload\ndef start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ...\n@overload\ndef start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...\n\nif sys.version_info >= (3, 10):\n    def interrupt_main(signum: signal.Signals = ..., /) -> None: ...\n\nelse:\n    def interrupt_main() -> None: ...\n\ndef exit() -> NoReturn: ...\ndef exit_thread() -> NoReturn: ...  # Obsolete synonym for exit()\ndef allocate_lock() -> LockType: ...\ndef allocate() -> LockType: ...  # Obsolete synonym for allocate_lock()\ndef get_ident() -> int: ...\ndef stack_size(size: int = 0, /) -> int: ...\n\nTIMEOUT_MAX: 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\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    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    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 collections.abc import Callable\nfrom typing import Any, ClassVar, Final, final\nfrom typing_extensions import TypeAlias\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, /): ...\n    def call(self, command: Any, /, *args: Any) -> Any: ...\n    def createcommand(self, name, func, /): ...\n    if sys.platform != \"win32\":\n        def createfilehandler(self, file, mask, func, /): ...\n        def deletefilehandler(self, file, /): ...\n\n    def createtimerhandler(self, milliseconds, func, /): ...\n    def deletecommand(self, name, /): ...\n    def dooneevent(self, flags: int = 0, /): ...\n    def eval(self, script: str, /) -> str: ...\n    def evalfile(self, fileName, /): ...\n    def exprboolean(self, s, /): ...\n    def exprdouble(self, s, /): ...\n    def exprlong(self, s, /): ...\n    def exprstring(self, s, /): ...\n    def getboolean(self, arg, /): ...\n    def getdouble(self, arg, /): ...\n    def getint(self, arg, /): ...\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): ...\n    def loadtk(self) -> None: ...\n    def mainloop(self, threshold: int = 0, /): ...\n    def quit(self): ...\n    def record(self, script, /): ...\n    def setvar(self, *ags, **kwargs): ...\n    if sys.version_info < (3, 11):\n        def split(self, arg, /): ...\n\n    def splitlist(self, arg, /): ...\n    def unsetvar(self, *args, **kwargs): ...\n    def wantobjects(self, *args, **kwargs): ...\n    def willdispatch(self): ...\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): ...\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    ): ...\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    ): ...\n\ndef getbusywaitinterval(): ...\ndef setbusywaitinterval(new_val, /): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_tracemalloc.pyi",
    "content": "import sys\nfrom 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: ...\n\nif sys.version_info >= (3, 9):\n    def reset_peak() -> None: ...\n\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 contains 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, 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, 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# 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# CONTRIBUTING.md 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)\n# sentinel: _SentinelType\n# def foo(x: int | None | _SentinelType = ...) -> None: ...\nsentinel: Any\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\n# Comparison protocols\n\nclass SupportsDunderLT(Protocol[_T_contra]):\n    def __lt__(self, other: _T_contra, /) -> bool: ...\n\nclass SupportsDunderGT(Protocol[_T_contra]):\n    def __gt__(self, other: _T_contra, /) -> bool: ...\n\nclass SupportsDunderLE(Protocol[_T_contra]):\n    def __le__(self, other: _T_contra, /) -> bool: ...\n\nclass SupportsDunderGE(Protocol[_T_contra]):\n    def __ge__(self, other: _T_contra, /) -> bool: ...\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 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 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# This protocol is currently under discussion. Use SupportsContainsAndGetItem\n# instead, if you require the __contains__ method.\n# See https://github.com/python/typeshed/issues/11822.\nclass SupportsGetItem(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 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# 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, /) -> 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, /) -> Sequence[int]: ...\n    @overload\n    def __getitem__(self, i: int, /) -> int: ...\n\nclass SizedBuffer(Sized, Buffer, Protocol): ...\n\n# for compatibility with third-party stubs that may use this\n_BufferWithLen: TypeAlias = SizedBuffer  # not stable  # noqa: Y047\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: type[Self], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> Self: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(self: 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\nConvertibleToInt: 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"
  },
  {
    "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 = ...,\n    module_globals: dict[str, Any] | None = ...,\n    source: Any | None = ...,\n) -> None: ...\n@overload\ndef warn_explicit(\n    message: Warning,\n    category: Any,\n    filename: str,\n    lineno: int,\n    module: str | None = ...,\n    registry: dict[str | tuple[str, type[Warning], int], int] | None = ...,\n    module_globals: dict[str, Any] | None = ...,\n    source: Any | 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": "import sys\nfrom collections.abc import Iterable, Iterator, MutableSet\nfrom typing import Any, ClassVar, TypeVar, overload\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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: ...  # type: ignore[override]\n    def discard(self, item: _T) -> None: ...  # type: ignore[override]\n    def copy(self) -> Self: ...\n    def remove(self, item: _T) -> None: ...  # type: ignore[override]\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    if sys.version_info >= (3, 9):\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: str\n        LOCALE_NAME_MAX_LENGTH: int\n        LOCALE_NAME_SYSTEM_DEFAULT: str\n        LOCALE_NAME_USER_DEFAULT: str | None\n\n        LCMAP_FULLWIDTH: int\n        LCMAP_HALFWIDTH: int\n        LCMAP_HIRAGANA: int\n        LCMAP_KATAKANA: int\n        LCMAP_LINGUISTIC_CASING: int\n        LCMAP_LOWERCASE: int\n        LCMAP_SIMPLIFIED_CHINESE: int\n        LCMAP_TITLECASE: int\n        LCMAP_TRADITIONAL_CHINESE: int\n        LCMAP_UPPERCASE: 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    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 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 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 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    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/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(\"Use 'classmethod' with '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(\"Use 'staticmethod' with '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(\"Use 'property' with '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": "import sys\nfrom types import TracebackType\nfrom typing import IO, Any, Literal, NamedTuple, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"Error\", \"open\"]\nelse:\n    __all__ = [\"Error\", \"open\", \"openfp\"]\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\nif sys.version_info < (3, 9):\n    @overload\n    def openfp(f: _File, mode: Literal[\"r\", \"rb\"]) -> Aifc_read: ...\n    @overload\n    def openfp(f: _File, mode: Literal[\"w\", \"wb\"]) -> Aifc_write: ...\n    @overload\n    def openfp(f: _File, mode: str | None = None) -> Any: ...\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\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    \"ONE_OR_MORE\",\n    \"OPTIONAL\",\n    \"PARSER\",\n    \"REMAINDER\",\n    \"SUPPRESS\",\n    \"ZERO_OR_MORE\",\n]\n\nif sys.version_info >= (3, 9):\n    __all__ += [\"BooleanOptionalAction\"]\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# more precisely, Literal[\"store\", \"store_const\", \"store_true\",\n# \"store_false\", \"append\", \"append_const\", \"count\", \"help\", \"version\",\n# \"extend\"], but using this would make it hard to annotate callers\n# that don't use a literal argument\n_ActionStr: TypeAlias = str\n# more precisely, Literal[\"?\", \"*\", \"+\", \"...\", \"A...\",\n# \"==SUPPRESS==\"], but using this would make it hard to annotate\n# callers that don't use a literal argument\n_NArgsStr: TypeAlias = 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[str]  # 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        action: _ActionStr | type[Action] = ...,\n        nargs: int | _NArgsStr | _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    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    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\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\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, 9):\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    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        ) -> 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    def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ...\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    def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None) -> None: ...\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    def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ...\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    if sys.version_info >= (3, 9):\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\nelif sys.version_info >= (3, 9):\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\nclass FileType:\n    # undocumented\n    _mode: str\n    _bufsize: int\n    _encoding: str | None\n    _errors: str | None\n    def __init__(self, mode: str = \"r\", bufsize: int = -1, encoding: str | None = None, errors: str | None = None) -> 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    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, 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 = ...,\n            allow_abbrev: bool = ...,\n            exit_on_error: bool = ...,\n            **kwargs: Any,  # Accepting any additional kwargs for custom parser classes\n        ) -> _ArgumentParserT: ...\n    elif sys.version_info >= (3, 9):\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 = ...,\n            allow_abbrev: bool = ...,\n            exit_on_error: bool = ...,\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 = ...,\n            allow_abbrev: bool = ...,\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\n\n# pytype crashes if array inherits from collections.abc.MutableSequence instead of typing.MutableSequence\nfrom typing import Any, ClassVar, Literal, MutableSequence, SupportsIndex, TypeVar, overload  # noqa: Y022\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 12):\n    from types import GenericAlias\n\n_IntTypeCode: TypeAlias = Literal[\"b\", \"B\", \"h\", \"H\", \"i\", \"I\", \"l\", \"L\", \"q\", \"Q\"]\n_FloatTypeCode: TypeAlias = Literal[\"f\", \"d\"]\n_UnicodeTypeCode: TypeAlias = Literal[\"u\"]\n_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode\n\n_T = TypeVar(\"_T\", int, float, str)\n\ntypecodes: str\n\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    @overload\n    def __new__(\n        cls: type[array[str]], typecode: _UnicodeTypeCode, initializer: bytes | bytearray | Iterable[str] = ..., /\n    ) -> array[str]: ...\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    if sys.version_info < (3, 9):\n        def fromstring(self, buffer: str | ReadableBuffer, /) -> None: ...\n        def tostring(self) -> bytes: ...\n\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __len__(self) -> int: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> _T: ...\n    @overload\n    def __getitem__(self, key: slice, /) -> array[_T]: ...\n    @overload  # type: ignore[override]\n    def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice, value: array[_T], /) -> None: ...\n    def __delitem__(self, key: SupportsIndex | slice, /) -> 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 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\nfrom typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload\nfrom typing_extensions import Self, Unpack, deprecated\n\nif sys.version_info >= (3, 13):\n    from _ast import PyCF_OPTIMIZED_AST as PyCF_OPTIMIZED_AST\n\n# Alias used for fields that must always be valid identifiers\n# A string `x` counts as a valid identifier if both the following are True\n# (1) `x.isidentifier()` evaluates to `True`\n# (2) `keyword.iskeyword(x)` evaluates to `False`\n_Identifier: typing_extensions.TypeAlias = str\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\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.\nclass AST:\n    if sys.version_info >= (3, 10):\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\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: _Identifier\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: _Identifier,\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: _Identifier,\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: _Identifier,\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: _Identifier,\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: _Identifier = ...,\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        ) -> 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: _Identifier\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: _Identifier,\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: _Identifier,\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: _Identifier,\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: _Identifier,\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: _Identifier = ...,\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        ) -> 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: _Identifier\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: _Identifier,\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: _Identifier,\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: _Identifier,\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: _Identifier,\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__(\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__(self, *, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> 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\nif sys.version_info >= (3, 10):\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\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[_Identifier]\n    if sys.version_info >= (3, 13):\n        def __init__(self, names: list[_Identifier] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, names: list[_Identifier], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, names: list[_Identifier], **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Nonlocal(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"names\",)\n    names: list[_Identifier]\n    if sys.version_info >= (3, 13):\n        def __init__(self, names: list[_Identifier] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, names: list[_Identifier], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, names: list[_Identifier] = ..., **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\nclass Constant(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\", \"kind\")\n    value: Any  # None, str, bytes, bool, int, float, complex, Ellipsis\n    kind: str | None\n    if sys.version_info < (3, 14):\n        # Aliases for value, for backwards compatibility\n        s: Any\n        n: int | float | complex\n\n    def __init__(self, value: Any, kind: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: Any = ..., 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: _Identifier\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, value: expr, attr: _Identifier, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, value: expr = ..., attr: _Identifier = ..., 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: _Slice\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, value: expr, slice: _Slice, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, value: expr = ..., slice: _Slice = ..., 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: _Identifier\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, id: _Identifier, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, id: _Identifier = ..., 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    if sys.version_info >= (3, 9):\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): ...  # deprecated and moved to ast.py for >= (3, 9)\n\nif sys.version_info >= (3, 9):\n    _Slice: typing_extensions.TypeAlias = expr\n    _SliceAttributes: typing_extensions.TypeAlias = _Attributes\nelse:\n    # alias for use with variables named slice\n    _Slice: typing_extensions.TypeAlias = slice\n\n    class _SliceAttributes(TypedDict): ...\n\nclass Slice(_Slice):\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[_SliceAttributes]\n    ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            lower: expr | None = ...,\n            upper: expr | None = ...,\n            step: expr | None = ...,\n            **kwargs: Unpack[_SliceAttributes],\n        ) -> Self: ...\n\n@deprecated(\"Deprecated since Python 3.9. Use ast.Tuple instead.\")\nclass ExtSlice(slice):  # deprecated and moved to ast.py if sys.version_info >= (3, 9)\n    if sys.version_info >= (3, 9):\n        def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_SliceAttributes]) -> Tuple: ...  # type: ignore[misc]\n    else:\n        dims: list[slice]\n        def __init__(self, dims: list[slice], **kwargs: Unpack[_SliceAttributes]) -> None: ...\n\n@deprecated(\"Deprecated since Python 3.9. Use the index value directly instead.\")\nclass Index(slice):  # deprecated and moved to ast.py if sys.version_info >= (3, 9)\n    if sys.version_info >= (3, 9):\n        def __new__(cls, value: expr, **kwargs: Unpack[_SliceAttributes]) -> expr: ...  # type: ignore[misc]\n    else:\n        value: expr\n        def __init__(self, value: expr, **kwargs: Unpack[_SliceAttributes]) -> None: ...\n\nclass expr_context(AST): ...\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass AugLoad(expr_context): ...  # deprecated and moved to ast.py if sys.version_info >= (3, 9)\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass AugStore(expr_context): ...  # deprecated and moved to ast.py if sys.version_info >= (3, 9)\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass Param(expr_context): ...  # deprecated and moved to ast.py if sys.version_info >= (3, 9)\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass Suite(mod):  # deprecated and moved to ast.py if sys.version_info >= (3, 9)\n    if sys.version_info < (3, 9):\n        body: list[stmt]\n        def __init__(self, body: list[stmt]) -> None: ...\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: _Identifier | None\n    body: list[stmt]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, type: expr | None = None, name: _Identifier | None = None, body: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self, type: expr | None, name: _Identifier | None, body: list[stmt], **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n        @overload\n        def __init__(\n            self, type: expr | None = None, name: _Identifier | None = None, *, body: list[stmt], **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            type: expr | None = ...,\n            name: _Identifier | None = ...,\n            body: list[stmt] = ...,\n            **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: _Identifier\n    annotation: expr | None\n    type_comment: str | None\n    def __init__(\n        self, arg: _Identifier, 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,\n            *,\n            arg: _Identifier = ...,\n            annotation: expr | None = ...,\n            type_comment: str | None = ...,\n            **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: _Identifier | None\n    value: expr\n    @overload\n    def __init__(self, arg: _Identifier | None, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n    @overload\n    def __init__(self, arg: _Identifier | None = None, *, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, arg: _Identifier | None = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass alias(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__ = (\"name\", \"asname\")\n    name: str\n    asname: _Identifier | None\n    def __init__(self, name: str, asname: _Identifier | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, name: str = ..., asname: _Identifier | 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 match_case(AST):\n        __match_args__ = (\"pattern\", \"guard\", \"body\")\n        pattern: _Pattern\n        guard: expr | None\n        body: list[stmt]\n        if sys.version_info >= (3, 13):\n            def __init__(self, pattern: _Pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ...\n        else:\n            @overload\n            def __init__(self, pattern: _Pattern, guard: expr | None, body: list[stmt]) -> None: ...\n            @overload\n            def __init__(self, pattern: _Pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, pattern: _Pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ...\n\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    # Without the alias, Pyright complains variables named pattern are recursively defined\n    _Pattern: typing_extensions.TypeAlias = pattern\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: Literal[True, False] | None\n        def __init__(self, value: Literal[True, False] | None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, value: Literal[True, False] | 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: _Identifier | None\n        if sys.version_info >= (3, 13):\n            def __init__(\n                self,\n                keys: list[expr] = ...,\n                patterns: list[pattern] = ...,\n                rest: _Identifier | None = None,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> None: ...\n        else:\n            def __init__(\n                self,\n                keys: list[expr],\n                patterns: list[pattern],\n                rest: _Identifier | None = None,\n                **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: _Identifier | 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[_Identifier]\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[_Identifier] = ...,\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[_Identifier],\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[_Identifier] = ...,\n                kwd_patterns: list[pattern] = ...,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> Self: ...\n\n    class MatchStar(pattern):\n        __match_args__ = (\"name\",)\n        name: _Identifier | None\n        def __init__(self, name: _Identifier | None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, name: _Identifier | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\n    class MatchAs(pattern):\n        __match_args__ = (\"pattern\", \"name\")\n        pattern: _Pattern | None\n        name: _Identifier | None\n        def __init__(\n            self, pattern: _Pattern | None = None, name: _Identifier | None = None, **kwargs: Unpack[_Attributes[int]]\n        ) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, pattern: _Pattern | None = ..., name: _Identifier | 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: _Identifier\n        bound: expr | None\n        if sys.version_info >= (3, 13):\n            default_value: expr | None\n            def __init__(\n                self,\n                name: _Identifier,\n                bound: expr | None = None,\n                default_value: expr | None = None,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> None: ...\n        else:\n            def __init__(self, name: _Identifier, 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: _Identifier = ...,\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: _Identifier\n        if sys.version_info >= (3, 13):\n            default_value: expr | None\n            def __init__(\n                self, name: _Identifier, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n        else:\n            def __init__(self, name: _Identifier, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, name: _Identifier = ..., 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: _Identifier\n        if sys.version_info >= (3, 13):\n            default_value: expr | None\n            def __init__(\n                self, name: _Identifier, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n        else:\n            def __init__(self, name: _Identifier, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, name: _Identifier = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]]\n            ) -> Self: ...\n\nclass _ABC(type):\n    if sys.version_info >= (3, 9):\n        def __init__(cls, *args: Unused) -> None: ...\n\nif sys.version_info < (3, 14):\n    @deprecated(\"Replaced by ast.Constant; removed in Python 3.14\")\n    class Num(Constant, metaclass=_ABC):\n        value: int | float | complex\n\n    @deprecated(\"Replaced by ast.Constant; removed in Python 3.14\")\n    class Str(Constant, metaclass=_ABC):\n        value: str\n        # Aliases for value, for backwards compatibility\n        s: str\n\n    @deprecated(\"Replaced by ast.Constant; removed in Python 3.14\")\n    class Bytes(Constant, metaclass=_ABC):\n        value: bytes\n        # Aliases for value, for backwards compatibility\n        s: bytes\n\n    @deprecated(\"Replaced by ast.Constant; removed in Python 3.14\")\n    class NameConstant(Constant, metaclass=_ABC): ...\n\n    @deprecated(\"Replaced by ast.Constant; removed in Python 3.14\")\n    class Ellipsis(Constant, metaclass=_ABC): ...\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: str | ReadableBuffer,\n        filename: str | ReadableBuffer | 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 | ReadableBuffer | 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 | ReadableBuffer | 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 | ReadableBuffer | 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 | ReadableBuffer | 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    ) -> AST: ...\n\nelse:\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | ReadableBuffer | 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 | ReadableBuffer | 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 | ReadableBuffer | 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 | ReadableBuffer | 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 | ReadableBuffer | os.PathLike[Any] = \"<unknown>\",\n        mode: str = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> AST: ...\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\nelif sys.version_info >= (3, 9):\n    def dump(\n        node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None\n    ) -> str: ...\n\nelse:\n    def dump(node: AST, annotate_fields: bool = True, include_attributes: bool = False) -> 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    def visit(self, node: AST) -> Any: ...\n    def generic_visit(self, node: AST) -> Any: ...\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(\"Replaced by visit_Constant; removed in Python 3.14\")\n        def visit_Num(self, node: Num) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Replaced by visit_Constant; removed in Python 3.14\")\n        def visit_Str(self, node: Str) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Replaced by visit_Constant; removed in Python 3.14\")\n        def visit_Bytes(self, node: Bytes) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Replaced by visit_Constant; removed in Python 3.14\")\n        def visit_NameConstant(self, node: NameConstant) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Replaced by visit_Constant; removed in Python 3.14\")\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\nif sys.version_info >= (3, 9):\n    def unparse(ast_obj: AST) -> str: ...\n\nif sys.version_info >= (3, 9):\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": "import 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 .transports import *\n\nif sys.version_info >= (3, 9):\n    from .threads 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        __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            \"_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, 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    elif sys.version_info >= (3, 10):\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        )\n    elif sys.version_info >= (3, 9):\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        )\n    else:\n        __all__ = (\n            \"BaseEventLoop\",  # 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            \"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            \"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            \"_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            \"DefaultEventLoopPolicy\",  # 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    elif sys.version_info >= (3, 10):\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    elif sys.version_info >= (3, 9):\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    else:\n        __all__ = (\n            \"BaseEventLoop\",  # 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            \"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            \"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 contextvars import Context\nfrom socket import AddressFamily, 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\nif sys.version_info >= (3, 9):\n    __all__ = (\"BaseEventLoop\", \"Server\")\nelse:\n    __all__ = (\"BaseEventLoop\",)\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, 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: Any, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ...\n    def set_default_executor(self, executor: Any) -> None: ...\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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    elif sys.version_info >= (3, 9):\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 collections.abc import Callable, Sequence\nfrom contextvars import Context\nfrom typing import Any, Final\n\nfrom . import futures\n\n__all__ = ()\n\n# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py\n# but it leads to circular import error in pytype tool.\n# That's why the import order is reversed.\nfrom .futures import isfuture as isfuture\n\n_PENDING: Final = \"PENDING\"  # undocumented\n_CANCELLED: Final = \"CANCELLED\"  # undocumented\n_FINISHED: Final = \"FINISHED\"  # undocumented\n\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\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    def coroutine(func: _FunctionT) -> _FunctionT: ...\n\n@overload\ndef iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ...\n@overload\ndef iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ...\n@overload\ndef iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ...\n@overload\ndef iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ...\ndef iscoroutine(obj: object) -> TypeIs[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 contextvars import Context\nfrom socket import AddressFamily, SocketKind, _Address, _RetAddress, socket\nfrom typing import IO, Any, Literal, Protocol, TypeVar, overload\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\nfrom .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        \"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        \"_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\nclass _TaskFactory(Protocol):\n    def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ...\n\nclass Handle:\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    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    if sys.version_info >= (3, 9):  # \"context\" added in 3.9.10/3.10.2\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    else:\n        @abstractmethod\n        def call_soon(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> Handle: ...\n        @abstractmethod\n        def call_later(self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> TimerHandle: ...\n        @abstractmethod\n        def call_at(self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> TimerHandle: ...\n\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, 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    if sys.version_info >= (3, 9):  # \"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    else:\n        @abstractmethod\n        def call_soon_threadsafe(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> Handle: ...\n\n    @abstractmethod\n    def run_in_executor(self, executor: Any, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ...\n    @abstractmethod\n    def set_default_executor(self, executor: Any) -> 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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\n            flags: int = ...,\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 = ...,\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    if sys.version_info >= (3, 9):\n        @abstractmethod\n        async def shutdown_default_executor(self) -> None: ...\n\nclass 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, 14):\n        if sys.version_info >= (3, 12):\n            @abstractmethod\n            @deprecated(\"Deprecated as of Python 3.12; will be removed in Python 3.14\")\n            def get_child_watcher(self) -> AbstractChildWatcher: ...\n            @abstractmethod\n            @deprecated(\"Deprecated as of Python 3.12; will be 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\nclass 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\ndef get_event_loop_policy() -> AbstractEventLoopPolicy: ...\ndef set_event_loop_policy(policy: AbstractEventLoopPolicy | None) -> None: ...\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 as of Python 3.12; will be removed in Python 3.14\")\n        def get_child_watcher() -> AbstractChildWatcher: ...\n        @deprecated(\"Deprecated as of Python 3.12; will be 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\nfrom typing_extensions import TypeAlias\n\nclass _HasWrapper:\n    __wrapper__: _HasWrapper | FunctionType[..., Any]\n\n_FuncType: TypeAlias = FunctionType[..., Any] | _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": "from _asyncio import Future as Future\nfrom concurrent.futures._base import Future as _ConcurrentFuture\nfrom typing import Any, TypeVar\nfrom typing_extensions import TypeIs\n\nfrom .events import AbstractEventLoop\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"Future\", \"wrap_future\", \"isfuture\")\n\n_T = TypeVar(\"_T\")\n\n# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py\n# but it leads to circular import error in pytype tool.\n# That's why the import order is reversed.\ndef isfuture(obj: object) -> TypeIs[Future[Any]]: ...\ndef wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ...\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, Generator\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\nif sys.version_info >= (3, 9):\n    class _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\nelse:\n    class _ContextManager:\n        def __init__(self, lock: Lock | Semaphore) -> None: ...\n        def __enter__(self) -> None: ...\n        def __exit__(self, *args: Unused) -> None: ...\n\n    class _ContextManagerMixin:\n        # Apparently this exists to *prohibit* use as a context manager.\n        # def __enter__(self) -> NoReturn: ... see: https://github.com/python/typing/issues/1043\n        # def __exit__(self, *args: Any) -> None: ...\n        def __iter__(self) -> Generator[Any, None, _ContextManager]: ...\n        def __await__(self) -> Generator[Any, None, _ContextManager]: ...\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: ... # type: ignore[override]\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    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    def data_received(self, data: bytes) -> None: ...\n    def eof_received(self) -> bool | None: ...\n\nclass BufferedProtocol(BaseProtocol):\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    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    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 asyncio.events import AbstractEventLoop\nfrom typing import Any, Generic, TypeVar\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    if sys.version_info >= (3, 9):\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[_T]): ...\nclass LifoQueue(Queue[_T]): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/runners.pyi",
    "content": "import sys\nfrom _typeshed import Unused\nfrom collections.abc import 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        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 = ..., loop_factory: Callable[[], AbstractEventLoop] | 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: ...  # type: ignore[override]\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) -> None: ...\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\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\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 = ...,\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 = ...,\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 = ...,\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 = ...,\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    def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: ...\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, Literal, Protocol, TypeVar, overload\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_TaskYieldType: TypeAlias = Future[object] | None\n\nFIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED\nFIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION\nALL_COMPLETED = concurrent.futures.ALL_COMPLETED\n\nif sys.version_info >= (3, 13):\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\ndef run_coroutine_threadsafe(coro: _FutureLike[_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    @overload\n    async def wait(\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[Task[_T]], *, timeout: float | None = None, return_when: str = \"ALL_COMPLETED\"\n    ) -> tuple[set[Task[_T]], set[Task[_T]]]: ...\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]\nelif sys.version_info >= (3, 9):\n    _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co]\nelse:\n    _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co]\n\ndef all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ...\n\nif 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, 12):\n    _TaskT_co = TypeVar(\"_TaskT_co\", bound=Task[Any], covariant=True)\n\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    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    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"
  },
  {
    "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/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    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    def is_reading(self) -> bool: ...\n    def pause_reading(self) -> None: ...\n    def resume_reading(self) -> None: ...\n\nclass WriteTransport(BaseTransport):\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) -> None: ...\n    def writelines(self, list_of_data: Iterable[bytes | bytearray | memoryview]) -> None: ...\n    def write_eof(self) -> None: ...\n    def can_write_eof(self) -> bool: ...\n    def abort(self) -> None: ...\n\nclass Transport(ReadTransport, WriteTransport): ...\n\nclass DatagramTransport(BaseTransport):\n    def sendto(self, data: bytes | bytearray | memoryview, addr: _Address | None = None) -> None: ...\n    def abort(self) -> None: ...\n\nclass SubprocessTransport(BaseTransport):\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    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\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    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        def accept(self) -> tuple[socket.socket, _RetAddress]: ...\n        def connect(self, address: _Address) -> None: ...\n        def connect_ex(self, address: _Address) -> int: ...\n        def bind(self, address: _Address) -> None: ...\n        if sys.platform == \"win32\":\n            def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ...\n        else:\n            def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ...\n\n        def listen(self, backlog: int = ..., /) -> None: ...\n        def makefile(self) -> BinaryIO: ...\n        def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ...\n        def close(self) -> None: ...\n        def detach(self) -> int: ...\n        if sys.platform == \"linux\":\n            def sendmsg_afalg(\n                self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ...\n            ) -> int: ...\n        else:\n            def sendmsg_afalg(\n                self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ...\n            ) -> NoReturn: ...\n\n        def sendmsg(\n            self, buffers: Iterable[ReadableBuffer], ancdata: Iterable[_CMSG] = ..., flags: int = ..., address: _Address = ..., /\n        ) -> int: ...\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        def send(self, data: ReadableBuffer, flags: int = ...) -> int: ...\n        def sendall(self, data: ReadableBuffer, flags: int = ...) -> None: ...\n        def set_inheritable(self, inheritable: bool) -> None: ...\n        if sys.platform == \"win32\":\n            def share(self, process_id: int) -> bytes: ...\n        else:\n            def share(self, process_id: int) -> NoReturn: ...\n\n        def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ...\n        def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ...\n        def recvmsg_into(\n            self, buffers: Iterable[_WriteBuffer], ancbufsize: int = ..., flags: int = ..., /\n        ) -> tuple[int, list[_CMSG], int, Any]: ...\n        def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ...\n        def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ...\n        def recv(self, bufsize: int, flags: int = ...) -> bytes: ...\n        def __enter__(self) -> socket.socket: ...\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 .base_events import Server, _ProtocolFactory, _SSLContext\nfrom .events import AbstractEventLoop, BaseDefaultEventLoopPolicy\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\", \"DefaultEventLoopPolicy\", \"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    elif sys.version_info >= (3, 9):\n        # adds PidfdChildWatcher\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"AbstractChildWatcher\",\n            \"SafeChildWatcher\",\n            \"FastChildWatcher\",\n            \"PidfdChildWatcher\",\n            \"MultiLoopChildWatcher\",\n            \"ThreadedChildWatcher\",\n            \"DefaultEventLoopPolicy\",\n        )\n    else:\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"AbstractChildWatcher\",\n            \"SafeChildWatcher\",\n            \"FastChildWatcher\",\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 as of Python 3.12; will be 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: 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: 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: AbstractEventLoop | None) -> None: ...\n\n            @deprecated(\"Deprecated as of Python 3.12; will be 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 as of Python 3.12; will be 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: 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    class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy):\n        if sys.version_info < (3, 14):\n            if sys.version_info >= (3, 12):\n                @deprecated(\"Deprecated as of Python 3.12; will be removed in Python 3.14\")\n                def get_child_watcher(self) -> AbstractChildWatcher: ...\n                @deprecated(\"Deprecated as of Python 3.12; will be 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    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 as of Python 3.12; will be 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: 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: 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: AbstractEventLoop | None) -> None: ...\n\n        if sys.version_info >= (3, 9):\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: 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, 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    class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):\n        _loop_factory: ClassVar[type[SelectorEventLoop]]\n        if sys.version_info < (3, 14):\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    DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy\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 = subprocess.PIPE\n    STDOUT = 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 = ...,\n            stdout: subprocess._FILE | None = ...,\n            stderr: subprocess._FILE | 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, 9):\n    def encodestring(s: ReadableBuffer) -> bytes: ...\n    def decodestring(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, Mapping\nfrom types import CodeType, FrameType, TracebackType\nfrom typing import IO, Any, Final, SupportsInt, TypeVar\nfrom typing_extensions import ParamSpec\n\n__all__ = [\"BdbQuit\", \"Bdb\", \"Breakpoint\"]\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\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    def __init__(self, skip: Iterable[str] | None = None) -> None: ...\n    def canonic(self, filename: str) -> str: ...\n    def reset(self) -> None: ...\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[Breakpoint]: ...\n    def get_all_breaks(self) -> list[Breakpoint]: ...\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: 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\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\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    def a2b_hqx(data: _AsciiBuffer, /) -> bytes: ...\n    def rledecode_hqx(data: ReadableBuffer, /) -> bytes: ...\n    def rlecode_hqx(data: ReadableBuffer, /) -> bytes: ...\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 = ...) -> bytes: ...\ndef hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> 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": "# ruff: noqa: PYI036 # This is the module declaring BaseException\nimport _ast\nimport _sitebuiltins\nimport _typeshed\nimport sys\nimport types\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import (\n    ConvertibleToFloat,\n    ConvertibleToInt,\n    FileDescriptorOrPath,\n    MaybeNone,\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 types import BuiltinFunctionType, CellType, CodeType, 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\n    _NamedCallable,\n    IO,\n    Any,\n    AnyStr,\n    BinaryIO,\n    ClassVar,\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)\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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 = TypeVar(\"_SupportsNextT\", bound=SupportsNext[Any], covariant=True)\n_SupportsAnextT = TypeVar(\"_SupportsAnextT\", 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_StartT = TypeVar(\"_StartT\", covariant=True, default=Any)\n_StopT = TypeVar(\"_StopT\", covariant=True, default=Any)\n_StepT = TypeVar(\"_StepT\", covariant=True, default=Any)\n\nclass object:\n    __doc__: str | None\n    __dict__: dict[str, object]\n    __module__: str\n    __annotations__: dict[str, object]\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, /) -> object: ...\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\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    # TODO: doesn't actually return `_NamedCallable`, it returns the callable that was passed to the constructor\n    @overload\n    def __get__(self, instance: None, owner: type, /) -> _NamedCallable[_P, _R_co]: ...\n    @overload\n    def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> _NamedCallable[_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\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\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    @property\n    def __dict__(self) -> types.MappingProxyType[str, object]: ...  # type: ignore[override]\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    # TODO: dict: dict[str, Out[object]]\n    def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: object) -> 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: object\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: object, /) -> 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        def __or__(self, value: Any, /) -> types.UnionType: ...\n        def __ror__(self, value: Any, /) -> types.UnionType: ...\n    if sys.version_info >= (3, 12):\n        __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]\n\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\nclass int:\n    @overload\n    def __new__(cls, x: ConvertibleToInt = ..., /) -> 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    def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ...\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\nclass float:\n    def __new__(cls, x: ConvertibleToFloat = ..., /) -> 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    if sys.version_info >= (3, 9):\n        def __ceil__(self) -> int: ...\n        def __floor__(self) -> int: ...\n\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\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 = ...,\n        imag: complex | SupportsFloat | SupportsIndex = ...,\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    if sys.version_info >= (3, 11):\n        def __complex__(self) -> complex: ...\n\nclass _FormatMapMapping(Protocol):\n    def __getitem__(self, key: str, /) -> Any: ...\n\nclass _TranslateTable(Protocol):\n    def __getitem__(self, key: int, /) -> str | int | None: ...\n\nclass str(Sequence[str]):\n    @overload\n    def __new__(cls, object: object = ...) -> Self: ...\n    @overload\n    def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> 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 = ..., end: SupportsIndex | None = ..., /) -> int: ...  # type: ignore[override]\n    def encode(self, encoding: str = \"utf-8\", errors: str = \"strict\") -> bytes: ...\n    def endswith(\n        self, suffix: str | tuple[str, ...], start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /\n    ) -> bool: ...\n    def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ...  # type: ignore[misc]\n    def find(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ..., end: SupportsIndex | None = ..., /) -> int: ...  # type: ignore[override]\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    if sys.version_info >= (3, 9):\n        def removeprefix(self, prefix: str, /) -> str: ...  # type: ignore[misc]\n        def removesuffix(self, suffix: str, /) -> str: ...  # type: ignore[misc]\n\n    def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ...\n    def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ..., end: SupportsIndex | 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, /) -> str: ...\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\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 = ...) -> 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(  # type: ignore[override]\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ...,\n        end: SupportsIndex | None = ...,\n        /,\n    ) -> bool: ...\n    def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ...\n    def find(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /\n    ) -> int: ...\n    def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ...\n    def index(  # type: ignore[override]\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | 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    if sys.version_info >= (3, 9):\n        def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ...\n        def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ...\n\n    def rfind(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /\n    ) -> int: ...\n    def rindex(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ...,\n        end: SupportsIndex | 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: bytes = b\"\") -> bytes: ...\n    def upper(self) -> bytes: ...\n    def zfill(self, width: SupportsIndex, /) -> bytes: ...\n    @classmethod\n    def fromhex(cls, string: str, /) -> Self: ...\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, /) -> 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\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 = ...) -> None: ...\n    def append(self, item: SupportsIndex, /) -> None: ...  # type: ignore[override]\n    def capitalize(self) -> bytearray: ...\n    def center(self, width: SupportsIndex, fillchar: bytes = b\" \", /) -> bytearray: ...\n    def count(  # type: ignore[override]\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ...,\n        end: SupportsIndex | None = ...,\n        /,\n    ) -> bool: ...\n    def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ...\n    def extend(self, iterable_of_ints: Iterable[SupportsIndex], /) -> None: ...  # type: ignore[override]\n    def find(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /\n    ) -> int: ...\n    def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ...\n    def index(  # type: ignore[override]\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /\n    ) -> int: ...\n    def insert(self, index: SupportsIndex, item: SupportsIndex, /) -> None: ...  # type: ignore[override]\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: ...  # type: ignore[override]\n    def remove(self, value: int, /) -> None: ...  # type: ignore[override]\n    if sys.version_info >= (3, 9):\n        def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ...\n        def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ...\n\n    def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ...\n    def rfind(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /\n    ) -> int: ...\n    def rindex(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | 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 = ...,\n        end: SupportsIndex | 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    @classmethod\n    def fromhex(cls, string: str, /) -> Self: ...\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, /) -> bytearray: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice, value: Iterable[SupportsIndex] | bytes, /) -> None: ...\n    def __delitem__(self, key: SupportsIndex | slice, /) -> 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\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, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, /\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, /) -> 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, 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 = ...) -> str: ...\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __release_buffer__(self, buffer: memoryview, /) -> None: ...\n\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@final\nclass bool(int):\n    def __new__(cls, o: object = ..., /) -> 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.14. Use `not` for logical negation of bools instead.\")\n    def __invert__(self) -> int: ...\n\n@final\nclass slice(Generic[_StartT, _StopT, _StepT]):\n    @property\n    def start(self) -> _StartT: ...\n    @property\n    def step(self) -> _StepT: ...\n    @property\n    def stop(self) -> _StopT: ...\n    @overload\n    def __new__(cls, stop: int | None, /) -> slice[int | MaybeNone, int | MaybeNone, int | MaybeNone]: ...\n    @overload\n    def __new__(\n        cls, start: int | None, stop: int | None, step: int | None = None, /\n    ) -> slice[int | MaybeNone, int | MaybeNone, int | MaybeNone]: ...\n    @overload\n    def __new__(cls, stop: _T2, /) -> slice[Any, _T2, Any]: ...\n    @overload\n    def __new__(cls, start: _T1, stop: _T2, /) -> slice[_T1, _T2, Any]: ...\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\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, /) -> 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: ...  # type: ignore[override]\n    def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ...  # type: ignore[override]\n    if sys.version_info >= (3, 9):\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@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[object, ...] | None\n    __dict__: dict[str, object]\n    @property\n    def __globals__(self) -> dict[str, object]: ...\n    __name__: str\n    __qualname__: str\n    __annotations__: dict[str, object]\n    __kwdefaults__: dict[str, object]\n    if sys.version_info >= (3, 10):\n        @property\n        def __builtins__(self) -> dict[str, object]: ...\n    if sys.version_info >= (3, 12):\n        __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]\n\n    __module__: str\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\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: ...  # type: ignore[override]\n    def extend(self, iterable: Iterable[_T], /) -> None: ...  # type: ignore[override]\n    def pop(self, index: SupportsIndex = -1, /) -> _T: ...  # type: ignore[override]\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: ...  # type: ignore[override]\n    def count(self, value: _T, /) -> int: ...  # type: ignore[override]\n    def insert(self, index: SupportsIndex, object: _T, /) -> None: ...  # type: ignore[override]\n    def remove(self, value: _T, /) -> None: ...  # type: ignore[override]\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, /) -> list[_T]: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice, value: Iterable[_T], /) -> None: ...\n    def __delitem__(self, key: SupportsIndex | slice, /) -> 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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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, /) -> _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  # type: ignore[override]\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    if sys.version_info >= (3, 9):\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\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: ...  # type: ignore[override]\n    def copy(self) -> set[_T]: ...\n    def difference(self, /, *s: Iterable[object]) -> set[_T]: ...\n    def difference_update(self, /, *s: Iterable[object]) -> None: ...\n    def discard(self, element: _T, /) -> None: ...  # type: ignore[override]\n    def intersection(self, /, *s: Iterable[object]) -> set[_T]: ...\n    def intersection_update(self, /, *s: Iterable[object]) -> None: ...\n    def isdisjoint(self, s: Iterable[object], /) -> bool: ...  # type: ignore[override]\n    def issubset(self, s: Iterable[object], /) -> bool: ...\n    def issuperset(self, s: Iterable[object], /) -> bool: ...\n    def remove(self, element: _T, /) -> None: ...  # type: ignore[override]\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    __hash__: ClassVar[None]  # type: ignore[assignment]\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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: ...  # type: ignore[override]\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[_T_co], /) -> 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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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    if sys.version_info >= (3, 9):\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 = ..., /) -> Self: ...\n    def count(self, value: int, /) -> int: ...  # type: ignore[override]\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, /) -> range: ...\n    def __reversed__(self) -> Iterator[int]: ...\n\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 = ...,\n        fset: Callable[[Any, Any], None] | None = ...,\n        fdel: Callable[[Any], None] | None = ...,\n        doc: str | 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    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 _NotImplementedType(Any):\n    __call__: None\n\nNotImplemented: _NotImplementedType\n\n@type_check_only\ndef _as_builtin(fn: Callable[_P, _T]) -> BuiltinFunctionType[_P, _T]: ...\n\n@_as_builtin\ndef abs(x: SupportsAbs[_T], /) -> _T: ...\n@_as_builtin\ndef all(iterable: Iterable[object], /) -> bool: ...\n@_as_builtin\ndef any(iterable: Iterable[object], /) -> bool: ...\n@_as_builtin\ndef ascii(obj: object, /) -> str: ...\n@_as_builtin\ndef bin(number: int | SupportsIndex, /) -> str: ...\n@_as_builtin\ndef breakpoint(*args: Any, **kws: Any) -> None: ...\ncallable: BuiltinFunctionType[[object], TypeIs[Callable[..., object]]]\n@_as_builtin\ndef chr(i: int, /) -> str: ...\n\n# We define this here instead of using os.PathLike to avoid import cycle issues.\n# See https://github.com/python/typeshed/pull/991#issuecomment-288160993\nclass _PathLike(Protocol[AnyStr]):\n    def __fspath__(self) -> AnyStr: ...\n\nif sys.version_info >= (3, 10):\n    @_as_builtin\n    def aiter(async_iterable: SupportsAiter[_SupportsAnextT], /) -> _SupportsAnextT: ...\n\n    class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]):\n        def __anext__(self) -> _AwaitableT_co: ...\n\n    @_as_builtin\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    @_as_builtin\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@_as_builtin\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | ReadableBuffer | _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@_as_builtin\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | ReadableBuffer | _PathLike[Any],\n    mode: str,\n    *,\n    dont_inherit: bool = False,\n    optimize: int = -1,\n    _feature_version: int = -1,\n) -> CodeType: ...\n@_as_builtin\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | ReadableBuffer | _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@_as_builtin\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | ReadableBuffer | _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: ...\n@_as_builtin\ndef dir(o: object = ..., /) -> list[str]: ...\n@_as_builtin\n@overload\ndef divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ...\n@_as_builtin\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    @_as_builtin\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    @_as_builtin\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    @_as_builtin\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    @_as_builtin\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    @_as_builtin\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\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\n@_as_builtin\ndef format(value: object, format_spec: str = \"\", /) -> str: ...\n@_as_builtin\ndef getattr(o: object, name: str, default: object = ..., /) -> object: ...\n@_as_builtin\ndef globals() -> dict[str, object]: ...\n@_as_builtin\ndef hasattr(obj: object, name: str, /) -> bool: ...\n@_as_builtin\ndef hash(obj: object, /) -> int: ...\n\nhelp: _sitebuiltins._Helper\n\ndef hex(number: int | SupportsIndex, /) -> str: ...\n@_as_builtin\ndef id(obj: object, /) -> int: ...\n@_as_builtin\ndef input(prompt: object = \"\", /) -> str: ...\n\nclass _GetItemIterable(Protocol[_T_co]):\n    def __getitem__(self, i: int, /) -> _T_co: ...\n\n@_as_builtin\n@overload\ndef iter(object: SupportsIter[_SupportsNextT], /) -> _SupportsNextT: ...\n@_as_builtin\n@overload\ndef iter(object: _GetItemIterable[_T], /) -> Iterator[_T]: ...\n@_as_builtin\n@overload\ndef iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: ...\n@_as_builtin\n@overload\ndef iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ...\n\n# Keep this alias in sync with unittest.case._ClassInfo\nif sys.version_info >= (3, 10):\n    _ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...]\nelse:\n    _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...]\n\n@_as_builtin\ndef isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: ...\n@_as_builtin\ndef issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: ...\n@_as_builtin\ndef len(obj: Sized, /) -> int: ...\n\nlicense: _sitebuiltins._Printer\n\n@_as_builtin\ndef locals() -> dict[str, object]: ...\n\nclass map(Iterator[_S]):\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    def __iter__(self) -> Self: ...\n    def __next__(self) -> _S: ...\n\n@_as_builtin\n@overload\ndef max(\n    arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None\n) -> SupportsRichComparisonT: ...\n@_as_builtin\n@overload\ndef max(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@_as_builtin\n@overload\ndef max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ...\n@_as_builtin\n@overload\ndef max(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@_as_builtin\n@overload\ndef max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ...\n@_as_builtin\n@overload\ndef max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ...\n@_as_builtin\n@overload\ndef min(\n    arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None\n) -> SupportsRichComparisonT: ...\n@_as_builtin\n@overload\ndef min(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@_as_builtin\n@overload\ndef min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ...\n@_as_builtin\n@overload\ndef min(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@_as_builtin\n@overload\ndef min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ...\n@_as_builtin\n@overload\ndef min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ...\n@_as_builtin\n@overload\ndef next(i: SupportsNext[_T], /) -> _T: ...\n@_as_builtin\n@overload\ndef next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ...\n@_as_builtin\ndef oct(number: int | SupportsIndex, /) -> str: ...\n\n_Opener: TypeAlias = Callable[[str, int], int]\n\n# `open` is a `BuiltinFunctionType`, but isn't typed correctly due to a type cycle with `io`\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]: ...\n@_as_builtin\ndef ord(c: str | bytes | bytearray, /) -> int: ...\n\nclass _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ...\n\n@_as_builtin\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@_as_builtin\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 = TypeVar(\"_E\", contravariant=True)\n_M = TypeVar(\"_M\", contravariant=True)\n\nclass _SupportsPow2(Protocol[_E, _T_co]):\n    def __pow__(self, other: _E, /) -> _T_co: ...\n\nclass _SupportsPow3NoneOnly(Protocol[_E, _T_co]):\n    def __pow__(self, other: _E, modulo: None = None, /) -> _T_co: ...\n\nclass _SupportsPow3(Protocol[_E, _M, _T_co]):\n    def __pow__(self, other: _E, modulo: _M, /) -> _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@_as_builtin\n@overload\ndef pow(base: int, exp: int, mod: int) -> int: ...\n@_as_builtin\n@overload\ndef pow(base: int, exp: Literal[0], mod: None = None) -> Literal[1]: ...\n@_as_builtin\n@overload\ndef pow(base: int, exp: _PositiveInteger, mod: None = None) -> int: ...\n@_as_builtin\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@_as_builtin\n@overload\ndef pow(base: int, exp: int, mod: None = None) -> Any: ...\n@_as_builtin\n@overload\ndef pow(base: _PositiveInteger, exp: float, mod: None = None) -> float: ...\n@_as_builtin\n@overload\ndef pow(base: _NegativeInteger, exp: float, mod: None = None) -> complex: ...\n@_as_builtin\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@_as_builtin\n@overload\ndef pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ...\n@_as_builtin\n@overload\ndef pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ...\n@_as_builtin\n@overload\ndef pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ...  # type: ignore[overload-overlap]\n@_as_builtin\n@overload\ndef pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ...  # type: ignore[overload-overlap]\n@_as_builtin\n@overload\ndef pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ...\n@_as_builtin\n@overload\ndef pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ...\n@_as_builtin\n@overload\ndef pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ...\n\nquit: _sitebuiltins.Quitter\n\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\n@_as_builtin\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\nclass _SupportsRound1(Protocol[_T_co]):\n    def __round__(self) -> _T_co: ...\n\nclass _SupportsRound2(Protocol[_T_co]):\n    def __round__(self, ndigits: int, /) -> _T_co: ...\n\n@_as_builtin\n@overload\ndef round(number: _SupportsRound1[_T], ndigits: None = None) -> _T: ...\n@_as_builtin\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`\n@_as_builtin\ndef setattr(obj: object, name: str, value: Any, /) -> None: ...\n@_as_builtin\n@overload\ndef sorted(\n    iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False\n) -> list[SupportsRichComparisonT]: ...\n@_as_builtin\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\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@_as_builtin\n@overload\ndef sum(iterable: Iterable[bool], /, start: int = 0) -> int: ...\n@_as_builtin\n@overload\ndef sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ...\n@_as_builtin\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# Use a type: ignore to make complaints about overlapping overloads go away\n@_as_builtin\n@overload\ndef vars(object: type, /) -> types.MappingProxyType[str, Any]: ...\n@_as_builtin\n@overload\ndef vars(object: Any = ..., /) -> dict[str, Any]: ...\n\nclass zip(Iterator[_T_co]):\n    if sys.version_info >= (3, 10):\n        @overload\n        def __new__(cls, *, strict: bool = ...) -> zip[Any]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = ...) -> zip[tuple[_T1]]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = ...) -> zip[tuple[_T1, _T2]]: ...\n        @overload\n        def __new__(\n            cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = ...\n        ) -> zip[tuple[_T1, _T2, _T3]]: ...\n        @overload\n        def __new__(\n            cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, strict: bool = ...\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 = ...,\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 = ...,\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`\n@_as_builtin\ndef __import__(\n    name: str,\n    globals: Mapping[str, object] | None = None,\n    locals: Mapping[str, object] | None = None,\n    fromlist: Sequence[str] = (),\n    level: int = 0,\n) -> types.ModuleType: ...\n@_as_builtin\ndef __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ...\n\n# 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\nclass ellipsis: ...\n\nEllipsis: ellipsis\n\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    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\nclass SystemExit(BaseException):\n    code: sys._ExitCode\n\nclass Exception(BaseException): ...\n\nclass StopIteration(Exception):\n    value: Any\n\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\nclass AttributeError(Exception):\n    if sys.version_info >= (3, 10):\n        def __init__(self, *args: object, name: str | None = ..., obj: object = ...) -> None: ...\n        name: str\n        obj: object\n\nclass BufferError(Exception): ...\nclass EOFError(Exception): ...\n\nclass ImportError(Exception):\n    def __init__(self, *args: object, name: str | None = ..., path: str | 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\nclass NameError(Exception):\n    if sys.version_info >= (3, 10):\n        def __init__(self, *args: object, name: str | None = ...) -> None: ...\n        name: str\n\nclass ReferenceError(Exception): ...\nclass RuntimeError(Exception): ...\nclass StopAsyncIteration(Exception): ...\n\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\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\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\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    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, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> ExceptionGroup[_ExceptionT] | None: ...\n        @overload\n        def subgroup(\n            self, condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], /\n        ) -> BaseExceptionGroup[_BaseExceptionT] | None: ...\n        @overload\n        def subgroup(\n            self, condition: Callable[[_BaseExceptionT_co | Self], bool], /\n        ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ...\n        @overload\n        def split(\n            self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> tuple[ExceptionGroup[_ExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ...\n        @overload\n        def split(\n            self, condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], /\n        ) -> tuple[BaseExceptionGroup[_BaseExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ...\n        @overload\n        def split(\n            self, condition: 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, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> ExceptionGroup[_ExceptionT] | None: ...\n        @overload\n        def subgroup(self, condition: Callable[[_ExceptionT_co | Self], bool], /) -> ExceptionGroup[_ExceptionT_co] | None: ...\n        @overload  # type: ignore[override]\n        def split(\n            self, condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> tuple[ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None]: ...\n        @overload\n        def split(\n            self, condition: 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 _compression\nimport sys\nfrom _bz2 import BZ2Compressor as BZ2Compressor, BZ2Decompressor as BZ2Decompressor\nfrom _compression import BaseStream\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer\nfrom collections.abc import Iterable\nfrom typing import IO, Any, Literal, Protocol, SupportsIndex, TextIO, overload\nfrom typing_extensions import Self, TypeAlias\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: ...\nclass _ReadableFileobj(_compression._Reader, Protocol): ...\n\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) -> TextIO: ...\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) -> TextIO: ...\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) -> TextIO: ...\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 | TextIO: ...\n\nclass BZ2File(BaseStream, IO[bytes]):\n    def __enter__(self) -> Self: ...\n    if sys.version_info >= (3, 9):\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    else:\n        @overload\n        def __init__(\n            self, filename: _WritableFileobj, mode: _WriteBinaryMode, buffering: Any | None = None, compresslevel: int = 9\n        ) -> None: ...\n        @overload\n        def __init__(\n            self, filename: _ReadableFileobj, mode: _ReadBinaryMode = \"r\", buffering: Any | None = None, compresslevel: int = 9\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            filename: StrOrBytesPath,\n            mode: _ReadBinaryMode | _WriteBinaryMode = \"r\",\n            buffering: Any | None = None,\n            compresslevel: int = 9,\n        ) -> None: ...\n\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):\n    def __init__(self, month: int) -> None: ...\n\nclass IllegalWeekdayError(ValueError):\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 = Month.JANUARY\n    FEBRUARY = Month.FEBRUARY\n    MARCH = Month.MARCH\n    APRIL = Month.APRIL\n    MAY = Month.MAY\n    JUNE = Month.JUNE\n    JULY = Month.JULY\n    AUGUST = Month.AUGUST\n    SEPTEMBER = Month.SEPTEMBER\n    OCTOBER = Month.OCTOBER\n    NOVEMBER = Month.NOVEMBER\n    DECEMBER = 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 = Day.MONDAY\n    TUESDAY = Day.TUESDAY\n    WEDNESDAY = Day.WEDNESDAY\n    THURSDAY = Day.THURSDAY\n    FRIDAY = Day.FRIDAY\n    SATURDAY = Day.SATURDAY\n    SUNDAY = 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": "from _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\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] = ...,\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\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 = ...) -> None: ...\ndef print_environ(environ: _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] = ...,\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 SupportsComplex, SupportsFloat, SupportsIndex\nfrom typing_extensions import TypeAlias\n\ne: float\npi: float\ninf: float\ninfj: complex\nnan: float\nnanj: complex\ntau: float\n\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(x: _C, base: _C = ..., /) -> complex: ...\ndef log10(z: _C, /) -> complex: ...\ndef phase(z: _C, /) -> float: ...\ndef polar(z: _C, /) -> tuple[float, float]: ...\ndef rect(r: float, phi: float, /) -> 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\nfrom collections.abc import Callable, Mapping\nfrom types import CodeType\nfrom typing import Any\n\n__all__ = [\"InteractiveInterpreter\", \"InteractiveConsole\", \"interact\", \"compile_command\"]\n\nclass InteractiveInterpreter:\n    locals: Mapping[str, Any]  # undocumented\n    compile: CommandCompiler  # undocumented\n    def __init__(self, locals: Mapping[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: Mapping[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: Mapping[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: Mapping[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: Mapping[str, Any] | None = None,\n        exitmsg: str | None = None,\n    ) -> None: ...\n\ndef compile_command(source: str, filename: str = \"<input>\", symbol: str = \"single\") -> CodeType | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/codecs.pyi",
    "content": "import 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\nfrom typing_extensions import Self\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\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\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\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\nclass _Encoder(Protocol):\n    def __call__(self, input: str, errors: str = ..., /) -> tuple[bytes, int]: ...  # signature of Codec().encode\n\nclass _Decoder(Protocol):\n    def __call__(self, input: ReadableBuffer, errors: str = ..., /) -> tuple[str, int]: ...  # signature of Codec().decode\n\nclass _StreamReader(Protocol):\n    def __call__(self, stream: _ReadableStream, errors: str = ..., /) -> StreamReader: ...\n\nclass _StreamWriter(Protocol):\n    def __call__(self, stream: _WritableStream, errors: str = ..., /) -> StreamWriter: ...\n\nclass _IncrementalEncoder(Protocol):\n    def __call__(self, errors: str = ...) -> IncrementalEncoder: ...\n\nclass _IncrementalDecoder(Protocol):\n    def __call__(self, errors: str = ...) -> IncrementalDecoder: ...\n\nclass 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: ...\ndef getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ...\ndef getreader(encoding: str) -> _StreamReader: ...\ndef getwriter(encoding: str) -> _StreamWriter: ...\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\ndef 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 typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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 __repr__(self) -> str: ...\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    if sys.version_info >= (3, 9):\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: _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    def __repr__(self) -> str: ...\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) -> Self: ...\n    @overload\n    def __setitem__(self, i: SupportsIndex, item: _T) -> None: ...\n    @overload\n    def __setitem__(self, i: slice, item: Iterable[_T]) -> None: ...\n    def __delitem__(self, i: SupportsIndex | slice) -> 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: ...  # type: ignore[override]\n    def insert(self, i: int, item: _T) -> None: ...  # type: ignore[override]\n    def pop(self, i: int = -1) -> _T: ...  # type: ignore[override]\n    def remove(self, item: _T) -> None: ...  # type: ignore[override]\n    def copy(self) -> Self: ...\n    def __copy__(self) -> Self: ...\n    def count(self, item: _T) -> int: ...  # type: ignore[override]\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: ...  # type: ignore[override]\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: ...  # type: ignore[override]\n\nclass UserString(Sequence[UserString]):\n    data: str\n    def __init__(self, seq: object) -> None: ...\n    def __str__(self) -> str: ...\n    def __repr__(self) -> str: ...\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) -> 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: ...  # type: ignore[override]\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: ...  # type: ignore[override]\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    if sys.version_info >= (3, 9):\n        def removeprefix(self, prefix: str | UserString, /) -> Self: ...\n        def removesuffix(self, suffix: str | UserString, /) -> Self: ...\n\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\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: ...  # type: ignore[override]\n    def appendleft(self, x: _T, /) -> None: ...\n    def copy(self) -> Self: ...\n    def count(self, x: _T, /) -> int: ...  # type: ignore[override]\n    def extend(self, iterable: Iterable[_T], /) -> None: ...  # type: ignore[override]\n    def extendleft(self, iterable: Iterable[_T], /) -> None: ...\n    def insert(self, i: int, x: _T, /) -> None: ...  # type: ignore[override]\n    def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ...  # type: ignore[override]\n    def pop(self) -> _T: ...  # type: ignore[override]\n    def popleft(self) -> _T: ...\n    def remove(self, value: _T, /) -> None: ...  # type: ignore[override]\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    if sys.version_info >= (3, 9):\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\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\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\nclass _odict_values(dict_values[_KT_co, _VT_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def __reversed__(self) -> Iterator[_VT_co]: ...\n\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    if sys.version_info >= (3, 9):\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\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    if sys.version_info >= (3, 9):\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: _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    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: ...\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    if sys.version_info >= (3, 9):\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": "__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: float\nONE_THIRD: float\nTWO_THIRD: 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\n\n__all__ = [\"compile_dir\", \"compile_file\", \"compile_path\"]\n\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    ) -> int: ...\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    ) -> int: ...\n\nelif sys.version_info >= (3, 9):\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    ) -> int: ...\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    ) -> int: ...\n\nelse:\n    def compile_dir(\n        dir: StrPath,\n        maxlevels: int = 10,\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    ) -> int: ...\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    ) -> int: ...\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) -> int: ...\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, 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, Collection, Iterable, Iterator\nfrom logging import Logger\nfrom types import TracebackType\nfrom typing import Any, Final, Generic, NamedTuple, Protocol, TypeVar\nfrom typing_extensions import ParamSpec, Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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_FUTURE_STATES: list[str]\n_STATE_TO_DESCRIPTION_MAP: 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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass Executor:\n    if sys.version_info >= (3, 9):\n        def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ...\n    else:\n        def submit(self, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ...\n\n    def map(\n        self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = None, chunksize: int = 1\n    ) -> Iterator[_T]: ...\n    if sys.version_info >= (3, 9):\n        def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: ...\n    else:\n        def shutdown(self, wait: bool = True) -> None: ...\n\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\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\nif sys.version_info >= (3, 9):\n    def wait(\n        fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = \"ALL_COMPLETED\"\n    ) -> DoneAndNotDoneFutures[_T]: ...\n\nelse:\n    def wait(\n        fs: Collection[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/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, 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: int\n\n_MAX_WINDOWS_WORKERS: int\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    elif sys.version_info >= (3, 9):\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    else:\n        def __init__(\n            self, max_size: int | None = 0, *, ctx: BaseContext, pending_work_items: dict[int, _WorkItem[Any]]\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\nif sys.version_info >= (3, 9):\n    class _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    if sys.version_info >= (3, 9):\n        def _start_executor_manager_thread(self) -> None: ...\n\n    def _adjust_process_count(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 typing import Any, Generic, TypeVar, overload\nfrom typing_extensions import 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\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n_S = TypeVar(\"_S\")\n\nclass _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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef _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    _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    _initializer: Callable[..., None] | None\n    _initargs: tuple[Any, ...]\n    _work_queue: queue.SimpleQueue[_WorkItem[Any]]\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/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\nfrom typing_extensions import TypeAlias\n\nif 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\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: str, option: str, value: str, defaults: _Section) -> str: ...\n    def before_set(self, parser: _Parser, section: str, option: str, value: str) -> str: ...\n    def before_read(self, parser: _Parser, section: str, option: str, value: str) -> str: ...\n    def before_write(self, parser: _Parser, section: str, option: str, value: str) -> str: ...\n\nclass BasicInterpolation(Interpolation): ...\nclass ExtendedInterpolation(Interpolation): ...\n\nif sys.version_info < (3, 13):\n    class LegacyInterpolation(Interpolation):\n        def before_get(self, parser: _Parser, section: str, 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: str) -> SectionProxy: ...\n    def __setitem__(self, key: str, value: _Section) -> None: ...\n    def __delitem__(self, key: str) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    def __contains__(self, key: object) -> bool: ...\n    def defaults(self) -> _Section: ...\n    def sections(self) -> list[str]: ...\n    def add_section(self, section: str) -> None: ...\n    def has_section(self, section: str) -> bool: ...\n    def options(self, section: str) -> list[str]: ...\n    def has_option(self, section: str, 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        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: str, option: str, *, raw: bool = False, vars: _Section | None = None) -> int: ...\n    @overload\n    def getint(\n        self, section: str, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ...\n    ) -> int | _T: ...\n    @overload\n    def getfloat(self, section: str, option: str, *, raw: bool = False, vars: _Section | None = None) -> float: ...\n    @overload\n    def getfloat(\n        self, section: str, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ...\n    ) -> float | _T: ...\n    @overload\n    def getboolean(self, section: str, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool: ...\n    @overload\n    def getboolean(\n        self, section: str, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ...\n    ) -> bool | _T: ...\n    def _get_conv(\n        self,\n        section: str,\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: str, option: str, *, raw: bool = False, vars: _Section | None = None) -> str | MaybeNone: ...\n    @overload\n    def get(\n        self, section: str, 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: str, raw: bool = False, vars: _Section | None = None) -> list[tuple[str, str]]: ...\n    def set(self, section: str, 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: str, option: str) -> bool: ...\n    def remove_section(self, section: str) -> 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: str, option: str, *, raw: bool = False, vars: _Section | None = None) -> str: ...\n    @overload\n    def get(self, section: str, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T) -> str | _T: ...\n\nif sys.version_info < (3, 12):\n    class SafeConfigParser(ConfigParser): ...  # deprecated alias\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, option: str, *, raw: bool = False, vars: _Section | None = None, _impl: Any | None = None, **kwargs: Any\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,\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 = ..., vars: _Section | None = ...) -> int | None: ...\n    @overload\n    def getint(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _Section | None = ...) -> int | _T: ...\n    @overload\n    def getfloat(self, option: str, *, raw: bool = ..., vars: _Section | None = ...) -> float | None: ...\n    @overload\n    def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _Section | None = ...) -> float | _T: ...\n    @overload\n    def getboolean(self, option: str, *, raw: bool = ..., vars: _Section | None = ...) -> bool | None: ...\n    @overload\n    def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _Section | 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: str\n    def __init__(self, section: str) -> None: ...\n\nclass DuplicateSectionError(Error):\n    section: str\n    source: str | None\n    lineno: int | None\n    def __init__(self, section: str, source: str | None = None, lineno: int | None = None) -> None: ...\n\nclass DuplicateOptionError(Error):\n    section: str\n    option: str\n    source: str | None\n    lineno: int | None\n    def __init__(self, section: str, option: str, source: str | None = None, lineno: int | None = None) -> None: ...\n\nclass NoOptionError(Error):\n    section: str\n    option: str\n    def __init__(self, option: str, section: str) -> None: ...\n\nclass InterpolationError(Error):\n    section: str\n    option: str\n    def __init__(self, option: str, section: str, msg: str) -> None: ...\n\nclass InterpolationDepthError(InterpolationError):\n    def __init__(self, option: str, section: str, rawval: object) -> None: ...\n\nclass InterpolationMissingOptionError(InterpolationError):\n    reference: str\n    def __init__(self, option: str, section: str, 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        def __init__(self, source: str | None = None, filename: str | None = None) -> None: ...\n\n    def append(self, lineno: int, line: 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 _UNNAMED_SECTION: ...\n    UNNAMED_SECTION: _UNNAMED_SECTION\n\n    class MultilineContinuationError(ParsingError):\n        lineno: int\n        line: str\n        def __init__(self, filename: str, lineno: int, line: str) -> None: ...\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, FunctionType\nfrom typing import IO, Any, Generic, Protocol, TypeVar, overload, runtime_checkable\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_T_io = TypeVar(\"_T_io\", bound=IO[str] | None)\n_ExitT_co = TypeVar(\"_ExitT_co\", covariant=True, bound=bool | None, default=bool | None)\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_G = TypeVar(\"_G\", 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    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    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]):\n    # Ideally this would use ParamSpec, but that requires (*args, **kwargs), which this isn't. see #6676\n    def __init__(self, func: Callable[..., _G], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ...\n    gen: _G\n    func: Callable[..., _G]\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    if sys.version_info >= (3, 9):\n        def __exit__(\n            self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n        ) -> bool | None: ...\n    else:\n        def __exit__(\n            self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n        ) -> bool | None: ...\n\ndef contextmanager(func: Callable[_P, Iterator[_T_co]]) -> FunctionType[_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]]) -> FunctionType[_P, _AsyncGeneratorContextManager[_T_co]]: ...\n\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    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\nclass _RedirectStream(AbstractContextManager[_T_io, None]):\n    def __init__(self, new_target: _T_io) -> None: ...\n    def __exit__(\n        self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None\n    ) -> None: ...\n\nclass redirect_stdout(_RedirectStream[_T_io]): ...\nclass redirect_stderr(_RedirectStream[_T_io]): ...\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    ) -> bool: ...\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\nfrom typing_extensions import Self\n\n__all__ = [\"Error\", \"copy\", \"deepcopy\"]\n\n_T = TypeVar(\"_T\")\n_SR = TypeVar(\"_SR\", bound=_SupportsReplace)\n\nclass _SupportsReplace(Protocol):\n    # In reality doesn't support args, but there's no other great way to express this.\n    def __replace__(self, *args: Any, **kwargs: Any) -> Self: ...\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    def replace(obj: _SR, /, **changes: Any) -> _SR: ...\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\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    class _Method(_MethodBase): ...\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 typing import Any, Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 12):\n    from types import GenericAlias\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    POINTER as POINTER,\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    _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    pointer as pointer,\n    resize as resize,\n    set_errno as set_errno,\n    sizeof as sizeof,\n)\nfrom _typeshed import StrPath\nfrom ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure\nfrom typing import Any, ClassVar, Generic, TypeVar, 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\nif sys.version_info >= (3, 11):\n    from ctypes._endian import BigEndianUnion as BigEndianUnion, LittleEndianUnion as LittleEndianUnion\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n_T = TypeVar(\"_T\")\n_DLLT = TypeVar(\"_DLLT\", bound=CDLL)\n_CT = TypeVar(\"_CT\", bound=_CData)\n\nDEFAULT_MODE: 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    if sys.version_info >= (3, 9):\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@deprecated(\"Deprecated in Python 3.13; removal scheduled for Python 3.15\")\ndef SetPointerType(\n    pointer: type[_Pointer[Any]], cls: Any  # noqa: F811  # Redefinition of unused `pointer` from line 22\n) -> None: ...\ndef ARRAY(typ: _CT, len: int) -> Array[_CT]: ...  # Soft Deprecated, no plans to remove\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\nclass c_byte(_SimpleCData[int]): ...\n\nclass c_char(_SimpleCData[bytes]):\n    def __init__(self, value: int | bytes | bytearray = ...) -> None: ...\n\nclass c_char_p(_PointerLike, _SimpleCData[bytes | None]):\n    def __init__(self, value: int | bytes | None = ...) -> None: ...\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\nclass c_double(_SimpleCData[float]): ...\nclass c_longdouble(_SimpleCData[float]): ...  # can be an alias for c_double\nclass c_float(_SimpleCData[float]): ...\nclass c_int(_SimpleCData[int]): ...  # can be an alias for c_long\nclass c_long(_SimpleCData[int]): ...\nclass c_longlong(_SimpleCData[int]): ...  # can be an alias for c_long\nclass c_short(_SimpleCData[int]): ...\nclass c_size_t(_SimpleCData[int]): ...  # alias for c_uint, c_ulong, or c_ulonglong\nclass c_ssize_t(_SimpleCData[int]): ...  # alias for c_int, c_long, or c_longlong\nclass c_ubyte(_SimpleCData[int]): ...\nclass c_uint(_SimpleCData[int]): ...  # can be an alias for c_ulong\nclass c_ulong(_SimpleCData[int]): ...\nclass c_ulonglong(_SimpleCData[int]): ...  # can be an alias for c_ulong\nclass c_ushort(_SimpleCData[int]): ...\n\nclass c_void_p(_PointerLike, _SimpleCData[int | None]):\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\nc_int8 = c_byte\n\n# these are actually dynamic aliases for c_short, c_int, c_long, or c_longlong\nclass c_int16(_SimpleCData[int]): ...\nclass c_int32(_SimpleCData[int]): ...\nclass c_int64(_SimpleCData[int]): ...\n\nc_uint8 = c_ubyte\n\n# these are actually dynamic aliases for c_ushort, c_uint, c_ulong, or c_ulonglong\nclass c_uint16(_SimpleCData[int]): ...\nclass c_uint32(_SimpleCData[int]): ...\nclass c_uint64(_SimpleCData[int]): ...\n\nclass c_wchar_p(_PointerLike, _SimpleCData[str | None]):\n    def __init__(self, value: int | str | None = ...) -> None: ...\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\nclass c_bool(_SimpleCData[bool]):\n    def __init__(self, value: bool = ...) -> None: ...\n\nif sys.platform == \"win32\":\n    class HRESULT(_SimpleCData[int]): ...  # TODO undocumented\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_short, c_int, c_long, or c_longlong\n    # This covers all our bases.\n    c_time_t: type[c_int32 | c_int64 | c_short | c_int | c_long | c_longlong]\n\nclass py_object(_CanCastTo, _SimpleCData[_T]): ...\n\nif sys.version_info >= (3, 14):\n    class c_float_complex(_SimpleCData[complex]): ...\n    class c_double_complex(_SimpleCData[complex]): ...\n    class c_longdouble_complex(_SimpleCData[complex]): ...\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): ...\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    class LittleEndianUnion(Union): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/macholib/__init__.pyi",
    "content": "__version__: 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\ndef test() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/wintypes.pyi",
    "content": "from _ctypes import _CArgObject, _CField\nfrom ctypes import (\n    Array,\n    Structure,\n    _Pointer,\n    _SimpleCData,\n    c_byte,\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, TypeVar\nfrom typing_extensions import Self, TypeAlias\n\nBYTE = c_byte\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\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: int\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()`\nLINES: int\nCOLS: int\n\n# available after calling `curses.start_color()`\nCOLORS: int\nCOLOR_PAIRS: int\n\ndef wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: ...\n\n# typeshed used the name _CursesWindow for the underlying C class before\n# it was mapped to the name 'window' in 3.8.\n# Kept here as a legacy alias in case any third-party code is relying on it.\n_CursesWindow = window\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 TypeVar\n\n_CharT = TypeVar(\"_CharT\", str, int)\n\nNUL: int\nSOH: int\nSTX: int\nETX: int\nEOT: int\nENQ: int\nACK: int\nBEL: int\nBS: int\nTAB: int\nHT: int\nLF: int\nNL: int\nVT: int\nFF: int\nCR: int\nSO: int\nSI: int\nDLE: int\nDC1: int\nDC2: int\nDC3: int\nDC4: int\nNAK: int\nSYN: int\nETB: int\nCAN: int\nEM: int\nSUB: int\nESC: int\nFS: int\nGS: int\nRS: int\nUS: int\nSP: int\nDEL: int\n\ncontrolnames: 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 typing import Any, Generic, Literal, Protocol, TypeVar, overload\nfrom typing_extensions import Never, TypeAlias, TypeIs\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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# 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 = _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@overload\ndef dataclass(cls: None, /) -> Callable[[type[_T]], type[_T]]: ...\n@overload\ndef dataclass(cls: type[_T], /) -> type[_T]: ...\n\nif sys.version_info >= (3, 11):\n    @overload\n    def dataclass(\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        *,\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        *,\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\nclass _DefaultFactory(Protocol[_T_co]):\n    def __call__(self) -> _T_co: ...\n\nclass Field(Generic[_T]):\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    if sys.version_info >= (3, 10):\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING]\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    if sys.version_info >= (3, 9):\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, 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\nif sys.version_info >= (3, 9):\n    _InitVarMeta: TypeAlias = type\nelse:\n    class _InitVarMeta(type):\n        # Not used, instead `InitVar.__class_getitem__` is called.\n        # pyright (not unreasonably) thinks this is an invalid use of InitVar.\n        def __getitem__(self, params: Any) -> InitVar[Any]: ...  # pyright: ignore[reportInvalidTypeForm]\n\nclass InitVar(Generic[_T], metaclass=_InitVarMeta):\n    type: Type[_T]\n    def __init__(self, type: Type[_T]) -> None: ...\n    if sys.version_info >= (3, 9):\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, 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\n\nif sys.version_info >= (3, 11):\n    __all__ = (\"date\", \"datetime\", \"time\", \"timedelta\", \"timezone\", \"tzinfo\", \"MINYEAR\", \"MAXYEAR\", \"UTC\")\nelif sys.version_info >= (3, 9):\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\nif sys.version_info >= (3, 9):\n    # This class calls itself datetime.IsoCalendarDate. It's neither\n    # NamedTuple nor structseq.\n    @final\n    @type_check_only\n    class _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\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    # 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    if sys.version_info >= (3, 9):\n        def isocalendar(self) -> _IsoCalendarDate: ...\n    else:\n        def isocalendar(self) -> tuple[int, int, int]: ...\n\nclass time:\n    min: ClassVar[time]\n    max: ClassVar[time]\n    resolution: ClassVar[timedelta]\n    def __new__(\n        cls,\n        hour: SupportsIndex = ...,\n        minute: SupportsIndex = ...,\n        second: SupportsIndex = ...,\n        microsecond: SupportsIndex = ...,\n        tzinfo: _TzInfo | None = ...,\n        *,\n        fold: int = ...,\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 = ...) -> str: ...\n    @classmethod\n    def fromisoformat(cls, time_string: str, /) -> Self: ...\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\nclass timedelta:\n    min: ClassVar[timedelta]\n    max: ClassVar[timedelta]\n    resolution: ClassVar[timedelta]\n    def __new__(\n        cls,\n        days: float = ...,\n        seconds: float = ...,\n        microseconds: float = ...,\n        milliseconds: float = ...,\n        minutes: float = ...,\n        hours: float = ...,\n        weeks: float = ...,\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    def __str__(self) -> str: ...\n\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 = ...,\n        minute: SupportsIndex = ...,\n        second: SupportsIndex = ...,\n        microsecond: SupportsIndex = ...,\n        tzinfo: _TzInfo | None = ...,\n        *,\n        fold: int = ...,\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 = ...) -> Self: ...\n    else:\n        @classmethod\n        def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | 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 = ...) -> Self: ...\n    def isoformat(self, sep: str = ..., timespec: str = ...) -> 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\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\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\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\nclass Decimal:\n    def __new__(cls, value: _DecimalNew = ..., context: Context | None = ...) -> Self: ...\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 = ..., /) -> str: ...\n\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 inexpressable 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 = ...,\n        rounding: str | None = ...,\n        Emin: int | None = ...,\n        Emax: int | None = ...,\n        capitals: int | None = ...,\n        clamp: int | None = ...,\n        flags: None | dict[_TrapType, bool] | Container[_TrapType] = ...,\n        traps: None | dict[_TrapType, bool] | Container[_TrapType] = ...,\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 sys\nfrom collections.abc import Callable, Iterable, Iterator, Sequence\nfrom typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    if sys.version_info >= (3, 9):\n        def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: ...\n    else:\n        def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ...\n\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    if sys.version_info >= (3, 9):\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\ndef IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: ...  # pat is undocumented\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, NamedTuple\nfrom typing_extensions import Self, TypeAlias\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\nclass 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\nclass Bytecode:\n    codeobj: types.CodeType\n    first_line: int\n    if 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: 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, 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    # 3.13 made `show_cache` `None` by default\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    # 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    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 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    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, Incomplete, 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: 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: Incomplete | None = 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        if sys.version_info >= (3, 9):\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 Incomplete, 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: Incomplete | None = 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 _typeshed import Incomplete\nfrom 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: Incomplete | None = 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: Literal[0, 1]\n    dry_run: Literal[0, 1]\n    help: 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(\n        self, header: Incomplete | None = None, commands: Incomplete | None = None, indent: str = \"\"\n    ) -> 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 re import Pattern\nfrom typing import Any, Final, overload\nfrom typing_extensions import TypeAlias\n\n_Option: TypeAlias = tuple[str, str | None, str]\n_GR: TypeAlias = tuple[list[str], OptionDummy]\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(self, args: list[str] | None = None) -> _GR: ...\n    @overload\n    def getopt(self, args: list[str] | None, object: Any) -> list[str]: ...\n    def get_option_order(self) -> list[tuple[str, str]]: ...\n    def generate_help(self, header: str | None = None) -> list[str]: ...\n\ndef fancy_getopt(\n    options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: list[str] | None\n) -> list[str] | _GR: ...\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] = 0, 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] = 0, 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, 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: dict[str, int]\n\ndef register_optionflag(name: str) -> int: ...\n\nDONT_ACCEPT_TRUE_FOR_1: int\nDONT_ACCEPT_BLANKLINE: int\nNORMALIZE_WHITESPACE: int\nELLIPSIS: int\nSKIP: int\nIGNORE_EXCEPTION_DETAIL: int\n\nCOMPARISON_FLAGS: int\n\nREPORT_UDIFF: int\nREPORT_CDIFF: int\nREPORT_NDIFF: int\nREPORT_ONLY_FIRST_FAILURE: int\nFAIL_FAST: int\n\nREPORTING_FLAGS: int\n\nBLANKLINE_MARKER: str\nELLIPSIS_MARKER: str\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/dummy_threading.pyi",
    "content": "from _dummy_threading import *\nfrom _dummy_threading import __all__ as __all__\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/__init__.pyi",
    "content": "from collections.abc import Callable\nfrom email.message import Message\nfrom email.policy import Policy\nfrom typing import IO\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\ndef message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ...\ndef message_from_bytes(s: bytes | bytearray, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ...\ndef message_from_file(fp: IO[str], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ...\ndef message_from_binary_file(fp: IO[bytes], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/_header_value_parser.pyi",
    "content": "from 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.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5\nNLSET: Final[set[str]]\n# Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5\nSPECIALSNL: Final[set[str]]\n\ndef quote_string(value: Any) -> str: ...\n\nrfc2047_matcher: 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\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) -> 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: ...\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 Generic, Protocol, TypeVar, type_check_only\nfrom typing_extensions import Self\n\n__all__ = [\"Policy\", \"Compat32\", \"compat32\"]\n\n_MessageT = TypeVar(\"_MessageT\", bound=Message, default=Message)\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]):\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.8.20, 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] | None = None,\n        # Added in Python 3.8.20, 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] | None = ...,\n        # Added in Python 3.8.20, 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], metaclass=ABCMeta):\n    def handle_defect(self, obj: _MessageT, defect: MessageDefect) -> None: ...\n    def register_defect(self, obj: _MessageT, 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]):\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]\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[int]  # undocumented\nBASE64: Final[int]  # undocumented\nSHORTEST: Final[int]  # 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.8.20, 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.message import Message\nfrom email.policy import Policy\nfrom typing import Generic, TypeVar, overload\n\n__all__ = [\"FeedParser\", \"BytesFeedParser\"]\n\n_MessageT = TypeVar(\"_MessageT\", bound=Message, default=Message)\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, 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 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\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: ...\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\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\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 = TypeVar(\"_HeaderT\", default=str)\n_HeaderParamT = TypeVar(\"_HeaderParamT\", default=str)\n# Represents headers constructed by HeaderRegistry. Those are sub-classes\n# of BaseHeader and another header type.\n_HeaderRegistryT = TypeVar(\"_HeaderRegistryT\", default=Any)\n_HeaderRegistryParamT = TypeVar(\"_HeaderRegistryParamT\", 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\nclass _SupportsEncodeToPayload(Protocol):\n    def encode(self, encoding: str, /) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ...\n\nclass _SupportsDecodeToPayload(Protocol):\n    def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ...\n\nclass Message(Generic[_HeaderT, _HeaderParamT]):\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 | MaybeNone: ...\n    def __setitem__(self, name: str, val: _HeaderParamT) -> None: ...\n    def __delitem__(self, name: str) -> None: ...\n    def keys(self) -> list[str]: ...\n    def values(self) -> list[_HeaderT]: ...\n    def items(self) -> list[tuple[str, _HeaderT]]: ...\n    @overload\n    def get(self, name: str, failobj: None = None) -> _HeaderT | None: ...\n    @overload\n    def get(self, name: str, failobj: _T) -> _HeaderT | _T: ...\n    @overload\n    def get_all(self, name: str, failobj: None = None) -> list[_HeaderT] | None: ...\n    @overload\n    def get_all(self, name: str, failobj: _T) -> list[_HeaderT] | _T: ...\n    def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ...\n    def replace_header(self, _name: str, _value: _HeaderParamT) -> 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) -> None: ...\n    def raw_items(self) -> Iterator[tuple[str, _HeaderT]]: ...\n\nclass MIMEPart(Message[_HeaderRegistryT, _HeaderRegistryParamT]):\n    def __init__(self, policy: Policy[Any] | None = None) -> None: ...\n    def get_body(self, preferencelist: Sequence[str] = (\"related\", \"html\", \"plain\")) -> MIMEPart[_HeaderRegistryT] | 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]]: ...\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.message import Message\nfrom email.mime.nonmultipart import MIMENonMultipart\nfrom email.policy import Policy\n\n__all__ = [\"MIMEMessage\"]\n\nclass MIMEMessage(MIMENonMultipart):\n    def __init__(self, _msg: Message, _subtype: str = \"rfc822\", *, policy: Policy | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/multipart.pyi",
    "content": "from collections.abc import Sequence\nfrom email import _ParamsType\nfrom email.message import Message\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[Message] | None = None,\n        *,\n        policy: Policy | 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.mime.nonmultipart import MIMENonMultipart\nfrom email.policy import Policy\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.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, TypeVar, overload\n\n__all__ = [\"Parser\", \"HeaderParser\", \"BytesParser\", \"BytesHeaderParser\", \"FeedParser\", \"BytesFeedParser\"]\n\n_MessageT = TypeVar(\"_MessageT\", bound=Message, default=Message)\n\nclass Parser(Generic[_MessageT]):\n    @overload\n    def __init__(self: Parser[Message[str, str]], _class: None = None, *, policy: Policy[Message[str, str]] = ...) -> None: ...\n    @overload\n    def __init__(self, _class: Callable[[], _MessageT], *, 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__(\n        self: BytesParser[Message[str, str]], _class: None = None, *, policy: Policy[Message[str, str]] = ...\n    ) -> 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, compat32 as compat32\nfrom email.contentmanager import ContentManager\nfrom email.message import EmailMessage, Message\nfrom typing import Any, TypeVar, overload\nfrom typing_extensions import Self\n\n__all__ = [\"Compat32\", \"compat32\", \"Policy\", \"EmailPolicy\", \"default\", \"strict\", \"SMTP\", \"HTTP\"]\n\n_MessageT = TypeVar(\"_MessageT\", bound=Message, default=Message)\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.8.20, 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.8.20, 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.8.20, 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.8.20, 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.8.20, 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: ...\n\nif sys.version_info >= (3, 10):\n    @overload\n    def parsedate_to_datetime(data: None) -> None: ...\n    @overload\n    def parsedate_to_datetime(data: str) -> datetime.datetime: ...\n\nelse:\n    def parsedate_to_datetime(data: str) -> datetime.datetime: ...\n\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": "from _typeshed import Incomplete\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\n# Needed for submodules\ndef __getattr__(name: str) -> Incomplete: ...\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_centeuro.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_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\nimport sys\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    if sys.version_info >= (3, 9):\n        @staticmethod\n        def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ...\n    else:\n        @staticmethod\n        def decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nif sys.version_info >= (3, 9):\n    class IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n        def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ...\n\nelse:\n    class IncrementalDecoder(codecs.IncrementalDecoder):\n        def decode(self, input: str | ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    if sys.version_info >= (3, 9):\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\nimport sys\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    if sys.version_info >= (3, 9):\n        @staticmethod\n        def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ...\n    else:\n        @staticmethod\n        def decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nif sys.version_info >= (3, 9):\n    class IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n        def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ...\n\nelse:\n    class IncrementalDecoder(codecs.IncrementalDecoder):\n        def decode(self, input: str | ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    if sys.version_info >= (3, 9):\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, Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\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\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    def __init__(self) -> None: ...\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    elif sys.version_info >= (3, 9):\n        def __new__(\n            metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any\n        ) -> _typeshed.Self: ...\n    else:\n        def __new__(metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> _typeshed.Self: ...\n\n    if sys.version_info >= (3, 9):\n        @classmethod\n        def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ...  # type: ignore[override]\n    else:\n        @classmethod\n        def __prepare__(metacls, cls: str, bases: tuple[type, ...]) -> _EnumDict: ...  # type: ignore[override]\n\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\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):\n        @classmethod\n        def __signature__(cls) -> str: ...\n\nif sys.version_info >= (3, 11):\n    class ReprEnum(Enum): ...\n\nif sys.version_info >= (3, 11):\n    _IntEnumBase = ReprEnum\nelse:\n    _IntEnumBase = Enum\n\nclass 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    @_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 = EnumCheck.CONTINUOUS\n    NAMED_FLAGS = EnumCheck.NAMED_FLAGS\n    UNIQUE = 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 = FlagBoundary.STRICT\n    CONFORM = FlagBoundary.CONFORM\n    EJECT = FlagBoundary.EJECT\n    KEEP = 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\nif sys.version_info >= (3, 11):\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        __ror__ = __or__\n        __rand__ = __and__\n        __rxor__ = __xor__\n\nelse:\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        __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\n\nerrorcode: Mapping[int, str]\n\nEPERM: int\nENOENT: int\nESRCH: int\nEINTR: int\nEIO: int\nENXIO: int\nE2BIG: int\nENOEXEC: int\nEBADF: int\nECHILD: int\nEAGAIN: int\nENOMEM: int\nEACCES: int\nEFAULT: int\nEBUSY: int\nEEXIST: int\nEXDEV: int\nENODEV: int\nENOTDIR: int\nEISDIR: int\nEINVAL: int\nENFILE: int\nEMFILE: int\nENOTTY: int\nETXTBSY: int\nEFBIG: int\nENOSPC: int\nESPIPE: int\nEROFS: int\nEMLINK: int\nEPIPE: int\nEDOM: int\nERANGE: int\nEDEADLK: int\nENAMETOOLONG: int\nENOLCK: int\nENOSYS: int\nENOTEMPTY: int\nELOOP: int\nEWOULDBLOCK: int\nENOMSG: int\nEIDRM: int\nENOSTR: int\nENODATA: int\nETIME: int\nENOSR: int\nEREMOTE: int\nENOLINK: int\nEPROTO: int\nEBADMSG: int\nEOVERFLOW: int\nEILSEQ: int\nEUSERS: int\nENOTSOCK: int\nEDESTADDRREQ: int\nEMSGSIZE: int\nEPROTOTYPE: int\nENOPROTOOPT: int\nEPROTONOSUPPORT: int\nESOCKTNOSUPPORT: int\nENOTSUP: int\nEOPNOTSUPP: int\nEPFNOSUPPORT: int\nEAFNOSUPPORT: int\nEADDRINUSE: int\nEADDRNOTAVAIL: int\nENETDOWN: int\nENETUNREACH: int\nENETRESET: int\nECONNABORTED: int\nECONNRESET: int\nENOBUFS: int\nEISCONN: int\nENOTCONN: int\nESHUTDOWN: int\nETOOMANYREFS: int\nETIMEDOUT: int\nECONNREFUSED: int\nEHOSTDOWN: int\nEHOSTUNREACH: int\nEALREADY: int\nEINPROGRESS: int\nESTALE: int\nEDQUOT: int\nECANCELED: int  # undocumented\nENOTRECOVERABLE: int  # undocumented\nEOWNERDEAD: int  # undocumented\n\nif sys.platform == \"sunos5\" or sys.platform == \"solaris\":  # noqa: Y008\n    ELOCKUNMAPPED: int\n    ENOTACTIVE: int\n\nif sys.platform != \"win32\":\n    ENOTBLK: int\n    EMULTIHOP: int\n\nif sys.platform == \"darwin\":\n    # All of the below are undocumented\n    EAUTH: int\n    EBADARCH: int\n    EBADEXEC: int\n    EBADMACHO: int\n    EBADRPC: int\n    EDEVERR: int\n    EFTYPE: int\n    ENEEDAUTH: int\n    ENOATTR: int\n    ENOPOLICY: int\n    EPROCLIM: int\n    EPROCUNAVAIL: int\n    EPROGMISMATCH: int\n    EPROGUNAVAIL: int\n    EPWROFF: int\n    ERPCMISMATCH: int\n    ESHLIBVERS: int\n    if sys.version_info >= (3, 11):\n        EQFULL: int\n\nif sys.platform != \"darwin\":\n    EDEADLOCK: int\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    ECHRNG: int\n    EL2NSYNC: int\n    EL3HLT: int\n    EL3RST: int\n    ELNRNG: int\n    EUNATCH: int\n    ENOCSI: int\n    EL2HLT: int\n    EBADE: int\n    EBADR: int\n    EXFULL: int\n    ENOANO: int\n    EBADRQC: int\n    EBADSLT: int\n    EBFONT: int\n    ENONET: int\n    ENOPKG: int\n    EADV: int\n    ESRMNT: int\n    ECOMM: int\n    EDOTDOT: int\n    ENOTUNIQ: int\n    EBADFD: int\n    EREMCHG: int\n    ELIBACC: int\n    ELIBBAD: int\n    ELIBSCN: int\n    ELIBMAX: int\n    ELIBEXEC: int\n    ERESTART: int\n    ESTRPIPE: int\n    EUCLEAN: int\n    ENOTNAM: int\n    ENAVAIL: int\n    EISNAM: int\n    EREMOTEIO: int\n    # All of the below are undocumented\n    EKEYEXPIRED: int\n    EKEYREJECTED: int\n    EKEYREVOKED: int\n    EMEDIUMTYPE: int\n    ENOKEY: int\n    ENOMEDIUM: int\n    ERFKILL: int\n\nif sys.platform == \"win32\":\n    # All of these are undocumented\n    WSABASEERR: int\n    WSAEACCES: int\n    WSAEADDRINUSE: int\n    WSAEADDRNOTAVAIL: int\n    WSAEAFNOSUPPORT: int\n    WSAEALREADY: int\n    WSAEBADF: int\n    WSAECONNABORTED: int\n    WSAECONNREFUSED: int\n    WSAECONNRESET: int\n    WSAEDESTADDRREQ: int\n    WSAEDISCON: int\n    WSAEDQUOT: int\n    WSAEFAULT: int\n    WSAEHOSTDOWN: int\n    WSAEHOSTUNREACH: int\n    WSAEINPROGRESS: int\n    WSAEINTR: int\n    WSAEINVAL: int\n    WSAEISCONN: int\n    WSAELOOP: int\n    WSAEMFILE: int\n    WSAEMSGSIZE: int\n    WSAENAMETOOLONG: int\n    WSAENETDOWN: int\n    WSAENETRESET: int\n    WSAENETUNREACH: int\n    WSAENOBUFS: int\n    WSAENOPROTOOPT: int\n    WSAENOTCONN: int\n    WSAENOTEMPTY: int\n    WSAENOTSOCK: int\n    WSAEOPNOTSUPP: int\n    WSAEPFNOSUPPORT: int\n    WSAEPROCLIM: int\n    WSAEPROTONOSUPPORT: int\n    WSAEPROTOTYPE: int\n    WSAEREMOTE: int\n    WSAESHUTDOWN: int\n    WSAESOCKTNOSUPPORT: int\n    WSAESTALE: int\n    WSAETIMEDOUT: int\n    WSAETOOMANYREFS: int\n    WSAEUSERS: int\n    WSAEWOULDBLOCK: int\n    WSANOTINITIALISED: int\n    WSASYSNOTREADY: int\n    WSAVERNOTSUPPORTED: 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 = ..., all_threads: bool = ...) -> None: ...\ndef dump_traceback_later(timeout: float, repeat: bool = ..., file: FileDescriptorLike = ..., exit: bool = ...) -> None: ...\ndef enable(file: FileDescriptorLike = ..., all_threads: bool = ...) -> None: ...\ndef is_enabled() -> bool: ...\n\nif sys.platform != \"win32\":\n    def register(signum: int, file: FileDescriptorLike = ..., all_threads: bool = ..., chain: bool = ...) -> 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: int\n    FD_CLOEXEC: int\n    F_DUPFD: int\n    F_DUPFD_CLOEXEC: int\n    F_GETFD: int\n    F_GETFL: int\n    F_GETLK: int\n    F_GETOWN: int\n    F_RDLCK: int\n    F_SETFD: int\n    F_SETFL: int\n    F_SETLK: int\n    F_SETLKW: int\n    F_SETOWN: int\n    F_UNLCK: int\n    F_WRLCK: int\n\n    F_GETLEASE: int\n    F_SETLEASE: int\n    if sys.platform == \"darwin\":\n        F_FULLFSYNC: int\n        F_NOCACHE: int\n        if sys.version_info >= (3, 9):\n            F_GETPATH: int\n    if sys.platform == \"linux\":\n        F_SETLKW64: int\n        F_SETSIG: int\n        F_SHLCK: int\n        F_SETLK64: int\n        F_GETSIG: int\n        F_NOTIFY: int\n        F_EXLCK: int\n        F_GETLK64: int\n        F_ADD_SEALS: int\n        F_GET_SEALS: int\n        F_SEAL_GROW: int\n        F_SEAL_SEAL: int\n        F_SEAL_SHRINK: int\n        F_SEAL_WRITE: int\n        if sys.version_info >= (3, 9):\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: int\n            F_SETPIPE_SZ: int\n\n        DN_ACCESS: int\n        DN_ATTRIB: int\n        DN_CREATE: int\n        DN_DELETE: int\n        DN_MODIFY: int\n        DN_MULTISHOT: int\n        DN_RENAME: int\n\n    LOCK_EX: int\n    LOCK_NB: int\n    LOCK_SH: int\n    LOCK_UN: int\n    if sys.platform == \"linux\":\n        LOCK_MAND: int\n        LOCK_READ: int\n        LOCK_RW: int\n        LOCK_WRITE: 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: int\n        I_CANPUT: int\n        I_CKBAND: int\n        I_FDINSERT: int\n        I_FIND: int\n        I_FLUSH: int\n        I_FLUSHBAND: int\n        I_GETBAND: int\n        I_GETCLTIME: int\n        I_GETSIG: int\n        I_GRDOPT: int\n        I_GWROPT: int\n        I_LINK: int\n        I_LIST: int\n        I_LOOK: int\n        I_NREAD: int\n        I_PEEK: int\n        I_PLINK: int\n        I_POP: int\n        I_PUNLINK: int\n        I_PUSH: int\n        I_RECVFD: int\n        I_SENDFD: int\n        I_SETCLTIME: int\n        I_SETSIG: int\n        I_SRDOPT: int\n        I_STR: int\n        I_SWROPT: int\n        I_UNLINK: int\n\n    if sys.version_info >= (3, 12) and sys.platform == \"linux\":\n        FICLONE: int\n        FICLONERANGE: 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 typing import Any, AnyStr, Final, Generic, Literal\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n__all__ = [\"clear_cache\", \"cmp\", \"dircmp\", \"cmpfiles\", \"DEFAULT_IGNORES\"]\n\nDEFAULT_IGNORES: 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    if sys.version_info >= (3, 9):\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 StrOrBytesPath\nfrom collections.abc import Callable, Iterable, Iterator\nfrom types import TracebackType\nfrom typing import IO, Any, AnyStr, Literal, Protocol, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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\nclass _HasReadlineAndFileno(Protocol[AnyStr]):\n    def readline(self) -> AnyStr: ...\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    if sys.version_info >= (3, 9):\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\ndef hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/fnmatch.pyi",
    "content": "from collections.abc import Iterable\nfrom typing import AnyStr\n\n__all__ = [\"filter\", \"fnmatch\", \"fnmatchcase\", \"translate\"]\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"
  },
  {
    "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 Integral, Rational, Real\nfrom typing import Any, Literal, Protocol, SupportsIndex, overload\nfrom typing_extensions import Self, TypeAlias\n\n_ComparableNum: TypeAlias = int | float | Decimal | Real\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"Fraction\"]\nelse:\n    __all__ = [\"Fraction\", \"gcd\"]\n    @overload\n    def gcd(a: int, b: int) -> int: ...\n    @overload\n    def gcd(a: Integral, b: int) -> Integral: ...\n    @overload\n    def gcd(a: int, b: Integral) -> Integral: ...\n    @overload\n    def gcd(a: Integral, b: Integral) -> Integral: ...\n\nclass _ConvertibleToIntegerRatio(Protocol):\n    def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ...\n\nclass Fraction(Rational):\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    @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    @overload\n    def __rpow__(b, a: float | Fraction) -> float: ...\n    @overload\n    def __rpow__(b, a: complex) -> complex: ...\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"
  },
  {
    "path": "mypy/typeshed/stdlib/ftplib.pyi",
    "content": "import sys\nfrom _typeshed import 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\nfrom typing_extensions import Self\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    if sys.version_info >= (3, 9):\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    else:\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        ) -> None: ...\n\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    elif sys.version_info >= (3, 9):\n        def __init__(\n            self,\n            host: str = \"\",\n            user: str = \"\",\n            passwd: str = \"\",\n            acct: str = \"\",\n            keyfile: str | None = None,\n            certfile: str | 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    else:\n        def __init__(\n            self,\n            host: str = \"\",\n            user: str = \"\",\n            passwd: str = \"\",\n            acct: str = \"\",\n            keyfile: str | None = None,\n            certfile: str | None = None,\n            context: SSLContext | None = None,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n        ) -> None: ...\n    ssl_version: int\n    keyfile: str | None\n    certfile: str | 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, Sequence, Sized\nfrom typing import Any, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload, Protocol, Final, \\\n    type_check_only\nfrom typing_extensions import ParamSpec, Self, TypeAlias, Never, Concatenate\nfrom types import MethodType, FunctionType\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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]\n\nif sys.version_info >= (3, 9):\n    __all__ += [\"cache\"]\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_S = TypeVar(\"_S\")\n_P = ParamSpec(\"_P\")\n_PWrapped = ParamSpec(\"_PWrapped\")\n_RWrapped = TypeVar(\"_RWrapped\")\n_PWrapper = ParamSpec(\"_PWrapper\")\n_RWrapper = TypeVar(\"_RWrapper\")\n\n@overload\ndef reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T, /) -> _T: ...\n@overload\ndef reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T], /) -> _T: ...\n\nclass _CacheInfo(NamedTuple):\n    hits: int\n    misses: int\n    maxsize: int | None\n    currsize: int\n\nif sys.version_info >= (3, 9):\n    class _CacheParameters(TypedDict):\n        maxsize: int\n        typed: bool\n\n@type_check_only\nclass _HashCallable(Protocol):\n    def __call__(self, /, *args: Hashable, **kwargs: Hashable) -> Never: ...\n\n@type_check_only\nclass _LruCacheWrapperBase(Generic[_out_TCallable]):\n    __wrapped__: Final[_out_TCallable]  # type: ignore[misc]\n    __call__: Final[_out_TCallable | _HashCallable]  # type: ignore[misc]\n\n    def cache_info(self) -> _CacheInfo: ...\n    def cache_clear(self) -> None: ...\n    if sys.version_info >= (3, 9):\n        def cache_parameters(self) -> _CacheParameters: ...\n\n    def __copy__(self) -> Self: ...\n    def __deepcopy__(self, memo: Any, /) -> Self: ...\n\n\n# replace with `Method & X` once #856 is resolved\n@type_check_only\nclass _LruCacheWrapperMethod(MethodType, _LruCacheWrapperBase[_out_TCallable]):  # type: ignore[misc]\n    __call__: Final[_out_TCallable | _HashCallable]  # type: ignore[misc, assignment]\n\n\n# actually defined in `_functools`\n@final\nclass _lru_cache_wrapper(_LruCacheWrapperBase[_out_TCallable]):\n    def __init__(self, user_function: Never, maxsize: Never, typed: Never, cache_info_type: Never): ...\n\n    @overload\n    def __get__(self, instance: None, owner: object) -> Self: ...\n    @overload\n    def __get__(\n        self: _lru_cache_wrapper[Callable[Concatenate[Never, _PWrapped], _RWrapped]],\n        instance: object,\n        owner: type[object] | None = None,\n        /,\n    # ideally we could capture the `Callable` to account for subtypes and intersect with `MethodType`\n    ) -> _LruCacheWrapperMethod[Callable[_PWrapped, _RWrapped]]: ...\n\n@overload\ndef lru_cache(maxsize: int | None = 128, typed: bool = False) -> FunctionType[[_TCallable], _lru_cache_wrapper[_TCallable]]: ...\n@overload\ndef lru_cache(maxsize: _TCallable, typed: bool = False) -> _lru_cache_wrapper[_TCallable]: ...\n\nif sys.version_info >= (3, 12):\n    WRAPPER_ASSIGNMENTS: tuple[\n        Literal[\"__module__\"],\n        Literal[\"__name__\"],\n        Literal[\"__qualname__\"],\n        Literal[\"__doc__\"],\n        Literal[\"__annotations__\"],\n        Literal[\"__type_params__\"],\n    ]\nelse:\n    WRAPPER_ASSIGNMENTS: tuple[\n        Literal[\"__module__\"], Literal[\"__name__\"], Literal[\"__qualname__\"], Literal[\"__doc__\"], Literal[\"__annotations__\"]\n    ]\nWRAPPER_UPDATES: tuple[Literal[\"__dict__\"]]\n\n_AnyCallable = Callable[..., object]\n_TCallable = TypeVar(\"_TCallable\", bound=_AnyCallable)\n_out_TCallable = TypeVar(\"_out_TCallable\", bound=_AnyCallable, covariant=True)\n_TCallable2 = TypeVar(\"_TCallable2\", bound=_AnyCallable)\n\nclass _Wrapped(Generic[_TCallable]):\n    __wrapped__: _TCallable\n\nclass _Wrapper(Generic[_TCallable]):\n    def __call__(self, f: _TCallable2) -> _TCallable2 & _Wrapped[_TCallable]: ...\n\nif sys.version_info >= (3, 12):\n    def update_wrapper(\n        wrapper: _TCallable,\n        wrapped: _TCallable2,\n        assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\", \"__type_params__\"),\n        updated: Sequence[str] = (\"__dict__\",),\n    ) -> _TCallable & _Wrapped[_TCallable2]: ...\n    def wraps(\n        wrapped: _TCallable,\n        assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\", \"__type_params__\"),\n        updated: Sequence[str] = (\"__dict__\",),\n    ) -> _Wrapper[_TCallable]: ...\n\nelse:\n    def update_wrapper(\n        wrapper: _TCallable,\n        wrapped: _TCallable2,\n        assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n        updated: Sequence[str] = (\"__dict__\",),\n    ) -> _TCallable & _Wrapped[_TCallable2]: ...\n    def wraps(\n        wrapped: _TCallable,\n        assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n        updated: Sequence[str] = (\"__dict__\",),\n    ) -> _Wrapper[_TCallable]: ...\n\ndef total_ordering(cls: type[_T]) -> type[_T]: ...\ndef cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ...\n\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    if sys.version_info >= (3, 9):\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    @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    def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ...\n    @property\n    def __isabstractmethod__(self) -> bool: ...\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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: type[Any], 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: type[Any], 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: type[Any], 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: type[Any], 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[unsafe-variance]  # pyright: ignore[reportGeneralTypeIssues]\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 9):\n    def cache(user_function: _TCallable, /) -> _lru_cache_wrapper[_TCallable]: ...\n\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"
  },
  {
    "path": "mypy/typeshed/stdlib/gc.pyi",
    "content": "import sys\nfrom 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: ...\n\nif sys.version_info >= (3, 9):\n    def is_finalized(obj: Any, /) -> bool: ...\n\ndef isenabled() -> bool: ...\ndef set_debug(flags: int, /) -> None: ...\ndef set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ..., /) -> 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, 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]\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"
  },
  {
    "path": "mypy/typeshed/stdlib/getopt.pyi",
    "content": "from collections.abc import Iterable\n\n__all__ = [\"GetoptError\", \"error\", \"getopt\", \"gnu_getopt\"]\n\ndef getopt(args: list[str], shortopts: str, longopts: Iterable[str] | str = []) -> tuple[list[tuple[str, str]], list[str]]: ...\ndef gnu_getopt(\n    args: list[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": "from typing import TextIO\n\n__all__ = [\"getpass\", \"getuser\", \"GetPassWarning\"]\n\ndef getpass(prompt: str = \"Password: \", stream: TextIO | None = None) -> str: ...\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\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\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        def output_charset(self) -> str | None: ...\n        def set_output_charset(self, charset: str) -> None: ...\n        def lgettext(self, message: str) -> str: ...\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 = 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 = 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 = 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 = None,\n    ) -> NullTranslations: ...\n    def install(\n        domain: str, localedir: StrPath | None = None, codeset: str | None = 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    def lgettext(message: str) -> str: ...\n    def ldgettext(domain: str, message: str) -> str: ...\n    def lngettext(msgid1: str, msgid2: str, n: int) -> str: ...\n    def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ...\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\n\n__all__ = [\"escape\", \"glob\", \"iglob\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"translate\"]\n\ndef glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ...\ndef 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 _compression\nimport sys\nimport zlib\nfrom _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath\nfrom io import FileIO, TextIOWrapper\nfrom typing import Final, Literal, Protocol, overload\nfrom typing_extensions import TypeAlias\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\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\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(_compression.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        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\nclass _GzipReader(_compression.DecompressReader):\n    def __init__(self, fp: _ReadableFileobj) -> None: ...\n\ndef compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: ...\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    openssl_md5 as md5,\n    openssl_sha1 as sha1,\n    openssl_sha224 as sha224,\n    openssl_sha256 as sha256,\n    openssl_sha384 as sha384,\n    openssl_sha512 as sha512,\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\nif sys.version_info >= (3, 9):\n    def new(name: str, data: ReadableBuffer = b\"\", *, usedforsecurity: bool = ...) -> HASH: ...\n    from _hashlib import (\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_shake_128 as shake_128,\n        openssl_shake_256 as shake_256,\n    )\n\nelse:\n    @type_check_only\n    class _VarLenHash(HASH):\n        def digest(self, length: int) -> bytes: ...  # type: ignore[override]\n        def hexdigest(self, length: int) -> str: ...  # type: ignore[override]\n\n    def new(name: str, data: ReadableBuffer = b\"\") -> HASH: ...\n    # At runtime these aren't functions but classes imported from _sha3\n    def sha3_224(string: ReadableBuffer = b\"\") -> HASH: ...\n    def sha3_256(string: ReadableBuffer = b\"\") -> HASH: ...\n    def sha3_384(string: ReadableBuffer = b\"\") -> HASH: ...\n    def sha3_512(string: ReadableBuffer = b\"\") -> HASH: ...\n    def shake_128(string: ReadableBuffer = b\"\") -> _VarLenHash: ...\n    def shake_256(string: ReadableBuffer = b\"\") -> _VarLenHash: ...\n\nalgorithms_guaranteed: AbstractSet[str]\nalgorithms_available: AbstractSet[str]\n\nif sys.version_info >= (3, 11):\n    class _BytesIOLike(Protocol):\n        def getbuffer(self) -> ReadableBuffer: ...\n\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[[], HASH], /, *, _bufsize: int = 262144\n    ) -> HASH: ...\n\n# Legacy typing-only alias\n_Hash = HASH\n"
  },
  {
    "path": "mypy/typeshed/stdlib/heapq.pyi",
    "content": "from _heapq import *\nfrom _typeshed import SupportsRichComparison\nfrom collections.abc import Callable, Iterable\nfrom typing import Any, Final, TypeVar\n\n__all__ = [\"heappush\", \"heappop\", \"heapify\", \"heapreplace\", \"merge\", \"nlargest\", \"nsmallest\", \"heappushpop\"]\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) -> Iterable[_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": "import sys\nfrom _hashlib import HASH as _HashlibHash\nfrom _typeshed import ReadableBuffer, SizedBuffer\nfrom collections.abc import Callable\nfrom types import ModuleType\nfrom typing import AnyStr, overload\nfrom typing_extensions import TypeAlias\n\n_DigestMod: TypeAlias = str | Callable[[], _HashlibHash] | 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    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\nif sys.version_info >= (3, 9):\n    from _hashlib import compare_digest as compare_digest\nelse:\n    @overload\n    def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ...\n    @overload\n    def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ...\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": "__all__ = [\"html5\", \"name2codepoint\", \"codepoint2name\", \"entitydefs\"]\n\nname2codepoint: dict[str, int]\nhtml5: dict[str, str]\ncodepoint2name: dict[int, str]\nentitydefs: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/html/parser.pyi",
    "content": "from _markupbase import ParserBase\nfrom re import Pattern\n\n__all__ = [\"HTMLParser\"]\n\nclass HTMLParser(ParserBase):\n    def __init__(self, *, convert_charrefs: bool = True) -> 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    CDATA_CONTENT_ELEMENTS: tuple[str, ...]\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 = ...) -> 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    def set_cdata_mode(self, elem: str) -> 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    if sys.version_info >= (3, 9):\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    if sys.version_info >= (3, 9):\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    if sys.version_info >= (3, 9):\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, SupportsRead, SupportsReadline, WriteableBuffer\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom socket import socket\nfrom typing import BinaryIO, Literal, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\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_MessageT = TypeVar(\"_MessageT\", bound=email.message.Message)\n_HeaderValue: TypeAlias = ReadableBuffer | str | int\n\nHTTP_PORT: int\nHTTPS_PORT: int\n\n# Keep these global constants in sync with http.HTTPStatus (http/__init__.pyi).\n# They are present for backward compatibility reasons.\nCONTINUE: Literal[100]\nSWITCHING_PROTOCOLS: Literal[101]\nPROCESSING: Literal[102]\nif sys.version_info >= (3, 9):\n    EARLY_HINTS: Literal[103]\n\nOK: Literal[200]\nCREATED: Literal[201]\nACCEPTED: Literal[202]\nNON_AUTHORITATIVE_INFORMATION: Literal[203]\nNO_CONTENT: Literal[204]\nRESET_CONTENT: Literal[205]\nPARTIAL_CONTENT: Literal[206]\nMULTI_STATUS: Literal[207]\nALREADY_REPORTED: Literal[208]\nIM_USED: Literal[226]\n\nMULTIPLE_CHOICES: Literal[300]\nMOVED_PERMANENTLY: Literal[301]\nFOUND: Literal[302]\nSEE_OTHER: Literal[303]\nNOT_MODIFIED: Literal[304]\nUSE_PROXY: Literal[305]\nTEMPORARY_REDIRECT: Literal[307]\nPERMANENT_REDIRECT: Literal[308]\n\nBAD_REQUEST: Literal[400]\nUNAUTHORIZED: Literal[401]\nPAYMENT_REQUIRED: Literal[402]\nFORBIDDEN: Literal[403]\nNOT_FOUND: Literal[404]\nMETHOD_NOT_ALLOWED: Literal[405]\nNOT_ACCEPTABLE: Literal[406]\nPROXY_AUTHENTICATION_REQUIRED: Literal[407]\nREQUEST_TIMEOUT: Literal[408]\nCONFLICT: Literal[409]\nGONE: Literal[410]\nLENGTH_REQUIRED: Literal[411]\nPRECONDITION_FAILED: Literal[412]\nif sys.version_info >= (3, 13):\n    CONTENT_TOO_LARGE: Literal[413]\nREQUEST_ENTITY_TOO_LARGE: Literal[413]\nif sys.version_info >= (3, 13):\n    URI_TOO_LONG: Literal[414]\nREQUEST_URI_TOO_LONG: Literal[414]\nUNSUPPORTED_MEDIA_TYPE: Literal[415]\nif sys.version_info >= (3, 13):\n    RANGE_NOT_SATISFIABLE: Literal[416]\nREQUESTED_RANGE_NOT_SATISFIABLE: Literal[416]\nEXPECTATION_FAILED: Literal[417]\nif sys.version_info >= (3, 9):\n    IM_A_TEAPOT: Literal[418]\nMISDIRECTED_REQUEST: Literal[421]\nif sys.version_info >= (3, 13):\n    UNPROCESSABLE_CONTENT: Literal[422]\nUNPROCESSABLE_ENTITY: Literal[422]\nLOCKED: Literal[423]\nFAILED_DEPENDENCY: Literal[424]\nif sys.version_info >= (3, 9):\n    TOO_EARLY: Literal[425]\nUPGRADE_REQUIRED: Literal[426]\nPRECONDITION_REQUIRED: Literal[428]\nTOO_MANY_REQUESTS: Literal[429]\nREQUEST_HEADER_FIELDS_TOO_LARGE: Literal[431]\nUNAVAILABLE_FOR_LEGAL_REASONS: Literal[451]\n\nINTERNAL_SERVER_ERROR: Literal[500]\nNOT_IMPLEMENTED: Literal[501]\nBAD_GATEWAY: Literal[502]\nSERVICE_UNAVAILABLE: Literal[503]\nGATEWAY_TIMEOUT: Literal[504]\nHTTP_VERSION_NOT_SUPPORTED: Literal[505]\nVARIANT_ALSO_NEGOTIATES: Literal[506]\nINSUFFICIENT_STORAGE: Literal[507]\nLOOP_DETECTED: Literal[508]\nNOT_EXTENDED: Literal[510]\nNETWORK_AUTHENTICATION_REQUIRED: Literal[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    def info(self) -> email.message.Message: ...\n    def geturl(self) -> str: ...\n    def getcode(self) -> int: ...\n    def begin(self) -> None: ...\n\nclass HTTPConnection:\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        def __init__(\n            self,\n            host: str,\n            port: int | None = None,\n            key_file: str | None = None,\n            cert_file: str | 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\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": "import sys\nfrom collections.abc import Iterable, Mapping\nfrom typing import Any, Generic, TypeVar, overload\nfrom typing_extensions import TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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: ...\n    @property\n    def coded_value(self) -> _T: ...\n    @property\n    def key(self) -> str: ...\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    if sys.version_info >= (3, 9):\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[_T, 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 _typeshed import StrPath, SupportsRead, SupportsWrite\nfrom collections.abc import Mapping, Sequence\nfrom typing import Any, AnyStr, BinaryIO, ClassVar\n\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\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: str | 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\nclass 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\nfrom builtins import list as _list  # conflicts with a method named \"list\"\nfrom collections.abc import Callable\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\nfrom typing_extensions import Self, TypeAlias\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    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    if sys.version_info >= (3, 9):\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    else:\n        def __init__(self, host: str = \"\", port: int = 143) -> None: ...\n        def open(self, host: str = \"\", port: int = 143) -> None: ...\n\n    def __getattr__(self, attr: str) -> Any: ...\n    host: str\n    port: int\n    sock: _socket\n    file: IO[str] | IO[bytes]\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(self, mailbox: str, flags: str, date_time: str, message: ReadableBuffer) -> str: ...\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    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    if sys.version_info >= (3, 9):\n        def unselect(self) -> _CommandResults: ...\n\n    def xatom(self, name: str, *args: str) -> _CommandResults: ...\n    def print_log(self) -> None: ...\n\nclass IMAP4_SSL(IMAP4):\n    if sys.version_info < (3, 12):\n        keyfile: str\n        certfile: str\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    elif sys.version_info >= (3, 9):\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 993,\n            keyfile: str | None = None,\n            certfile: str | None = None,\n            ssl_context: SSLContext | None = None,\n            timeout: float | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 993,\n            keyfile: str | None = None,\n            certfile: str | None = None,\n            ssl_context: SSLContext | None = None,\n        ) -> None: ...\n    sslobj: SSLSocket\n    file: IO[Any]\n    if sys.version_info >= (3, 9):\n        def open(self, host: str = \"\", port: int | None = 993, timeout: float | None = None) -> None: ...\n    else:\n        def open(self, host: str = \"\", port: int | None = 993) -> None: ...\n\n    def ssl(self) -> SSLSocket: ...\n\nclass IMAP4_stream(IMAP4):\n    command: str\n    def __init__(self, command: str) -> None: ...\n    file: IO[Any]\n    process: subprocess.Popen[bytes]\n    writefile: IO[Any]\n    readfile: IO[Any]\n    if sys.version_info >= (3, 9):\n        def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: ...\n    else:\n        def open(self, host: str | None = None, port: int | 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, ...]: ...\ndef Time2Internaldate(date_time: float | time.struct_time | time._TimeTuple | datetime | str) -> 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\n\n__all__ = [\"what\"]\n\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, Protocol\n\nSEARCH_ERROR: int\nPY_SOURCE: int\nPY_COMPILED: int\nC_EXTENSION: int\nPY_RESOURCE: int\nPKG_DIRECTORY: int\nC_BUILTIN: int\nPY_FROZEN: int\nPY_CODERESOURCE: int\nIMP_HOOK: int\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.\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\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    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\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            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\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    class Finder(metaclass=ABCMeta): ...\n\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: ReadableBuffer | 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    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            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            def find_module(self, fullname: str) -> Loader | None: ...\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, name: str | None = None) -> str: ...  # type: ignore[override]\n    def load_module(self, name: str | None = None) -> types.ModuleType: ...  # type: ignore[override]\n\nclass 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\nif sys.version_info >= (3, 9):\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: ...  # type: ignore[override]\n        def contents(self) -> Iterator[str]: ...\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\n\ndef all_suffixes() -> list[str]: ...\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\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\nclass EntryPoint(_EntryPointBase):\n    pattern: ClassVar[Pattern[str]]\n    if sys.version_info >= (3, 11):\n        name: str\n        value: str\n        group: str\n\n        def __init__(self, name: str, value: str, group: str) -> None: ...\n\n    def load(self) -> Any: ...  # Callable[[], Any] or an importable module\n    @property\n    def extras(self) -> list[str]: ...\n    if sys.version_info >= (3, 9):\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 __eq__(self, other: object) -> bool: ...\n    if sys.version_info >= (3, 11):\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\nif sys.version_info >= (3, 12):\n    class EntryPoints(tuple[EntryPoint, ...]):\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\n    class EntryPoints(DeprecatedList[EntryPoint]):  # use as list is deprecated since 3.10\n        # int argument is deprecated since 3.10\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) -> _VT | None: ...\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    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: ...\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 Incomplete, 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, 11):\n    import importlib.resources.abc as abc\nelse:\n    import importlib.abc as 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) -> 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: Incomplete\n        def __init__(self, loader, 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: str) -> abc.Traversable: ...\n        elif sys.version_info >= (3, 11):\n            def joinpath(self, child: str) -> 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) -> 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, TextIO\nfrom typing_extensions import TypeAlias\n\nif sys.version_info >= (3, 11):\n    from importlib.resources._common import Package as Package\nelse:\n    Package: TypeAlias = str | ModuleType\n\nif sys.version_info >= (3, 9):\n    from importlib.abc import Traversable\n\n__all__ = [\"Package\", \"contents\", \"is_resource\", \"open_binary\", \"open_text\", \"path\", \"read_binary\", \"read_text\"]\n\nif sys.version_info >= (3, 9):\n    __all__ += [\"as_file\", \"files\"]\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, 13):\n    from importlib.resources._common import Anchor as Anchor\n\n    __all__ += [\"Anchor\"]\n\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]: ...\n    def is_resource(package: Package, name: str) -> bool: ...\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\nelif sys.version_info >= (3, 9):\n    def as_file(path: Traversable) -> AbstractContextManager[Path]: ...\n\nif sys.version_info >= (3, 11):\n    from importlib.resources._common import files as files\n\nelif sys.version_info >= (3, 9):\n    def files(package: Package) -> Traversable: ...\n\nif 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.abc import ResourceReader, Traversable\n    from pathlib import Path\n    from typing import 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(\"First parameter to files is renamed to 'anchor'\")\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]: ...\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, overload\n    from typing_extensions import Unpack\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]: ...\n    def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: ...\n    def contents(anchor: Anchor, *path_names: StrPath) -> Iterator[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/abc.pyi",
    "content": "import sys\n\nif sys.version_info >= (3, 11):\n    # These are all actually defined in this file on 3.11+,\n    # and re-exported from importlib.abc,\n    # but it's much less code duplication for typeshed if we pretend that they're still defined\n    # in importlib.abc on 3.11+, and re-exported from this file\n    from importlib.abc import (\n        ResourceReader as ResourceReader,\n        Traversable as Traversable,\n        TraversableResources as TraversableResources,\n    )\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 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: str) -> 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.abc\nimport 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 typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n\nif sys.version_info < (3, 12):\n    def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ...\n    def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ...\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(importlib.abc.Loader):\n    def __init__(self, loader: importlib.abc.Loader) -> None: ...\n    @classmethod\n    def factory(cls, loader: importlib.abc.Loader) -> Callable[..., LazyLoader]: ...\n    def exec_module(self, module: types.ModuleType) -> None: ...\n\ndef source_hash(source_bytes: ReadableBuffer) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/inspect.pyi",
    "content": "import dis\nimport enum\nimport sys\nimport types\nfrom _typeshed import 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\nfrom typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard, TypeIs\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\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_T_cont = TypeVar(\"_T_cont\", contravariant=True)\n_V_cont = TypeVar(\"_V_cont\", 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\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]: ...\ndef isfunction(object: object) -> TypeIs[FunctionType[..., Any]]: ...\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\nclass _SupportsSet(Protocol[_T_cont, _V_cont]):\n    def __set__(self, instance: _T_cont, value: _V_cont, /) -> None: ...\n\nclass _SupportsDelete(Protocol[_T_cont]):\n    def __delete__(self, instance: _T_cont, /) -> 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[..., Any]\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[..., Any] | 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, 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    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, 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, 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    def __str__(self) -> str: ...\n\nif sys.version_info >= (3, 10):\n    def get_annotations(\n        obj: Callable[..., object] | type[Any] | ModuleType,\n        *,\n        globals: Mapping[str, Any] | None = None,\n        locals: Mapping[str, Any] | None = None,\n        eval_str: bool = False,\n    ) -> dict[str, Any]: ...\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    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    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    class ArgSpec(NamedTuple):\n        args: list[str]\n        varargs: str | None\n        keywords: str | None\n        defaults: tuple[Any, ...]\n\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: ...\ndef formatannotation(annotation: object, base_module: str | None = None) -> str: ...\ndef formatannotationrelativeto(object: object) -> Callable[[object], str]: ...\n\nif sys.version_info < (3, 11):\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, ...]: ...\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 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(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    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\nif sys.version_info >= (3, 9):\n    class 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\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, 11):\n    from _io import text_encoding as text_encoding\n\n    __all__ += [\"DEFAULT_BUFFER_SIZE\", \"IncrementalNewlineDecoder\", \"text_encoding\"]\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"
  },
  {
    "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    @property\n    def compressed(self) -> str: ...\n    @property\n    def exploded(self) -> str: ...\n    @property\n    def reverse_pointer(self) -> str: ...\n    @property\n    def version(self) -> int: ...\n\nclass _BaseAddress(_IPAddressBase):\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    if sys.version_info >= (3, 9):\n        def __format__(self, fmt: str) -> str: ...\n\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    @property\n    def version(self) -> Literal[4]: ...\n    @property\n    def max_prefixlen(self) -> Literal[32]: ...\n\nclass IPv4Address(_BaseV4, _BaseAddress):\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 = ...) -> 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    @property\n    def version(self) -> Literal[6]: ...\n    @property\n    def max_prefixlen(self) -> Literal[128]: ...\n\nclass IPv6Address(_BaseV6, _BaseAddress):\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    if sys.version_info >= (3, 9):\n        @property\n        def scope_id(self) -> str | None: ...\n\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 = ...) -> 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 typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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\nclass count(Iterator[_N]):\n    @overload\n    def __new__(cls) -> count[int]: ...\n    @overload\n    def __new__(cls, start: _N, step: _Step = ...) -> count[_N]: ...\n    @overload\n    def __new__(cls, *, step: _N) -> count[_N]: ...\n    def __next__(self) -> _N: ...\n    def __iter__(self) -> Self: ...\n\nclass cycle(Iterator[_T]):\n    def __new__(cls, iterable: Iterable[_T], /) -> Self: ...\n    def __next__(self) -> _T: ...\n    def __iter__(self) -> Self: ...\n\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\nclass accumulate(Iterator[_T]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = ...) -> Self: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = ...) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\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\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\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\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\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 = ..., /) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\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\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\nclass zip_longest(Iterator[_T_co]):\n    # one iterable (fillvalue doesn't matter)\n    @overload\n    def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = ...) -> 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\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\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 = ...) -> permutations[tuple[_T, ...]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\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\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    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    class batched(Iterator[tuple[_T_co, ...]], Generic[_T_co]):\n        if sys.version_info >= (3, 13):\n            def __new__(cls, iterable: Iterable[_T_co], n: int, *, strict: bool = False) -> Self: ...\n        else:\n            def __new__(cls, iterable: Iterable[_T_co], n: int) -> Self: ...\n\n        def __iter__(self) -> Self: ...\n        def __next__(self) -> tuple[_T_co, ...]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/__init__.pyi",
    "content": "from _typeshed import SupportsRead, SupportsWrite\nfrom collections.abc import Callable\nfrom typing_extensions import Any, TypeAlias, overload, Never\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\n_JsonType: TypeAlias = dict[str, _JsonType] | list[_JsonType] | float | int | bool | str | None\n\ndef dumps(\n    obj: object,\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: object,\n) -> str: ...\ndef dump(\n    obj: object,\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[[Never], object] | None = None,\n    sort_keys: bool = False,\n    **kwds: object,\n) -> None: ...\n\n@overload\ndef loads(s: str | bytes | bytearray) -> _JsonType: ...\n@overload\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[Never, Never]]], object] | None = None,\n    **kwds: object,\n) -> object: ...\n\n@overload\ndef load(fp: SupportsRead[str | bytes])-> _JsonType:...\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: object,\n) -> object: ...\n\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]]\nESCAPE_ASCII: Final[Pattern[str]]\nHAS_UTF8: Final[Pattern[bytes]]\nESCAPE_DCT: Final[dict[str, str]]\nINFINITY: Final[float]\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\n\n__all__ = [\"make_scanner\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/tool.pyi",
    "content": "def main() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/keyword.pyi",
    "content": "import sys\nfrom collections.abc import Sequence\nfrom typing import Final\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"iskeyword\", \"issoftkeyword\", \"kwlist\", \"softkwlist\"]\nelse:\n    __all__ = [\"iskeyword\", \"kwlist\"]\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\nif sys.version_info >= (3, 9):\n    def issoftkeyword(s: str, /) -> bool: ...\n\n    # a list at runtime, but you're not meant to mutate it;\n    # type it as a sequence\n    softkwlist: 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 _typeshed import Incomplete\nfrom 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: Incomplete | 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": "import sys\nfrom collections.abc import Callable\nfrom typing import Any\nfrom typing_extensions import TypeAlias\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"getline\", \"clearcache\", \"checkcache\", \"lazycache\"]\nelse:\n    __all__ = [\"getline\", \"clearcache\", \"checkcache\"]\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\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    def resetlocale(category: int = ...) -> None: ...\n\nif sys.version_info < (3, 12):\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: ...\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, TracebackType\nfrom typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias, deprecated\n\nif sys.version_info >= (3, 11):\n    from types import GenericAlias\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    class _SupportsFilter(Protocol):\n        def filter(self, record: LogRecord, /) -> bool | LogRecord: ...\n\n    _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool | LogRecord] | _SupportsFilter\nelse:\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; use 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    if sys.version_info >= (3, 9):\n        default_msec_format: str | None\n    else:\n        default_msec_format: str\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    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; use 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; 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\nif sys.version_info >= (3, 9):\n    def basicConfig(\n        *,\n        filename: StrPath | None = ...,\n        filemode: str = ...,\n        format: str = ...,\n        datefmt: str | None = ...,\n        style: _FormatStyle = ...,\n        level: _Level | None = ...,\n        stream: SupportsWrite[str] | None = ...,\n        handlers: Iterable[Handler] | None = ...,\n        force: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str | None = ...,\n    ) -> None: ...\n\nelse:\n    def basicConfig(\n        *,\n        filename: StrPath | None = ...,\n        filemode: str = ...,\n        format: str = ...,\n        datefmt: str | None = ...,\n        style: _FormatStyle = ...,\n        level: _Level | None = ...,\n        stream: SupportsWrite[str] | None = ...,\n        handlers: Iterable[Handler] | None = ...,\n        force: bool = ...,\n    ) -> None: ...\n\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    if sys.version_info >= (3, 9):\n        errors: str | None  # 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    else:\n        def __init__(self, filename: StrPath, mode: str = \"a\", encoding: str | None = None, delay: bool = False) -> None: ...\n\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[str]\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\nfrom typing_extensions import Required, TypeAlias\n\nfrom . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level\n\nDEFAULT_LOGGING_CONFIG_PORT: int\nRESET_ERROR: Final[int]  # undocumented\nIDENTIFIER: Final[Pattern[str]]  # undocumented\n\nif sys.version_info >= (3, 11):\n    class _RootLoggerConfiguration(TypedDict, total=False):\n        level: _Level\n        filters: Sequence[str | _FilterType]\n        handlers: Sequence[str]\n\nelse:\n    class _RootLoggerConfiguration(TypedDict, total=False):\n        level: _Level\n        filters: Sequence[str]\n        handlers: Sequence[str]\n\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\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\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) -> Any: ...\n    def pop(self, idx: SupportsIndex = -1) -> Any: ...\n\nclass ConvertingTuple(tuple[Any, ...], ConvertingMixin):  # undocumented\n    @overload\n    def __getitem__(self, key: SupportsIndex) -> Any: ...\n    @overload\n    def __getitem__(self, key: slice) -> Any: ...\n\nclass BaseConfigurator:  # undocumented\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    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 typing import Any, ClassVar, Final, Protocol, TypeVar\n\n_T = TypeVar(\"_T\")\n\nDEFAULT_TCP_LOGGING_PORT: Final[int]\nDEFAULT_UDP_LOGGING_PORT: Final[int]\nDEFAULT_HTTP_LOGGING_PORT: Final[int]\nDEFAULT_SOAP_LOGGING_PORT: Final[int]\nSYSLOG_UDP_PORT: Final[int]\nSYSLOG_TCP_PORT: Final[int]\n\nclass WatchedFileHandler(FileHandler):\n    dev: int  # undocumented\n    ino: int  # undocumented\n    if sys.version_info >= (3, 9):\n        def __init__(\n            self, filename: StrPath, mode: str = \"a\", encoding: str | None = None, delay: bool = False, errors: str | None = None\n        ) -> None: ...\n    else:\n        def __init__(self, filename: StrPath, mode: str = \"a\", encoding: str | None = None, delay: bool = False) -> None: ...\n\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    if sys.version_info >= (3, 9):\n        def __init__(\n            self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None\n        ) -> None: ...\n    else:\n        def __init__(self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False) -> None: ...\n\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    if sys.version_info >= (3, 9):\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    else:\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        ) -> None: ...\n\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    if sys.version_info >= (3, 9):\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    else:\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        ) -> None: ...\n\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\n    if sys.version_info >= (3, 9):\n        LOG_NTP: int\n        LOG_SECURITY: int\n        LOG_CONSOLE: int\n        LOG_SOLCRON: int\n\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    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    if sys.version_info >= (3, 9):\n        def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ...  # undocumented\n\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"
  },
  {
    "path": "mypy/typeshed/stdlib/lzma.pyi",
    "content": "from _compression import BaseStream\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 typing import IO, Literal, TextIO, overload\nfrom typing_extensions import Self, TypeAlias\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) -> TextIO: ...\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) -> TextIO: ...\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 | TextIO: ...\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 types import TracebackType\nfrom typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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_MessageT = TypeVar(\"_MessageT\", bound=Message)\n\nclass _SupportsReadAndReadline(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ...\n\n_MessageData: TypeAlias = email.message.Message | bytes | str | io.StringIO | _SupportsReadAndReadline\n\nclass _HasIteritems(Protocol):\n    def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ...\n\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    if sys.version_info >= (3, 9):\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    if sys.version_info >= (3, 9):\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\nfrom typing_extensions import TypeAlias\n\nversion: 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, 13):\n    def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /, *, allow_code: bool = True) -> None: ...\n    def load(file: SupportsRead[bytes], /, *, allow_code: bool = True) -> Any: ...\n    def dumps(value: _Marshallable, version: int = 4, /, *, allow_code: bool = True) -> bytes: ...\n    def loads(bytes: ReadableBuffer, /, *, allow_code: bool = True) -> Any: ...\n\nelse:\n    def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /) -> None: ...\n    def load(file: SupportsRead[bytes], /) -> Any: ...\n    def dumps(value: _Marshallable, version: int = 4, /) -> bytes: ...\n    def loads(bytes: ReadableBuffer, /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/math.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom typing import Protocol, SupportsFloat, SupportsIndex, TypeVar, overload\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: float\npi: float\ninf: float\nnan: float\ntau: 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\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\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: ...\n\nif sys.version_info >= (3, 9):\n    def gcd(*integers: SupportsIndex) -> int: ...\n\nelse:\n    def gcd(x: SupportsIndex, y: SupportsIndex, /) -> int: ...\n\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: ...\n\nif sys.version_info >= (3, 9):\n    def lcm(*integers: SupportsIndex) -> int: ...\n\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\nelif sys.version_info >= (3, 9):\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@overload\ndef prod(iterable: Iterable[SupportsIndex], /, *, start: SupportsIndex = 1) -> int: ...  # type: ignore[overload-overlap]\n@overload\ndef prod(iterable: Iterable[_SupportsFloatOrIndex], /, *, start: _SupportsFloatOrIndex = 1) -> float: ...\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\nclass _SupportsTrunc(Protocol[_T_co]):\n    def __trunc__(self) -> _T_co: ...\n\ndef trunc(x: _SupportsTrunc[_T], /) -> _T: ...\n\nif sys.version_info >= (3, 9):\n    def 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 Sequence\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: Sequence[str] | None = None) -> None: ...\ndef read_mime_types(file: str) -> 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[str]\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: tuple[str, ...] = (), 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: str, 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 sys\nfrom _typeshed import ReadableBuffer, Unused\nfrom collections.abc import Iterator\nfrom typing import Final, Literal, NoReturn, overload\nfrom typing_extensions import Self\n\nACCESS_DEFAULT: int\nACCESS_READ: int\nACCESS_WRITE: int\nACCESS_COPY: int\n\nALLOCATIONGRANULARITY: int\n\nif sys.platform == \"linux\":\n    MAP_DENYWRITE: int\n    MAP_EXECUTABLE: int\n    if sys.version_info >= (3, 10):\n        MAP_POPULATE: int\nif sys.version_info >= (3, 11) and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    MAP_STACK: int\n\nif sys.platform != \"win32\":\n    MAP_ANON: int\n    MAP_ANONYMOUS: int\n    MAP_PRIVATE: int\n    MAP_SHARED: int\n    PROT_EXEC: int\n    PROT_READ: int\n    PROT_WRITE: int\n\nPAGESIZE: int\n\nclass mmap:\n    if sys.platform == \"win32\":\n        def __init__(self, fileno: int, length: int, tagname: str | None = ..., access: int = ..., offset: int = ...) -> None: ...\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 = ...,\n                offset: int = ...,\n                *,\n                trackfd: bool = True,\n            ) -> Self: ...\n        else:\n            def __new__(\n                cls, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = ..., offset: int = ...\n            ) -> Self: ...\n\n    def close(self) -> None: ...\n    def flush(self, offset: int = ..., 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    def seek(self, pos: int, whence: int = ...) -> None: ...\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 = ..., length: int = ...) -> None: ...\n\n    def find(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ...\n    def rfind(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ...\n    def read(self, n: int | None = ...) -> bytes: ...\n    def write(self, bytes: ReadableBuffer) -> int: ...\n    @overload\n    def __getitem__(self, key: int, /) -> int: ...\n    @overload\n    def __getitem__(self, key: slice, /) -> bytes: ...\n    def __delitem__(self, key: int | slice, /) -> NoReturn: ...\n    @overload\n    def __setitem__(self, key: int, value: int, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice, 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, *args: 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: int\n    MADV_RANDOM: int\n    MADV_SEQUENTIAL: int\n    MADV_WILLNEED: int\n    MADV_DONTNEED: int\n    MADV_FREE: int\n\nif sys.platform == \"linux\":\n    MADV_REMOVE: int\n    MADV_DONTFORK: int\n    MADV_DOFORK: int\n    MADV_HWPOISON: int\n    MADV_MERGEABLE: int\n    MADV_UNMERGEABLE: 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: int\n    MADV_HUGEPAGE: int\n    MADV_NOHUGEPAGE: int\n    MADV_DONTDUMP: int\n    MADV_DODUMP: 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: int\n    MADV_AUTOSYNC: int\n    MADV_NOCORE: int\n    MADV_CORE: int\n    MADV_PROTECT: int\n\nif sys.version_info >= (3, 10) and sys.platform == \"darwin\":\n    MADV_FREE_REUSABLE: int\n    MADV_FREE_REUSE: int\n\nif sys.version_info >= (3, 13) and sys.platform != \"win32\":\n    MAP_32BIT: Final = 32768\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, Literal\n\nif sys.platform == \"win32\":\n    from _msi import *\n    from _msi import _Database\n\n    AMD64: bool\n    Win64: bool\n\n    datasizemask: Literal[0x00FF]\n    type_valid: Literal[0x0100]\n    type_localizable: Literal[0x0200]\n    typemask: Literal[0x0C00]\n    type_long: Literal[0x0000]\n    type_short: Literal[0x0400]\n    type_string: Literal[0x0C00]\n    type_binary: Literal[0x0800]\n    type_nullable: Literal[0x1000]\n    type_key: Literal[0x2000]\n    knownbits: Literal[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\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: 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_extensions import TypeAlias\n\nif sys.platform == \"win32\":\n    _SequenceType: TypeAlias = list[tuple[str, str | None, int]]\n\n    AdminExecuteSequence: _SequenceType\n    AdminUISequence: _SequenceType\n    AdvtExecuteSequence: _SequenceType\n    InstallExecuteSequence: _SequenceType\n    InstallUISequence: _SequenceType\n\n    tables: list[str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/msilib/text.pyi",
    "content": "import sys\n\nif sys.platform == \"win32\":\n    ActionText: list[tuple[str, str, str | None]]\n    UIText: list[tuple[str, str | None]]\n    dirname: str\n    tables: 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: int\n    SEM_NOALIGNMENTFAULTEXCEPT: int\n    SEM_NOGPFAULTERRORBOX: int\n    SEM_NOOPENFILEERRORBOX: int\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 = TypeVar(\"_SendT\", contravariant=True, default=Any)\n_RecvT = TypeVar(\"_RecvT\", covariant=True, default=Any)\n\nclass _ConnectionBase(Generic[_SendT, _RecvT]):\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) -> 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: ...\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, _RecvT]): ...\n\nif sys.platform == \"win32\":\n    class PipeConnection(_ConnectionBase[_SendT, _RecvT]): ...\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, _RecvT] | socket.socket | int], timeout: float | None = None\n) -> list[Connection[_SendT, _RecvT] | 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 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    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] = {},\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": "from _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\ndef 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: ...\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\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    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 Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence\nfrom types import 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\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n_T = TypeVar(\"_T\")\n_KT = TypeVar(\"_KT\")\n_VT = TypeVar(\"_VT\")\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    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    if sys.version_info >= (3, 9):\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\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  # type: ignore[override]  # `default` shouldn't be positional\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\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, /) -> None: ...\n    @overload\n    def __getitem__(self, i: SupportsIndex, /) -> _T: ...\n    @overload\n    def __getitem__(self, s: slice, /) -> list[_T]: ...\n    @overload\n    def __setitem__(self, i: SupportsIndex, o: _T, /) -> None: ...\n    @overload\n    def __setitem__(self, s: slice, 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: ...  # type: ignore[override]\n    def extend(self, iterable: Iterable[_T], /) -> None: ...  # type: ignore[override]\n    def pop(self, index: SupportsIndex = ..., /) -> _T: ...  # type: ignore[override]\n    def index(self, value: _T, start: SupportsIndex = ..., stop: SupportsIndex = ..., /) -> int: ...  # type: ignore[override]\n    def count(self, value: _T, /) -> int: ...  # type: ignore[override]\n    def insert(self, index: SupportsIndex, object: _T, /) -> None: ...  # type: ignore[override]\n    def remove(self, value: _T, /) -> None: ...  # type: ignore[override]\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    @overload\n    def list(self, sequence: Sequence[_T], /) -> ListProxy[_T]: ...\n    @overload\n    def list(self) -> ListProxy[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": "import sys\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom multiprocessing.context import DefaultContext, Process\nfrom types import TracebackType\nfrom typing import Any, Final, Generic, TypeVar\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    if sys.version_info >= (3, 9):\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        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": "from 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    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 typing import Any, Generic, TypeVar\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n__all__ = [\"Queue\", \"SimpleQueue\", \"JoinableQueue\"]\n\n_T = TypeVar(\"_T\")\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 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 task_done(self) -> None: ...\n    def join(self) -> None: ...\n\nclass SimpleQueue(Generic[_T]):\n    def __init__(self, *, ctx: Any = ...) -> None: ...\n    if sys.version_info >= (3, 9):\n        def close(self) -> None: ...\n\n    def empty(self) -> bool: ...\n    def get(self) -> _T: ...\n    def put(self, obj: _T) -> None: ...\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/reduction.pyi",
    "content": "import pickle\nimport sys\nfrom _pickle import _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__(self, file: SupportsWrite[bytes], protocol: int | None = ...) -> 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    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": "from _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\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 typing import Any, Generic, TypeVar, overload\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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: ...\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    if sys.version_info >= (3, 9):\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, TypeVar, overload\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\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) -> list[_T]: ...\n    @overload\n    def __getitem__(self, i: int) -> _T: ...\n    @overload\n    def __setitem__(self, i: slice, value: Iterable[_T]) -> None: ...\n    @overload\n    def __setitem__(self, i: int, value: _T) -> None: ...\n    def __getslice__(self, start: int, stop: int) -> list[_T]: ...\n    def __setslice__(self, start: int, stop: int, values: Iterable[_T]) -> None: ...\n\nclass SynchronizedString(SynchronizedArray[bytes]):\n    @overload  # type: ignore[override]\n    def __getitem__(self, i: slice) -> bytes: ...\n    @overload\n    def __getitem__(self, i: int) -> bytes: ...\n    @overload  # type: ignore[override]\n    def __setitem__(self, i: slice, value: bytes) -> None: ...\n    @overload\n    def __setitem__(self, i: int, value: bytes) -> None: ...\n    def __getslice__(self, start: int, stop: int) -> bytes: ...  # type: ignore[override]\n    def __setslice__(self, start: int, stop: int, 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 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\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 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\n_T = TypeVar(\"_T\")\n_R_co = TypeVar(\"_R_co\", default=Any, covariant=True)\n\nNOTSET: Final[int]\nSUBDEBUG: Final[int]\nDEBUG: Final[int]\nINFO: Final[int]\nSUBWARNING: Final[int]\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: ...\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: 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\nimport sys\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    if sys.version_info < (3, 9):\n        def xgtitle(self, group: str, *, file: _File = None) -> tuple[str, _list[tuple[str, str]]]: ...\n        def xpath(self, id: Any) -> tuple[str, str]: ...\n\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        urandom as urandom,\n        utime as utime,\n        waitpid as waitpid,\n        write as write,\n    )\n\n    if sys.version_info >= (3, 9):\n        from os import unsetenv as unsetenv, waitstatus_to_exitcode as waitstatus_to_exitcode\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    environ: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ntpath.pyi",
    "content": "import sys\nfrom _typeshed import BytesPath, StrOrBytesPath, StrPath\nfrom genericpath import (\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]\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    if sys.version_info >= (3, 10):\n        @overload\n        def realpath(path: PathLike[AnyStr], *, strict: bool = False) -> AnyStr: ...\n        @overload\n        def realpath(path: AnyStr, *, strict: bool = False) -> AnyStr: ...\n    else:\n        @overload\n        def realpath(path: PathLike[AnyStr]) -> AnyStr: ...\n        @overload\n        def realpath(path: AnyStr) -> 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": "def url2pathname(url: str) -> str: ...\ndef 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 _typeshed import Incomplete\nfrom abc import ABCMeta, abstractmethod\nfrom typing import ClassVar, Literal, Protocol, overload\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 :(\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\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\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    @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    @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    @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    @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    @abstractmethod\n    def __int__(self) -> int: ...\n    def __index__(self) -> int: ...\n    @abstractmethod\n    def __pow__(self, exponent, modulus: Incomplete | None = 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 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\nif sys.version_info >= (3, 9):\n    cmp_op: tuple[Literal[\"<\"], Literal[\"<=\"], Literal[\"==\"], Literal[\"!=\"], Literal[\">\"], Literal[\">=\"]]\nelse:\n    cmp_op: tuple[\n        Literal[\"<\"],\n        Literal[\"<=\"],\n        Literal[\"==\"],\n        Literal[\"!=\"],\n        Literal[\">\"],\n        Literal[\">=\"],\n        Literal[\"in\"],\n        Literal[\"not in\"],\n        Literal[\"is\"],\n        Literal[\"is not\"],\n        Literal[\"exception match\"],\n        Literal[\"BAD\"],\n    ]\nhasconst: list[int]\nhasname: list[int]\nhasjrel: list[int]\nhasjabs: list[int]\nhaslocal: list[int]\nhascompare: list[int]\nhasfree: list[int]\nif sys.version_info >= (3, 12):\n    hasarg: list[int]\n    hasexc: list[int]\nelse:\n    hasnargs: list[int]\nif sys.version_info >= (3, 13):\n    hasjump: list[int]\nopname: list[str]\n\nopmap: dict[str, int]\nHAVE_ARGUMENT: int\nEXTENDED_ARG: 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[object]: ...\n    @overload\n    def __new__(cls, attr: str, attr2: str, /) -> attrgetter[tuple[object, object]]: ...\n    @overload\n    def __new__(cls, attr: str, attr2: str, attr3: str, /) -> attrgetter[tuple[object, object, object]]: ...\n    @overload\n    def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[object, object, object, object]]: ...\n    @overload\n    def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[object, ...]]: ...\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    # A suspected mypy issue prevents using [..., _T] instead of [..., Any] here.\n    # https://github.com/python/mypy/issues/14032\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 Incomplete, MaybeNone\nfrom abc import abstractmethod\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom typing import IO, Any, AnyStr, ClassVar, 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]\n\nNO_DEFAULT: tuple[str, ...]\nSUPPRESS_HELP: str\nSUPPRESS_USAGE: str\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,  # 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: Iterable[Incomplete]) -> list[Incomplete]: ...\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], add_help: bool = True) -> None: ...\n    def _process_args(self, largs: list[Incomplete], rargs: list[Incomplete], values: Values) -> None: ...\n    def _process_long_opt(self, rargs: list[Incomplete], values) -> None: ...\n    def _process_short_opts(self, rargs: list[Incomplete], 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    @overload\n    def parse_args(self, args: None = None, values: Values | None = None) -> tuple[Values, list[str]]: ...\n    @overload\n    def parse_args(self, args: Sequence[AnyStr], values: Values | None = None) -> tuple[Values, list[AnyStr]]: ...\n    def print_usage(self, file: IO[str] | None = None) -> None: ...\n    def print_help(self, file: IO[str] | None = None) -> None: ...\n    def print_version(self, file: IO[str] | None = None) -> None: ...\n    def set_default(self, dest, value) -> None: ...\n    def set_defaults(self, **kwargs) -> None: ...\n    def set_process_default_values(self, process) -> None: ...\n    def set_usage(self, usage: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/os/__init__.pyi",
    "content": "import sys\nfrom _typeshed import (\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 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)\nfrom typing_extensions import Self, TypeAlias, Unpack, deprecated\n\nfrom . import path as _path\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    \"urandom\",\n    \"utime\",\n    \"waitpid\",\n    \"walk\",\n    \"write\",\n]\nif sys.version_info >= (3, 9):\n    __all__ += [\"waitstatus_to_exitcode\"]\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        \"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        \"removexattr\",\n        \"setxattr\",\n    ]\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    ]\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 == \"linux\" and sys.version_info >= (3, 9):\n    __all__ += [\"P_PIDFD\", \"pidfd_open\"]\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_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 != \"win32\" and sys.version_info >= (3, 9):\n    __all__ += [\"CLD_KILLED\", \"CLD_STOPPED\"]\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\"]\nif sys.platform != \"win32\" or sys.version_info >= (3, 9):\n    __all__ += [\"unsetenv\"]\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: int\n    PRIO_PGRP: int\n    PRIO_USER: int\n\n    F_LOCK: int\n    F_TLOCK: int\n    F_ULOCK: int\n    F_TEST: int\n\n    if sys.platform != \"darwin\":\n        POSIX_FADV_NORMAL: int\n        POSIX_FADV_SEQUENTIAL: int\n        POSIX_FADV_RANDOM: int\n        POSIX_FADV_NOREUSE: int\n        POSIX_FADV_WILLNEED: int\n        POSIX_FADV_DONTNEED: 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: int\n        SF_MNOWAIT: int\n        SF_SYNC: int\n\n        if sys.version_info >= (3, 11):\n            SF_NOCACHE: int\n\n    if sys.platform == \"linux\":\n        XATTR_SIZE_MAX: int\n        XATTR_CREATE: int\n        XATTR_REPLACE: int\n\n    P_PID: int\n    P_PGID: int\n    P_ALL: int\n\n    if sys.platform == \"linux\" and sys.version_info >= (3, 9):\n        P_PIDFD: int\n\n    WEXITED: int\n    WSTOPPED: int\n    WNOWAIT: int\n\n    CLD_EXITED: int\n    CLD_DUMPED: int\n    CLD_TRAPPED: int\n    CLD_CONTINUED: int\n\n    if sys.version_info >= (3, 9):\n        CLD_KILLED: int\n        CLD_STOPPED: int\n\n    SCHED_OTHER: int\n    SCHED_FIFO: int\n    SCHED_RR: int\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        SCHED_SPORADIC: int\n\nif sys.platform == \"linux\":\n    SCHED_BATCH: int\n    SCHED_IDLE: int\n    SCHED_RESET_ON_FORK: int\n\nif sys.platform != \"win32\":\n    RTLD_LAZY: int\n    RTLD_NOW: int\n    RTLD_GLOBAL: int\n    RTLD_LOCAL: int\n    RTLD_NODELETE: int\n    RTLD_NOLOAD: int\n\nif sys.platform == \"linux\":\n    RTLD_DEEPBIND: int\n    GRND_NONBLOCK: int\n    GRND_RANDOM: int\n\nif sys.platform == \"darwin\" and sys.version_info >= (3, 12):\n    PRIO_DARWIN_BG: int\n    PRIO_DARWIN_NONUI: int\n    PRIO_DARWIN_PROCESS: int\n    PRIO_DARWIN_THREAD: int\n\nSEEK_SET: int\nSEEK_CUR: int\nSEEK_END: int\nif sys.platform != \"win32\":\n    SEEK_DATA: int\n    SEEK_HOLE: int\n\nO_RDONLY: int\nO_WRONLY: int\nO_RDWR: int\nO_APPEND: int\nO_CREAT: int\nO_EXCL: int\nO_TRUNC: int\nif sys.platform == \"win32\":\n    O_BINARY: int\n    O_NOINHERIT: int\n    O_SHORT_LIVED: int\n    O_TEMPORARY: int\n    O_RANDOM: int\n    O_SEQUENTIAL: int\n    O_TEXT: int\n\nif sys.platform != \"win32\":\n    O_DSYNC: int\n    O_SYNC: int\n    O_NDELAY: int\n    O_NONBLOCK: int\n    O_NOCTTY: int\n    O_CLOEXEC: int\n    O_ASYNC: int  # Gnu extension if in C library\n    O_DIRECTORY: int  # Gnu extension if in C library\n    O_NOFOLLOW: int  # Gnu extension if in C library\n    O_ACCMODE: int  # TODO: when does this exist?\n\nif sys.platform == \"linux\":\n    O_RSYNC: int\n    O_DIRECT: int  # Gnu extension if in C library\n    O_NOATIME: int  # Gnu extension if in C library\n    O_PATH: int  # Gnu extension if in C library\n    O_TMPFILE: int  # Gnu extension if in C library\n    O_LARGEFILE: int  # Gnu extension if in C library\n\nif sys.platform != \"linux\" and sys.platform != \"win32\":\n    O_SHLOCK: int\n    O_EXLOCK: int\n\nif sys.platform == \"darwin\" and sys.version_info >= (3, 10):\n    O_EVTONLY: int\n    O_NOFOLLOW_ANY: int\n    O_SYMLINK: int\n\nif sys.platform != \"win32\" and sys.version_info >= (3, 10):\n    O_FSYNC: int\n\nif sys.platform != \"linux\" and sys.platform != \"win32\" and sys.version_info >= (3, 13):\n    O_EXEC: int\n    O_SEARCH: int\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # posix, but apparently missing on macos\n    ST_APPEND: int\n    ST_MANDLOCK: int\n    ST_NOATIME: int\n    ST_NODEV: int\n    ST_NODIRATIME: int\n    ST_NOEXEC: int\n    ST_RELATIME: int\n    ST_SYNCHRONOUS: int\n    ST_WRITE: int\n\nif sys.platform != \"win32\":\n    NGROUPS_MAX: int\n    ST_NOSUID: int\n    ST_RDONLY: int\n\ncurdir: str\npardir: str\nsep: str\nif sys.platform == \"win32\":\n    altsep: str\nelse:\n    altsep: str | None\nextsep: str\npathsep: str\ndefpath: str\nlinesep: str\ndevnull: str\nname: str\n\nF_OK: int\nR_OK: int\nW_OK: int\nX_OK: int\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    if sys.version_info >= (3, 9):\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    else:\n        putenv: Callable[[AnyStr, AnyStr], object]\n        unsetenv: Callable[[AnyStr, AnyStr], object]\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            putenv: Callable[[AnyStr, AnyStr], object],\n            unsetenv: Callable[[AnyStr, AnyStr], object],\n        ) -> None: ...\n\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    if sys.version_info >= (3, 9):\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, 11) or sys.platform != \"win32\":\n    EX_OK: 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: int\n    EX_DATAERR: int\n    EX_NOINPUT: int\n    EX_NOUSER: int\n    EX_NOHOST: int\n    EX_UNAVAILABLE: int\n    EX_SOFTWARE: int\n    EX_OSERR: int\n    EX_OSFILE: int\n    EX_CANTCREAT: int\n    EX_IOERR: int\n    EX_TEMPFAIL: int\n    EX_PROTOCOL: int\n    EX_NOPERM: int\n    EX_CONFIG: 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: int\n\nP_NOWAIT: int\nP_NOWAITO: int\nP_WAIT: int\nif sys.platform == \"win32\":\n    P_DETACH: int\n    P_OVERLAY: int\n\n# wait()/waitpid() options\nif sys.platform != \"win32\":\n    WNOHANG: int  # Unix only\n    WCONTINUED: int  # some Unix systems\n    WUNTRACED: int  # Unix only\n\nTMP_MAX: 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]):  # type: ignore[misc]\n    @abstractmethod\n    def __fspath__(self) -> AnyStr: ...\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    if sys.version_info >= (3, 9):\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\n    if sys.version_info >= (3, 9):\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 = ...,\n    newline: str | None = ...,\n    closefd: bool = ...,\n    opener: _Opener | 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 = ...,\n    opener: _Opener | 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 = ...,\n    opener: _Opener | 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 = ...,\n    opener: _Opener | 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 = ...,\n    opener: _Opener | 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 = ...,\n    opener: _Opener | 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 = ...,\n    newline: str | None = ...,\n    closefd: bool = ...,\n    opener: _Opener | 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: int  # docs say available on 3.7+, stubtest says otherwise\n        RWF_DSYNC: int\n        RWF_SYNC: int\n        RWF_HIPRI: int\n        RWF_NOWAIT: 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\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 = ...) -> 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\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\ndef popen(cmd: str, mode: str = \"r\", buffering: int = -1) -> _wrap_close: ...\ndef spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ...\ndef spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ...  # Imprecise sig\n\nif sys.platform != \"win32\":\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    def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ...\n    def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ...\n\ndef system(command: StrOrBytesPath) -> int: ...\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    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    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    def posix_spawn(\n        path: StrOrBytesPath,\n        argv: _ExecVArgs,\n        env: _ExecEnv,\n        /,\n        *,\n        file_actions: Sequence[tuple[Any, ...]] | None = ...,\n        setpgroup: int | None = ...,\n        resetids: bool = ...,\n        setsid: bool = ...,\n        setsigmask: Iterable[int] = ...,\n        setsigdef: Iterable[int] = ...,\n        scheduler: tuple[Any, sched_param] | None = ...,\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 | None = ...,\n        resetids: bool = ...,\n        setsid: bool = ...,\n        setsigmask: Iterable[int] = ...,\n        setsigdef: Iterable[int] = ...,\n        scheduler: tuple[Any, sched_param] | None = ...,\n    ) -> int: ...\n    POSIX_SPAWN_OPEN: int\n    POSIX_SPAWN_CLOSE: int\n    POSIX_SPAWN_DUP2: int\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: int\n    MFD_ALLOW_SEALING: int\n    MFD_HUGETLB: int\n    MFD_HUGE_SHIFT: int\n    MFD_HUGE_MASK: int\n    MFD_HUGE_64KB: int\n    MFD_HUGE_512KB: int\n    MFD_HUGE_1MB: int\n    MFD_HUGE_2MB: int\n    MFD_HUGE_8MB: int\n    MFD_HUGE_16MB: int\n    MFD_HUGE_32MB: int\n    MFD_HUGE_256MB: int\n    MFD_HUGE_512MB: int\n    MFD_HUGE_1GB: int\n    MFD_HUGE_2GB: int\n    MFD_HUGE_16GB: 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 = ..., offset_dst: int | None = ...) -> int: ...\n\nif sys.version_info >= (3, 9):\n    def waitstatus_to_exitcode(status: int) -> int: ...\n\n    if sys.platform == \"linux\":\n        def pidfd_open(pid: int, flags: int = ...) -> int: ...\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: int\n    EFD_NONBLOCK: int\n    EFD_SEMAPHORE: int\n    SPLICE_F_MORE: int\n    SPLICE_F_MOVE: int\n    SPLICE_F_NONBLOCK: 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 = ...,\n        offset_dst: int | None = ...,\n        flags: int = 0,\n    ) -> int: ...\n\nif sys.version_info >= (3, 12) and sys.platform == \"linux\":\n    CLONE_FILES: int\n    CLONE_FS: int\n    CLONE_NEWCGROUP: int  # Linux 4.6+\n    CLONE_NEWIPC: int  # Linux 2.6.19+\n    CLONE_NEWNET: int  # Linux 2.6.24+\n    CLONE_NEWNS: int\n    CLONE_NEWPID: int  # Linux 3.8+\n    CLONE_NEWTIME: int  # Linux 5.6+\n    CLONE_NEWUSER: int  # Linux 3.8+\n    CLONE_NEWUTS: int  # Linux 2.6.19+\n    CLONE_SIGHAND: int\n    CLONE_SYSVSEM: int  # Linux 2.6.26+\n    CLONE_THREAD: int\n    CLONE_VM: 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, Literal, overload\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    AFMT_AC3: int\n    AFMT_A_LAW: int\n    AFMT_IMA_ADPCM: int\n    AFMT_MPEG: int\n    AFMT_MU_LAW: int\n    AFMT_QUERY: int\n    AFMT_S16_BE: int\n    AFMT_S16_LE: int\n    AFMT_S16_NE: int\n    AFMT_S8: int\n    AFMT_U16_BE: int\n    AFMT_U16_LE: int\n    AFMT_U8: int\n    SNDCTL_COPR_HALT: int\n    SNDCTL_COPR_LOAD: int\n    SNDCTL_COPR_RCODE: int\n    SNDCTL_COPR_RCVMSG: int\n    SNDCTL_COPR_RDATA: int\n    SNDCTL_COPR_RESET: int\n    SNDCTL_COPR_RUN: int\n    SNDCTL_COPR_SENDMSG: int\n    SNDCTL_COPR_WCODE: int\n    SNDCTL_COPR_WDATA: int\n    SNDCTL_DSP_BIND_CHANNEL: int\n    SNDCTL_DSP_CHANNELS: int\n    SNDCTL_DSP_GETBLKSIZE: int\n    SNDCTL_DSP_GETCAPS: int\n    SNDCTL_DSP_GETCHANNELMASK: int\n    SNDCTL_DSP_GETFMTS: int\n    SNDCTL_DSP_GETIPTR: int\n    SNDCTL_DSP_GETISPACE: int\n    SNDCTL_DSP_GETODELAY: int\n    SNDCTL_DSP_GETOPTR: int\n    SNDCTL_DSP_GETOSPACE: int\n    SNDCTL_DSP_GETSPDIF: int\n    SNDCTL_DSP_GETTRIGGER: int\n    SNDCTL_DSP_MAPINBUF: int\n    SNDCTL_DSP_MAPOUTBUF: int\n    SNDCTL_DSP_NONBLOCK: int\n    SNDCTL_DSP_POST: int\n    SNDCTL_DSP_PROFILE: int\n    SNDCTL_DSP_RESET: int\n    SNDCTL_DSP_SAMPLESIZE: int\n    SNDCTL_DSP_SETDUPLEX: int\n    SNDCTL_DSP_SETFMT: int\n    SNDCTL_DSP_SETFRAGMENT: int\n    SNDCTL_DSP_SETSPDIF: int\n    SNDCTL_DSP_SETSYNCRO: int\n    SNDCTL_DSP_SETTRIGGER: int\n    SNDCTL_DSP_SPEED: int\n    SNDCTL_DSP_STEREO: int\n    SNDCTL_DSP_SUBDIVIDE: int\n    SNDCTL_DSP_SYNC: int\n    SNDCTL_FM_4OP_ENABLE: int\n    SNDCTL_FM_LOAD_INSTR: int\n    SNDCTL_MIDI_INFO: int\n    SNDCTL_MIDI_MPUCMD: int\n    SNDCTL_MIDI_MPUMODE: int\n    SNDCTL_MIDI_PRETIME: int\n    SNDCTL_SEQ_CTRLRATE: int\n    SNDCTL_SEQ_GETINCOUNT: int\n    SNDCTL_SEQ_GETOUTCOUNT: int\n    SNDCTL_SEQ_GETTIME: int\n    SNDCTL_SEQ_NRMIDIS: int\n    SNDCTL_SEQ_NRSYNTHS: int\n    SNDCTL_SEQ_OUTOFBAND: int\n    SNDCTL_SEQ_PANIC: int\n    SNDCTL_SEQ_PERCMODE: int\n    SNDCTL_SEQ_RESET: int\n    SNDCTL_SEQ_RESETSAMPLES: int\n    SNDCTL_SEQ_SYNC: int\n    SNDCTL_SEQ_TESTMIDI: int\n    SNDCTL_SEQ_THRESHOLD: int\n    SNDCTL_SYNTH_CONTROL: int\n    SNDCTL_SYNTH_ID: int\n    SNDCTL_SYNTH_INFO: int\n    SNDCTL_SYNTH_MEMAVL: int\n    SNDCTL_SYNTH_REMOVESAMPLE: int\n    SNDCTL_TMR_CONTINUE: int\n    SNDCTL_TMR_METRONOME: int\n    SNDCTL_TMR_SELECT: int\n    SNDCTL_TMR_SOURCE: int\n    SNDCTL_TMR_START: int\n    SNDCTL_TMR_STOP: int\n    SNDCTL_TMR_TEMPO: int\n    SNDCTL_TMR_TIMEBASE: int\n    SOUND_MIXER_ALTPCM: int\n    SOUND_MIXER_BASS: int\n    SOUND_MIXER_CD: int\n    SOUND_MIXER_DIGITAL1: int\n    SOUND_MIXER_DIGITAL2: int\n    SOUND_MIXER_DIGITAL3: int\n    SOUND_MIXER_IGAIN: int\n    SOUND_MIXER_IMIX: int\n    SOUND_MIXER_LINE: int\n    SOUND_MIXER_LINE1: int\n    SOUND_MIXER_LINE2: int\n    SOUND_MIXER_LINE3: int\n    SOUND_MIXER_MIC: int\n    SOUND_MIXER_MONITOR: int\n    SOUND_MIXER_NRDEVICES: int\n    SOUND_MIXER_OGAIN: int\n    SOUND_MIXER_PCM: int\n    SOUND_MIXER_PHONEIN: int\n    SOUND_MIXER_PHONEOUT: int\n    SOUND_MIXER_RADIO: int\n    SOUND_MIXER_RECLEV: int\n    SOUND_MIXER_SPEAKER: int\n    SOUND_MIXER_SYNTH: int\n    SOUND_MIXER_TREBLE: int\n    SOUND_MIXER_VIDEO: int\n    SOUND_MIXER_VOLUME: 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 = ..., col_info: bool = ...) -> list[Any]: ...\ndef st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> 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 = ..., col_info: bool = ...) -> list[Any]: ...\n    def totuple(self, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pathlib.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 TracebackType\nfrom typing import IO, Any, BinaryIO, ClassVar, Literal, overload\nfrom typing_extensions import Self, deprecated\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n__all__ = [\"PurePath\", \"PurePosixPath\", \"PureWindowsPath\", \"Path\", \"PosixPath\", \"WindowsPath\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"UnsupportedOperation\"]\n\nclass PurePath(PathLike[str]):\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 __str__(self) -> str: ...\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    def as_uri(self) -> str: ...\n    def is_absolute(self) -> bool: ...\n    def is_reserved(self) -> bool: ...\n    if sys.version_info >= (3, 12):\n        def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ...\n    elif sys.version_info >= (3, 9):\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, 12):\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    if sys.version_info >= (3, 9):\n        def with_stem(self, stem: str) -> Self: ...\n\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, 9) and 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): ...\nclass PureWindowsPath(PurePath): ...\n\nclass Path(PurePath):\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(\n            self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n        ) -> Generator[Self, None, None]: ...\n        def rglob(\n            self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n        ) -> Generator[Self, None, None]: ...\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        def copy(self, target: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> None: ...\n        def copytree(\n            self,\n            target: StrPath,\n            *,\n            follow_symlinks: bool = True,\n            preserve_metadata: bool = False,\n            dirs_exist_ok: bool = False,\n            ignore: Callable[[Self], bool] | None = None,\n            on_error: Callable[[OSError], object] | None = None,\n        ) -> None: ...\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    if sys.platform != \"win32\":\n        # These methods do \"exist\" on Windows, but they always raise NotImplementedError,\n        # so it's safer to pretend they don't exist\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\" or sys.version_info >= (3, 12):\n        def is_mount(self) -> bool: ...\n\n    if sys.version_info >= (3, 9):\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    if sys.version_info >= (3, 14):\n        def delete(self, ignore_errors: bool = False, on_error: Callable[[OSError], object] | None = None) -> None: ...\n\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 as of Python 3.10 and 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 = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ...\n        ) -> Iterator[tuple[Self, list[str], list[str]]]: ...\n\n    if sys.version_info >= (3, 14):\n        def rmtree(self, ignore_errors: bool = False, on_error: Callable[[OSError], object] | None = None) -> None: ...\n\nclass PosixPath(Path, PurePosixPath): ...\nclass WindowsPath(Path, PureWindowsPath): ...\n\nif sys.version_info >= (3, 13):\n    class UnsupportedOperation(NotImplementedError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pdb.pyi",
    "content": "import signal\nimport sys\nfrom bdb import Bdb\nfrom cmd import Cmd\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom inspect import _SourceObjectType\nfrom types import CodeType, FrameType, TracebackType\nfrom typing import IO, Any, ClassVar, Final, TypeVar\nfrom typing_extensions import ParamSpec, Self\n\n__all__ = [\"run\", \"pm\", \"Pdb\", \"runeval\", \"runctx\", \"runcall\", \"set_trace\", \"post_mortem\", \"help\"]\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n\nline_prefix: 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: ...\ndef set_trace(*, header: str | None = None) -> None: ...\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    curframe_locals: Mapping[str, Any]\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    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    def checkline(self, filename: str, lineno: int) -> int: ...\n    def _getval(self, arg: str) -> object: ...\n    def print_stack_trace(self) -> None: ...\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, 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    def do_break(self, arg: str, temporary: bool = ...) -> bool | None: ...\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\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": "from _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, 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: int\nDEFAULT_PROTOCOL: int\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: bytes\nSTOP: bytes\nPOP: bytes\nPOP_MARK: bytes\nDUP: bytes\nFLOAT: bytes\nINT: bytes\nBININT: bytes\nBININT1: bytes\nLONG: bytes\nBININT2: bytes\nNONE: bytes\nPERSID: bytes\nBINPERSID: bytes\nREDUCE: bytes\nSTRING: bytes\nBINSTRING: bytes\nSHORT_BINSTRING: bytes\nUNICODE: bytes\nBINUNICODE: bytes\nAPPEND: bytes\nBUILD: bytes\nGLOBAL: bytes\nDICT: bytes\nEMPTY_DICT: bytes\nAPPENDS: bytes\nGET: bytes\nBINGET: bytes\nINST: bytes\nLONG_BINGET: bytes\nLIST: bytes\nEMPTY_LIST: bytes\nOBJ: bytes\nPUT: bytes\nBINPUT: bytes\nLONG_BINPUT: bytes\nSETITEM: bytes\nTUPLE: bytes\nEMPTY_TUPLE: bytes\nSETITEMS: bytes\nBINFLOAT: bytes\n\nTRUE: bytes\nFALSE: bytes\n\n# protocol 2\nPROTO: bytes\nNEWOBJ: bytes\nEXT1: bytes\nEXT2: bytes\nEXT4: bytes\nTUPLE1: bytes\nTUPLE2: bytes\nTUPLE3: bytes\nNEWTRUE: bytes\nNEWFALSE: bytes\nLONG1: bytes\nLONG4: bytes\n\n# protocol 3\nBINBYTES: bytes\nSHORT_BINBYTES: bytes\n\n# protocol 4\nSHORT_BINUNICODE: bytes\nBINUNICODE8: bytes\nBINBYTES8: bytes\nEMPTY_SET: bytes\nADDITEMS: bytes\nFROZENSET: bytes\nNEWOBJ_EX: bytes\nSTACK_GLOBAL: bytes\nMEMOIZE: bytes\nFRAME: bytes\n\n# protocol 5\nBYTEARRAY8: bytes\nNEXT_BUFFER: bytes\nREADONLY_BUFFER: bytes\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\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: int\nTAKEN_FROM_ARGUMENT1: int\nTAKEN_FROM_ARGUMENT4: int\nTAKEN_FROM_ARGUMENT4U: int\nTAKEN_FROM_ARGUMENT8U: int\n\nclass ArgumentDescriptor:\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    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    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 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    \"get_loader\",\n    \"find_loader\",\n    \"walk_packages\",\n    \"iter_modules\",\n    \"get_data\",\n    \"read_code\",\n    \"extend_path\",\n    \"ModuleInfo\",\n]\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    class ImpImporter:\n        def __init__(self, path: str | None = None) -> None: ...\n\n    class ImpLoader:\n        def __init__(self, fullname: str, file: IO[str], filename: str, etc: tuple[str, str, int]) -> None: ...\n\n@deprecated(\"Use importlib.util.find_spec() instead. Will be removed in Python 3.14.\")\ndef find_loader(fullname: str) -> LoaderProtocol | None: ...\ndef get_importer(path_item: str) -> PathEntryFinderProtocol | None: ...\n@deprecated(\"Use importlib.util.find_spec() instead. Will be removed in Python 3.14.\")\ndef get_loader(module_or_name: str) -> LoaderProtocol | None: ...\ndef iter_importers(fullname: str = \"\") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: ...\ndef iter_modules(path: Iterable[str] | None = None, prefix: str = \"\") -> Iterator[ModuleInfo]: ...\ndef read_code(stream: SupportsRead[bytes]) -> Any: ...  # undocumented\ndef walk_packages(\n    path: Iterable[str] | None = None, prefix: str = \"\", onerror: Callable[[str], object] | None = None\n) -> Iterator[ModuleInfo]: ...\ndef get_data(package: str, resource: str) -> bytes | None: ...\n\nif sys.version_info >= (3, 9):\n    def 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\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]: ...\ndef java_ver(\n    release: str = \"\", vendor: str = \"\", vminfo: tuple[str, str, str] = (\"\", \"\", \"\"), osinfo: tuple[str, str, str] = (\"\", \"\", \"\")\n) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ...\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\nif sys.version_info >= (3, 9):\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\n    class _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.\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\nelse:\n    # On 3.8, uname_result is actually just a regular NamedTuple.\n    class uname_result(NamedTuple):\n        system: str\n        node: str\n        release: str\n        version: str\n        machine: str\n        processor: 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 = ..., terse: bool = ...) -> 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"
  },
  {
    "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, ClassVar\nfrom typing_extensions import Self\n\n__all__ = [\"InvalidFileException\", \"FMT_XML\", \"FMT_BINARY\", \"load\", \"dump\", \"loads\", \"dumps\", \"UID\"]\nif sys.version_info < (3, 9):\n    __all__ += [\"readPlist\", \"writePlist\", \"readPlistFromBytes\", \"writePlistToBytes\", \"Data\"]\n\nclass PlistFormat(Enum):\n    FMT_XML = 1\n    FMT_BINARY = 2\n\nFMT_XML = PlistFormat.FMT_XML\nFMT_BINARY = 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\nelif sys.version_info >= (3, 9):\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\nelse:\n    def load(\n        fp: IO[bytes],\n        *,\n        fmt: PlistFormat | None = None,\n        use_builtin_types: bool = True,\n        dict_type: type[MutableMapping[str, Any]] = ...,\n    ) -> Any: ...\n    def loads(\n        value: ReadableBuffer,\n        *,\n        fmt: PlistFormat | None = None,\n        use_builtin_types: bool = True,\n        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\nif sys.version_info < (3, 9):\n    def readPlist(pathOrFile: str | IO[bytes]) -> Any: ...\n    def writePlist(value: Mapping[str, Any], pathOrFile: str | IO[bytes]) -> None: ...\n    def readPlistFromBytes(data: ReadableBuffer) -> Any: ...\n    def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ...\n\nif sys.version_info < (3, 9):\n    class Data:\n        data: bytes\n        def __init__(self, data: bytes) -> None: ...\n        __hash__: ClassVar[None]  # type: ignore[assignment]\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 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\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: 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        def __init__(\n            self,\n            host: str,\n            port: int = 995,\n            keyfile: str | None = None,\n            certfile: str | None = None,\n            timeout: float = ...,\n            context: ssl.SSLContext | None = None,\n        ) -> 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_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        write as write,\n        writev as writev,\n    )\n\n    if sys.version_info >= (3, 9):\n        from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode\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.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            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            removexattr as removexattr,\n            setxattr as setxattr,\n        )\n\n        if sys.version_info >= (3, 9):\n            from os import P_PIDFD as P_PIDFD, pidfd_open as pidfd_open\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                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    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]\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\nif sys.version_info >= (3, 10):\n    @overload\n    def realpath(filename: PathLike[AnyStr], *, strict: bool = False) -> AnyStr: ...\n    @overload\n    def realpath(filename: AnyStr, *, strict: bool = False) -> AnyStr: ...\n\nelse:\n    @overload\n    def realpath(filename: PathLike[AnyStr]) -> AnyStr: ...\n    @overload\n    def realpath(filename: AnyStr) -> AnyStr: ...\n\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 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 = ...,\n        indent: int = ...,\n        width: int = ...,\n        depth: int | None = ...,\n        *,\n        compact: bool = ...,\n        sort_dicts: bool = False,\n        underscore_numbers: bool = ...,\n    ) -> None: ...\n\nelse:\n    def pp(\n        object: object,\n        stream: IO[str] | None = ...,\n        indent: int = ...,\n        width: int = ...,\n        depth: int | None = ...,\n        *,\n        compact: bool = ...,\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"
  },
  {
    "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 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\nif sys.version_info >= (3, 9):\n    __all__ = [\"Stats\", \"SortKey\", \"FunctionProfile\", \"StatsProfile\"]\nelse:\n    __all__ = [\"Stats\", \"SortKey\"]\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\nif sys.version_info >= (3, 9):\n    from dataclasses import dataclass\n\n    @dataclass(unsafe_hash=True)\n    class 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)\n    class 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 = ...,\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    if sys.version_info >= (3, 9):\n        def get_stats_profile(self) -> StatsProfile: ...\n\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        @deprecated(\"Deprecated in 3.12, to be removed in 3.14; use openpty() instead\")\n        def master_open() -> tuple[int, str]: ...\n        @deprecated(\"Deprecated in 3.12, to be removed in 3.14; use openpty() instead\")\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\nfrom typing_extensions import TypeGuard\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\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]]: ...\ndef ispackage(path: str) -> bool: ...\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    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/topics.pyi",
    "content": "topics: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pyexpat/__init__.pyi",
    "content": "from _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    @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]\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 threading import Condition, Lock\nfrom typing import Any, Generic, TypeVar\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass PriorityQueue(Queue[_T]):\n    queue: list[_T]\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\n\n__all__ = [\"encode\", \"decode\", \"encodestring\", \"decodestring\"]\n\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\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]\n\nif sys.version_info >= (3, 9):\n    __all__ += [\"randbytes\"]\nif sys.version_info >= (3, 12):\n    __all__ += [\"binomialvariate\"]\n\n_T = TypeVar(\"_T\")\n\nclass Random(_random.Random):\n    VERSION: ClassVar[int]\n    if sys.version_info >= (3, 9):\n        def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: ...  # noqa: Y041\n    else:\n        def __init__(self, x: Any = None) -> None: ...\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, 9):\n        def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: ...  # type: ignore[override]  # noqa: Y041\n    else:\n        def seed(self, a: Any = None, version: int = 2) -> None: ...\n\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    if sys.version_info >= (3, 9):\n        def randbytes(self, n: int) -> bytes: ...\n\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        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    elif sys.version_info >= (3, 9):\n        def sample(\n            self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = None\n        ) -> list[_T]: ...\n    else:\n        def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int) -> 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\nif sys.version_info >= (3, 9):\n    randbytes = _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 typing import Any, AnyStr, Generic, Literal, TypeVar, final, overload\nfrom typing_extensions import TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    # This function is special-cased by basedmypy\n    @overload\n    def group(self, group: Literal[0] = 0, /) -> AnyStr: ...\n    @overload\n    def group(self, group: str | int, /) -> AnyStr | None: ...\n    @overload\n    def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | None, ...]: ...\n    # Each item of groups()'s return tuple is either \"AnyStr\" or\n    # \"AnyStr | None\", depending on the pattern.\n    # This function is special-cased by basedmypy\n    @overload\n    def groups(self) -> tuple[AnyStr | None, ...]: ...\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    # This function is special-cased by basedmypy\n    @overload\n    def groupdict(self) -> dict[str, AnyStr | None]: ...\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    # This function is special-cased by basedmypy\n    @overload\n    def __getitem__(self, key: Literal[0], /) -> AnyStr: ...\n    @overload\n    def __getitem__(self, key: int | str, /) -> AnyStr | None: ...\n    def __copy__(self) -> Match[AnyStr]: ...\n    def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ...\n    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    def __str__(self) -> str: ...\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 | None]: ...\n    @overload\n    def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | None]: ...\n    # This function is special-cased by basedmypy\n    @overload\n    def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[str | tuple[str | None, ...] | None]: ...\n    @overload\n    def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> list[str | tuple[str | None, ...] | None]: ...\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 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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    def __str__(self) -> str: ...\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 = RegexFlag.A\nASCII = RegexFlag.ASCII\nDEBUG = RegexFlag.DEBUG\nI = RegexFlag.I\nIGNORECASE = RegexFlag.IGNORECASE\nL = RegexFlag.L\nLOCALE = RegexFlag.LOCALE\nM = RegexFlag.M\nMULTILINE = RegexFlag.MULTILINE\nS = RegexFlag.S\nDOTALL = RegexFlag.DOTALL\nX = RegexFlag.X\nVERBOSE = RegexFlag.VERBOSE\nU = RegexFlag.U\nUNICODE = RegexFlag.UNICODE\nif sys.version_info < (3, 13):\n    T = RegexFlag.T\n    TEMPLATE = RegexFlag.TEMPLATE\nif sys.version_info >= (3, 11):\n    NOFLAG = 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# This function is special-cased by basedmypy\n@overload\ndef split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | None]: ...\n@overload\ndef split(\n    pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0\n) -> list[bytes | None]: ...\n# This function is special-cased by basedmypy\n@overload\ndef findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[str | tuple[str | None, ...] | None]: ...\n@overload\ndef findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> list[bytes | tuple[bytes | None, ...] | None]: ...\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# This function is special-cased by basedmypy\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    def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ...\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    RLIMIT_AS: int\n    RLIMIT_CORE: int\n    RLIMIT_CPU: int\n    RLIMIT_DATA: int\n    RLIMIT_FSIZE: int\n    RLIMIT_MEMLOCK: int\n    RLIMIT_NOFILE: int\n    RLIMIT_NPROC: int\n    RLIMIT_RSS: int\n    RLIMIT_STACK: int\n    RLIM_INFINITY: int\n    RUSAGE_CHILDREN: int\n    RUSAGE_SELF: int\n    if sys.platform == \"linux\":\n        RLIMIT_MSGQUEUE: int\n        RLIMIT_NICE: int\n        RLIMIT_OFILE: int\n        RLIMIT_RTPRIO: int\n        RLIMIT_RTTIME: int\n        RLIMIT_SIGPENDING: int\n        RUSAGE_THREAD: 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\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__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], object] = ...) -> 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 TypeVar\n\n__all__ = [\"choice\", \"randbelow\", \"randbits\", \"SystemRandom\", \"token_bytes\", \"token_hex\", \"token_urlsafe\", \"compare_digest\"]\n\n_T = TypeVar(\"_T\")\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\nfrom typing_extensions import Self\n\nif sys.platform != \"win32\":\n    PIPE_BUF: int\n    POLLERR: int\n    POLLHUP: int\n    POLLIN: int\n    if sys.platform == \"linux\":\n        POLLMSG: int\n    POLLNVAL: int\n    POLLOUT: int\n    POLLPRI: int\n    POLLRDBAND: int\n    if sys.platform == \"linux\":\n        POLLRDHUP: int\n    POLLRDNORM: int\n    POLLWRBAND: int\n    POLLWRNORM: 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\ndef select(\n    rlist: Iterable[Any], wlist: Iterable[Any], xlist: Iterable[Any], timeout: float | None = None, /\n) -> tuple[list[Any], list[Any], list[Any]]: ...\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,\n            ident: FileDescriptorLike,\n            filter: int = ...,\n            flags: int = ...,\n            fflags: int = ...,\n            data: Any = ...,\n            udata: Any = ...,\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: int\n    KQ_EV_CLEAR: int\n    KQ_EV_DELETE: int\n    KQ_EV_DISABLE: int\n    KQ_EV_ENABLE: int\n    KQ_EV_EOF: int\n    KQ_EV_ERROR: int\n    KQ_EV_FLAG1: int\n    KQ_EV_ONESHOT: int\n    KQ_EV_SYSFLAGS: int\n    KQ_FILTER_AIO: int\n    if sys.platform != \"darwin\":\n        KQ_FILTER_NETDEV: int\n    KQ_FILTER_PROC: int\n    KQ_FILTER_READ: int\n    KQ_FILTER_SIGNAL: int\n    KQ_FILTER_TIMER: int\n    KQ_FILTER_VNODE: int\n    KQ_FILTER_WRITE: int\n    KQ_NOTE_ATTRIB: int\n    KQ_NOTE_CHILD: int\n    KQ_NOTE_DELETE: int\n    KQ_NOTE_EXEC: int\n    KQ_NOTE_EXIT: int\n    KQ_NOTE_EXTEND: int\n    KQ_NOTE_FORK: int\n    KQ_NOTE_LINK: int\n    if sys.platform != \"darwin\":\n        KQ_NOTE_LINKDOWN: int\n        KQ_NOTE_LINKINV: int\n        KQ_NOTE_LINKUP: int\n    KQ_NOTE_LOWAT: int\n    KQ_NOTE_PCTRLMASK: int\n    KQ_NOTE_PDATAMASK: int\n    KQ_NOTE_RENAME: int\n    KQ_NOTE_REVOKE: int\n    KQ_NOTE_TRACK: int\n    KQ_NOTE_TRACKERR: int\n    KQ_NOTE_WRITE: int\n\nif sys.platform == \"linux\":\n    @final\n    class epoll:\n        def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self,\n            exc_type: type[BaseException] | None = None,\n            exc_value: BaseException | 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: int\n    EPOLLEXCLUSIVE: int\n    EPOLLET: int\n    EPOLLHUP: int\n    EPOLLIN: int\n    EPOLLMSG: int\n    EPOLLONESHOT: int\n    EPOLLOUT: int\n    EPOLLPRI: int\n    EPOLLRDBAND: int\n    EPOLLRDHUP: int\n    EPOLLRDNORM: int\n    EPOLLWRBAND: int\n    EPOLLWRNORM: int\n    EPOLL_CLOEXEC: 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 = ...) -> 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, NamedTuple\nfrom typing_extensions import Self, TypeAlias\n\n_EventMask: TypeAlias = int\n\nEVENT_READ: _EventMask\nEVENT_WRITE: _EventMask\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, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite\nfrom collections.abc import Callable, Iterable, Sequence\nfrom tarfile import _TarfileFilter\nfrom typing import Any, AnyStr, NamedTuple, Protocol, TypeVar, overload\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    \"ExecError\",\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]\n\n_StrOrBytesPathT = TypeVar(\"_StrOrBytesPathT\", bound=StrOrBytesPath)\n_StrPathT = TypeVar(\"_StrPathT\", bound=StrPath)\n# Return value of some functions that may either return a path-like object that was passed in or\n# a string\n_PathReturn: TypeAlias = Any\n\nclass Error(OSError): ...\nclass SameFileError(Error): ...\nclass SpecialFileError(OSError): ...\nclass ExecError(OSError): ...\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: StrPath, *, follow_symlinks: bool = True) -> _PathReturn: ...\n@overload\ndef copy(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = True) -> _PathReturn: ...\n@overload\ndef copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = True) -> _PathReturn: ...\n@overload\ndef copy2(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = True) -> _PathReturn: ...\ndef ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ...\ndef copytree(\n    src: StrPath,\n    dst: StrPath,\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) -> _PathReturn: ...\n\n_OnErrorCallback: TypeAlias = Callable[[Callable[..., Any], str, ExcInfo], object]\n_OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object]\n\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,\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,\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)\nif sys.version_info >= (3, 9):\n    def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ...\n\nelse:\n    # See https://bugs.python.org/issue32689\n    def move(src: str, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ...\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\n@overload\ndef which(cmd: _StrPathT, mode: int = 1, path: StrPath | None = None) -> str | _StrPathT | 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, Literal, 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: Literal[Handlers.SIG_DFL]\nSIG_IGN: Literal[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: Literal[Signals.SIGABRT]\nSIGFPE: Literal[Signals.SIGFPE]\nSIGILL: Literal[Signals.SIGILL]\nSIGINT: Literal[Signals.SIGINT]\nSIGSEGV: Literal[Signals.SIGSEGV]\nSIGTERM: Literal[Signals.SIGTERM]\n\nif sys.platform == \"win32\":\n    SIGBREAK: Literal[Signals.SIGBREAK]\n    CTRL_C_EVENT: Literal[Signals.CTRL_C_EVENT]\n    CTRL_BREAK_EVENT: Literal[Signals.CTRL_BREAK_EVENT]\nelse:\n    if sys.platform != \"linux\":\n        SIGINFO: Literal[Signals.SIGINFO]\n        SIGEMT: Literal[Signals.SIGEMT]\n    SIGALRM: Literal[Signals.SIGALRM]\n    SIGBUS: Literal[Signals.SIGBUS]\n    SIGCHLD: Literal[Signals.SIGCHLD]\n    SIGCONT: Literal[Signals.SIGCONT]\n    SIGHUP: Literal[Signals.SIGHUP]\n    SIGIO: Literal[Signals.SIGIO]\n    SIGIOT: Literal[Signals.SIGABRT]  # alias\n    SIGKILL: Literal[Signals.SIGKILL]\n    SIGPIPE: Literal[Signals.SIGPIPE]\n    SIGPROF: Literal[Signals.SIGPROF]\n    SIGQUIT: Literal[Signals.SIGQUIT]\n    SIGSTOP: Literal[Signals.SIGSTOP]\n    SIGSYS: Literal[Signals.SIGSYS]\n    SIGTRAP: Literal[Signals.SIGTRAP]\n    SIGTSTP: Literal[Signals.SIGTSTP]\n    SIGTTIN: Literal[Signals.SIGTTIN]\n    SIGTTOU: Literal[Signals.SIGTTOU]\n    SIGURG: Literal[Signals.SIGURG]\n    SIGUSR1: Literal[Signals.SIGUSR1]\n    SIGUSR2: Literal[Signals.SIGUSR2]\n    SIGVTALRM: Literal[Signals.SIGVTALRM]\n    SIGWINCH: Literal[Signals.SIGWINCH]\n    SIGXCPU: Literal[Signals.SIGXCPU]\n    SIGXFSZ: Literal[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: Literal[Sigmasks.SIG_BLOCK]\n    SIG_UNBLOCK: Literal[Sigmasks.SIG_UNBLOCK]\n    SIG_SETMASK: Literal[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: Literal[Signals.SIGCHLD]  # alias\n        SIGPOLL: Literal[Signals.SIGIO]  # alias\n        SIGPWR: Literal[Signals.SIGPWR]\n        SIGRTMAX: Literal[Signals.SIGRTMAX]\n        SIGRTMIN: Literal[Signals.SIGRTMIN]\n        if sys.version_info >= (3, 11):\n            SIGSTKFLT: Literal[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 = ...) -> int: ...\n\nif sys.version_info >= (3, 9):\n    if sys.platform == \"linux\":\n        def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = ..., /) -> 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\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    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\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, Protocol, overload\nfrom typing_extensions import Self, TypeAlias\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: int\nSMTP_SSL_PORT: int\nCRLF: str\nbCRLF: bytes\n\nOLDSTYLE_AUTH: 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\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        def starttls(\n            self, keyfile: str | None = None, certfile: str | None = None, context: SSLContext | 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    keyfile: str | None\n    certfile: str | None\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        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 0,\n            local_hostname: str | None = None,\n            keyfile: str | None = None,\n            certfile: str | None = None,\n            timeout: float = ...,\n            source_address: _SourceAddress | None = None,\n            context: SSLContext | None = None,\n        ) -> None: ...\n\nLMTP_PORT: int\n\nclass LMTP(SMTP):\n    if sys.version_info >= (3, 9):\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    else:\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        ) -> 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_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_RECVTCLASS as IPV6_RECVTCLASS,\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, Literal, Protocol, SupportsIndex, overload\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_JOIN_GROUP\",\n    \"IPV6_LEAVE_GROUP\",\n    \"IPV6_MULTICAST_HOPS\",\n    \"IPV6_MULTICAST_IF\",\n    \"IPV6_MULTICAST_LOOP\",\n    \"IPV6_RECVTCLASS\",\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\" or sys.version_info >= (3, 9):\n    from _socket import (\n        IPV6_DONTFRAG as IPV6_DONTFRAG,\n        IPV6_HOPLIMIT as IPV6_HOPLIMIT,\n        IPV6_HOPOPTS as IPV6_HOPOPTS,\n        IPV6_PKTINFO as IPV6_PKTINFO,\n        IPV6_RECVRTHDR as IPV6_RECVRTHDR,\n        IPV6_RTHDR as IPV6_RTHDR,\n    )\n\n    __all__ += [\"IPV6_DONTFRAG\", \"IPV6_HOPLIMIT\", \"IPV6_HOPOPTS\", \"IPV6_PKTINFO\", \"IPV6_RECVRTHDR\", \"IPV6_RTHDR\"]\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    if sys.platform != \"darwin\" or sys.version_info >= (3, 9):\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\" and sys.platform != \"linux\":\n    if sys.platform != \"win32\" or sys.version_info >= (3, 9):\n        from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM\n\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\nif sys.platform == \"linux\" and sys.version_info >= (3, 9):\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\" and sys.version_info >= (3, 9):\n    __all__ += [\"send_fds\", \"recv_fds\"]\n\nif sys.platform != \"win32\" or sys.version_info >= (3, 9):\n    if sys.platform != \"linux\":\n        __all__ += [\"AF_LINK\"]\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        __all__ += [\"AF_BLUETOOTH\"]\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        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        \"LOCAL_PEERCRED\",\n        \"SCM_CREDS\",\n        \"AI_DEFAULT\",\n        \"AI_MASK\",\n        \"AI_V4MAPPED_CFG\",\n        \"MSG_EOF\",\n    ]\n    if sys.platform != \"darwin\" or sys.version_info >= (3, 9):\n        from _socket import IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU\n\n        __all__ += [\"IPV6_USE_MIN_MTU\"]\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\n# Re-exported from errno\nEBADF: int\nEAGAIN: int\nEWOULDBLOCK: 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 != \"win32\" or sys.version_info >= (3, 9):\n        if sys.platform != \"linux\":\n            AF_LINK = 33\n        if sys.platform != \"darwin\" and sys.platform != \"linux\":\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 = AddressFamily.AF_INET\nAF_INET6 = AddressFamily.AF_INET6\nAF_APPLETALK = AddressFamily.AF_APPLETALK\nAF_DECnet: Literal[12]\nAF_IPX = AddressFamily.AF_IPX\nAF_SNA = AddressFamily.AF_SNA\nAF_UNSPEC = AddressFamily.AF_UNSPEC\n\nif sys.platform != \"darwin\":\n    AF_IRDA = AddressFamily.AF_IRDA\n\nif sys.platform != \"win32\":\n    AF_ROUTE = AddressFamily.AF_ROUTE\n    AF_UNIX = AddressFamily.AF_UNIX\n\nif sys.platform == \"darwin\":\n    AF_SYSTEM = AddressFamily.AF_SYSTEM\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    AF_ASH = AddressFamily.AF_ASH\n    AF_ATMPVC = AddressFamily.AF_ATMPVC\n    AF_ATMSVC = AddressFamily.AF_ATMSVC\n    AF_AX25 = AddressFamily.AF_AX25\n    AF_BRIDGE = AddressFamily.AF_BRIDGE\n    AF_ECONET = AddressFamily.AF_ECONET\n    AF_KEY = AddressFamily.AF_KEY\n    AF_LLC = AddressFamily.AF_LLC\n    AF_NETBEUI = AddressFamily.AF_NETBEUI\n    AF_NETROM = AddressFamily.AF_NETROM\n    AF_PPPOX = AddressFamily.AF_PPPOX\n    AF_ROSE = AddressFamily.AF_ROSE\n    AF_SECURITY = AddressFamily.AF_SECURITY\n    AF_WANPIPE = AddressFamily.AF_WANPIPE\n    AF_X25 = AddressFamily.AF_X25\n\nif sys.platform == \"linux\":\n    AF_CAN = AddressFamily.AF_CAN\n    AF_PACKET = AddressFamily.AF_PACKET\n    AF_RDS = AddressFamily.AF_RDS\n    AF_TIPC = AddressFamily.AF_TIPC\n    AF_ALG = AddressFamily.AF_ALG\n    AF_NETLINK = AddressFamily.AF_NETLINK\n    AF_VSOCK = AddressFamily.AF_VSOCK\n    AF_QIPCRTR = AddressFamily.AF_QIPCRTR\n\nif sys.platform != \"win32\" or sys.version_info >= (3, 9):\n    if sys.platform != \"linux\":\n        AF_LINK = AddressFamily.AF_LINK\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        AF_BLUETOOTH = AddressFamily.AF_BLUETOOTH\n\nif sys.platform == \"win32\" and sys.version_info >= (3, 12):\n    AF_HYPERV = 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 = 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 = SocketKind.SOCK_STREAM\nSOCK_DGRAM = SocketKind.SOCK_DGRAM\nSOCK_RAW = SocketKind.SOCK_RAW\nSOCK_RDM = SocketKind.SOCK_RDM\nSOCK_SEQPACKET = SocketKind.SOCK_SEQPACKET\nif sys.platform == \"linux\":\n    SOCK_CLOEXEC = SocketKind.SOCK_CLOEXEC\n    SOCK_NONBLOCK = 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 = MsgFlag.MSG_CTRUNC\nMSG_DONTROUTE = MsgFlag.MSG_DONTROUTE\nMSG_OOB = MsgFlag.MSG_OOB\nMSG_PEEK = MsgFlag.MSG_PEEK\nMSG_TRUNC = MsgFlag.MSG_TRUNC\nMSG_WAITALL = MsgFlag.MSG_WAITALL\n\nif sys.platform == \"win32\":\n    MSG_BCAST = MsgFlag.MSG_BCAST\n    MSG_MCAST = MsgFlag.MSG_MCAST\n\nif sys.platform != \"darwin\":\n    MSG_ERRQUEUE = MsgFlag.MSG_ERRQUEUE\n\nif sys.platform != \"win32\":\n    MSG_DONTWAIT = MsgFlag.MSG_DONTWAIT\n    MSG_EOR = MsgFlag.MSG_EOR\n    MSG_NOSIGNAL = MsgFlag.MSG_NOSIGNAL  # Sometimes this exists on darwin, sometimes not\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    MSG_CMSG_CLOEXEC = MsgFlag.MSG_CMSG_CLOEXEC\n    MSG_CONFIRM = MsgFlag.MSG_CONFIRM\n    MSG_FASTOPEN = MsgFlag.MSG_FASTOPEN\n    MSG_MORE = MsgFlag.MSG_MORE\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    MSG_NOTIFICATION = MsgFlag.MSG_NOTIFICATION\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    MSG_EOF = 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 = AddressInfo.AI_ADDRCONFIG\nAI_ALL = AddressInfo.AI_ALL\nAI_CANONNAME = AddressInfo.AI_CANONNAME\nAI_NUMERICHOST = AddressInfo.AI_NUMERICHOST\nAI_NUMERICSERV = AddressInfo.AI_NUMERICSERV\nAI_PASSIVE = AddressInfo.AI_PASSIVE\nAI_V4MAPPED = AddressInfo.AI_V4MAPPED\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    AI_DEFAULT = AddressInfo.AI_DEFAULT\n    AI_MASK = AddressInfo.AI_MASK\n    AI_V4MAPPED_CFG = AddressInfo.AI_V4MAPPED_CFG\n\nif sys.platform == \"win32\":\n    errorTab: dict[int, str]  # undocumented\n\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    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    if sys.version_info >= (3, 9):\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: SocketType | 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, int],\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\n# This can possibly be generic at some point:\nclass BaseServer:\n    address_family: int\n    server_address: _Address\n    socket: _socket\n    allow_reuse_address: bool\n    request_queue_size: int\n    socket_type: int\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 fileno(self) -> int: ...\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]: ...\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 server_bind(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    if sys.version_info >= (3, 11):\n        allow_reuse_port: bool\n    server_address: _AfInetAddress\n    def __init__(\n        self,\n        server_address: _AfInetAddress,\n        RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler],\n        bind_and_activate: bool = True,\n    ) -> None: ...\n    def get_request(self) -> tuple[_socket, _RetAddress]: ...\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    version_info as version_info,\n)\nfrom types import TracebackType\nfrom typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\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\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\nclass _WindowAggregateClass(Protocol):\n    step: Callable[..., object]\n    inverse: Callable[..., object]\n    def value(self) -> _SqliteData: ...\n    def finalize(self) -> _SqliteData: ...\n\nclass _AggregateProtocol(Protocol):\n    def step(self, value: int, /) -> object: ...\n    def finalize(self) -> int: ...\n\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\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: str | None  # one of '', 'DEFERRED', 'IMMEDIATE' or 'EXCLUSIVE'\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: Any\n    text_factory: Any\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            database: StrOrBytesPath,\n            timeout: float = ...,\n            detect_types: int = ...,\n            isolation_level: str | None = ...,\n            check_same_thread: bool = ...,\n            factory: type[Connection] | None = ...,\n            cached_statements: int = ...,\n            uri: bool = ...,\n            autocommit: bool = ...,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            database: StrOrBytesPath,\n            timeout: float = ...,\n            detect_types: int = ...,\n            isolation_level: str | None = ...,\n            check_same_thread: bool = ...,\n            factory: type[Connection] | None = ...,\n            cached_statements: int = ...,\n            uri: bool = ...,\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], int | 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\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: Callable[[Cursor, Row], object] | None\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\nclass Row(Sequence[Any]):\n    def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ...\n    def keys(self) -> list[str]: ...\n    @overload\n    def __getitem__(self, key: int | str, /) -> Any: ...\n    @overload\n    def __getitem__(self, key: slice, /) -> 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)\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: 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        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: str\nthreadsafety: int\napilevel: 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: tuple[int, int, int]\n\nsqlite_version_info: 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\n\nMAXCODE: int\n\ndef dis(code: list[_NamedIntConstant]) -> None: ...\ndef isstring(obj: Any) -> bool: ...\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 Any\nfrom typing_extensions import Self\n\nMAXGROUPS: int\n\nMAGIC: int\n\nclass _NamedIntConstant(int):\n    name: Any\n    def __new__(cls, value: int, name: str) -> Self: ...\n\nMAXREPEAT: _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, 13):\n    SRE_FLAG_TEMPLATE: int\nSRE_FLAG_IGNORECASE: int\nSRE_FLAG_LOCALE: int\nSRE_FLAG_MULTILINE: int\nSRE_FLAG_DOTALL: int\nSRE_FLAG_UNICODE: int\nSRE_FLAG_VERBOSE: int\nSRE_FLAG_DEBUG: int\nSRE_FLAG_ASCII: int\nSRE_INFO_PREFIX: int\nSRE_INFO_LITERAL: int\nSRE_INFO_CHARSET: int\n\n# Stubgen above; manually defined constants below (dynamic at runtime)\n\n# from OPCODES\nFAILURE: _NamedIntConstant\nSUCCESS: _NamedIntConstant\nANY: _NamedIntConstant\nANY_ALL: _NamedIntConstant\nASSERT: _NamedIntConstant\nASSERT_NOT: _NamedIntConstant\nAT: _NamedIntConstant\nBRANCH: _NamedIntConstant\nif sys.version_info < (3, 11):\n    CALL: _NamedIntConstant\nCATEGORY: _NamedIntConstant\nCHARSET: _NamedIntConstant\nBIGCHARSET: _NamedIntConstant\nGROUPREF: _NamedIntConstant\nGROUPREF_EXISTS: _NamedIntConstant\nGROUPREF_IGNORE: _NamedIntConstant\nIN: _NamedIntConstant\nIN_IGNORE: _NamedIntConstant\nINFO: _NamedIntConstant\nJUMP: _NamedIntConstant\nLITERAL: _NamedIntConstant\nLITERAL_IGNORE: _NamedIntConstant\nMARK: _NamedIntConstant\nMAX_UNTIL: _NamedIntConstant\nMIN_UNTIL: _NamedIntConstant\nNOT_LITERAL: _NamedIntConstant\nNOT_LITERAL_IGNORE: _NamedIntConstant\nNEGATE: _NamedIntConstant\nRANGE: _NamedIntConstant\nREPEAT: _NamedIntConstant\nREPEAT_ONE: _NamedIntConstant\nSUBPATTERN: _NamedIntConstant\nMIN_REPEAT_ONE: _NamedIntConstant\nif sys.version_info >= (3, 11):\n    ATOMIC_GROUP: _NamedIntConstant\n    POSSESSIVE_REPEAT: _NamedIntConstant\n    POSSESSIVE_REPEAT_ONE: _NamedIntConstant\nRANGE_UNI_IGNORE: _NamedIntConstant\nGROUPREF_LOC_IGNORE: _NamedIntConstant\nGROUPREF_UNI_IGNORE: _NamedIntConstant\nIN_LOC_IGNORE: _NamedIntConstant\nIN_UNI_IGNORE: _NamedIntConstant\nLITERAL_LOC_IGNORE: _NamedIntConstant\nLITERAL_UNI_IGNORE: _NamedIntConstant\nNOT_LITERAL_LOC_IGNORE: _NamedIntConstant\nNOT_LITERAL_UNI_IGNORE: _NamedIntConstant\nMIN_REPEAT: _NamedIntConstant\nMAX_REPEAT: _NamedIntConstant\n\n# from ATCODES\nAT_BEGINNING: _NamedIntConstant\nAT_BEGINNING_LINE: _NamedIntConstant\nAT_BEGINNING_STRING: _NamedIntConstant\nAT_BOUNDARY: _NamedIntConstant\nAT_NON_BOUNDARY: _NamedIntConstant\nAT_END: _NamedIntConstant\nAT_END_LINE: _NamedIntConstant\nAT_END_STRING: _NamedIntConstant\nAT_LOC_BOUNDARY: _NamedIntConstant\nAT_LOC_NON_BOUNDARY: _NamedIntConstant\nAT_UNI_BOUNDARY: _NamedIntConstant\nAT_UNI_NON_BOUNDARY: _NamedIntConstant\n\n# from CHCODES\nCATEGORY_DIGIT: _NamedIntConstant\nCATEGORY_NOT_DIGIT: _NamedIntConstant\nCATEGORY_SPACE: _NamedIntConstant\nCATEGORY_NOT_SPACE: _NamedIntConstant\nCATEGORY_WORD: _NamedIntConstant\nCATEGORY_NOT_WORD: _NamedIntConstant\nCATEGORY_LINEBREAK: _NamedIntConstant\nCATEGORY_NOT_LINEBREAK: _NamedIntConstant\nCATEGORY_LOC_WORD: _NamedIntConstant\nCATEGORY_LOC_NOT_WORD: _NamedIntConstant\nCATEGORY_UNI_DIGIT: _NamedIntConstant\nCATEGORY_UNI_NOT_DIGIT: _NamedIntConstant\nCATEGORY_UNI_SPACE: _NamedIntConstant\nCATEGORY_UNI_NOT_SPACE: _NamedIntConstant\nCATEGORY_UNI_WORD: _NamedIntConstant\nCATEGORY_UNI_NOT_WORD: _NamedIntConstant\nCATEGORY_UNI_LINEBREAK: _NamedIntConstant\nCATEGORY_UNI_NOT_LINEBREAK: _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, overload\nfrom typing_extensions import TypeAlias\n\nSPECIAL_CHARS: str\nREPEAT_CHARS: str\nDIGITS: frozenset[str]\nOCTDIGITS: frozenset[str]\nHEXDIGITS: frozenset[str]\nASCIILETTERS: frozenset[str]\nWHITESPACE: frozenset[str]\nESCAPES: dict[str, tuple[_NIC, int]]\nCATEGORIES: dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]]\nFLAGS: dict[str, int]\nTYPE_FLAGS: int\nGLOBAL_FLAGS: int\n\nif sys.version_info >= (3, 11):\n    MAXWIDTH: 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 = ...) -> 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, Literal, NamedTuple, TypedDict, overload, type_check_only\nfrom typing_extensions import Never, Self, TypeAlias\n\nif sys.version_info >= (3, 13):\n    from _ssl import HAS_PSK as HAS_PSK\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\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\nif sys.version_info < (3, 12):\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 = ...,\n        ssl_version: int = ...,\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\ndef 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\nif sys.version_info >= (3, 10):\n    def _create_unverified_context(\n        protocol: int | None = None,\n        *,\n        cert_reqs: int = ...,\n        check_hostname: bool = False,\n        purpose: Purpose = ...,\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 = ...,\n        check_hostname: bool = False,\n        purpose: Purpose = ...,\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: Callable[..., SSLContext]\n\nif sys.version_info < (3, 12):\n    def match_hostname(cert: _PeerCertRetDictType, hostname: str) -> None: ...\n\ndef cert_time_to_seconds(cert_time: str) -> int: ...\n\nif sys.version_info >= (3, 10):\n    def get_server_certificate(\n        addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = None, timeout: float = ...\n    ) -> str: ...\n\nelse:\n    def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = None) -> str: ...\n\ndef DER_cert_to_PEM_cert(der_cert_bytes: ReadableBuffer) -> str: ...\ndef PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ...\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: VerifyMode\nCERT_OPTIONAL: VerifyMode\nCERT_REQUIRED: VerifyMode\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: VerifyFlags\nVERIFY_CRL_CHECK_LEAF: VerifyFlags\nVERIFY_CRL_CHECK_CHAIN: VerifyFlags\nVERIFY_X509_STRICT: VerifyFlags\nVERIFY_X509_TRUSTED_FIRST: VerifyFlags\n\nif sys.version_info >= (3, 10):\n    VERIFY_ALLOW_PROXY_CERTS: VerifyFlags\n    VERIFY_X509_PARTIAL_CHAIN: VerifyFlags\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: _SSLMethod\nPROTOCOL_SSLv2: _SSLMethod\nPROTOCOL_SSLv3: _SSLMethod\nPROTOCOL_TLSv1: _SSLMethod\nPROTOCOL_TLSv1_1: _SSLMethod\nPROTOCOL_TLSv1_2: _SSLMethod\nPROTOCOL_TLS: _SSLMethod\nPROTOCOL_TLS_CLIENT: _SSLMethod\nPROTOCOL_TLS_SERVER: _SSLMethod\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: Options\nOP_NO_SSLv2: Options\nOP_NO_SSLv3: Options\nOP_NO_TLSv1: Options\nOP_NO_TLSv1_1: Options\nOP_NO_TLSv1_2: Options\nOP_NO_TLSv1_3: Options\nOP_CIPHER_SERVER_PREFERENCE: Options\nOP_SINGLE_DH_USE: Options\nOP_SINGLE_ECDH_USE: Options\nOP_NO_COMPRESSION: Options\nOP_NO_TICKET: Options\nOP_NO_RENEGOTIATION: Options\nOP_ENABLE_MIDDLEBOX_COMPAT: Options\nif sys.version_info >= (3, 12):\n    OP_LEGACY_SERVER_CONNECT: Options\n    OP_ENABLE_KTLS: Options\nif sys.version_info >= (3, 11) or sys.platform == \"linux\":\n    OP_IGNORE_UNEXPECTED_EOF: Options\n\nHAS_NEVER_CHECK_COMMON_NAME: bool\n\nCHANNEL_BINDING_TYPES: 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: AlertDescription\nALERT_DESCRIPTION_INTERNAL_ERROR: AlertDescription\nALERT_DESCRIPTION_ACCESS_DENIED: AlertDescription\nALERT_DESCRIPTION_BAD_CERTIFICATE: AlertDescription\nALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: AlertDescription\nALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: AlertDescription\nALERT_DESCRIPTION_BAD_RECORD_MAC: AlertDescription\nALERT_DESCRIPTION_CERTIFICATE_EXPIRED: AlertDescription\nALERT_DESCRIPTION_CERTIFICATE_REVOKED: AlertDescription\nALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: AlertDescription\nALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: AlertDescription\nALERT_DESCRIPTION_CLOSE_NOTIFY: AlertDescription\nALERT_DESCRIPTION_DECODE_ERROR: AlertDescription\nALERT_DESCRIPTION_DECOMPRESSION_FAILURE: AlertDescription\nALERT_DESCRIPTION_DECRYPT_ERROR: AlertDescription\nALERT_DESCRIPTION_ILLEGAL_PARAMETER: AlertDescription\nALERT_DESCRIPTION_INSUFFICIENT_SECURITY: AlertDescription\nALERT_DESCRIPTION_NO_RENEGOTIATION: AlertDescription\nALERT_DESCRIPTION_PROTOCOL_VERSION: AlertDescription\nALERT_DESCRIPTION_RECORD_OVERFLOW: AlertDescription\nALERT_DESCRIPTION_UNEXPECTED_MESSAGE: AlertDescription\nALERT_DESCRIPTION_UNKNOWN_CA: AlertDescription\nALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: AlertDescription\nALERT_DESCRIPTION_UNRECOGNIZED_NAME: AlertDescription\nALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: AlertDescription\nALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: AlertDescription\nALERT_DESCRIPTION_USER_CANCELLED: AlertDescription\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    def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: ...\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    def selected_npn_protocol(self) -> str | None: ...\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\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        # Using the default (None) for the `protocol` parameter is deprecated,\n        # but there isn't a good way of marking that in the stub unless/until PEP 702 is accepted\n        def __new__(cls, protocol: int | 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 = ...) -> 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    def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ...\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\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    def selected_npn_protocol(self) -> str | None: ...\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: SSLErrorNumber  # undocumented\nSSL_ERROR_INVALID_ERROR_CODE: SSLErrorNumber  # undocumented\nSSL_ERROR_SSL: SSLErrorNumber  # undocumented\nSSL_ERROR_SYSCALL: SSLErrorNumber  # undocumented\nSSL_ERROR_WANT_CONNECT: SSLErrorNumber  # undocumented\nSSL_ERROR_WANT_READ: SSLErrorNumber  # undocumented\nSSL_ERROR_WANT_WRITE: SSLErrorNumber  # undocumented\nSSL_ERROR_WANT_X509_LOOKUP: SSLErrorNumber  # undocumented\nSSL_ERROR_ZERO_RETURN: SSLErrorNumber  # undocumented\n\ndef get_protocol_name(protocol_code: int) -> str: ...\n\nif sys.version_info < (3, 9):\n    AF_INET: int\nPEM_FOOTER: str\nPEM_HEADER: str\nSOCK_STREAM: int\nSOL_SOCKET: int\nSO_TYPE: int\n"
  },
  {
    "path": "mypy/typeshed/stdlib/stat.pyi",
    "content": "import sys\nfrom _stat import *\nfrom typing import Final\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\nfrom decimal import Decimal\nfrom fractions import Fraction\nfrom typing import Any, Literal, NamedTuple, SupportsFloat, 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\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    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: int, *, seed: Any | 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    if sys.version_info >= (3, 9):\n        def zscore(self, x: float) -> float: ...\n\n    def __eq__(self, x2: object) -> bool: ...\n    def __add__(self, x2: float | NormalDist) -> NormalDist: ...\n    def __sub__(self, x2: float | NormalDist) -> NormalDist: ...\n    def __mul__(self, x2: float) -> NormalDist: ...\n    def __truediv__(self, x2: float) -> NormalDist: ...\n    def __pos__(self) -> NormalDist: ...\n    def __neg__(self) -> NormalDist: ...\n    __radd__ = __add__\n    def __rsub__(self, 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: Sequence[_Number], dependent_variable: Sequence[_Number], /, *, proportional: bool = False\n    ) -> LinearRegression: ...\n\nelif sys.version_info >= (3, 10):\n    def linear_regression(regressor: Sequence[_Number], dependent_variable: Sequence[_Number], /) -> 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],\n        h: float,\n        kernel: _Kernel = \"normal\",\n        *,\n        seed: int | float | str | bytes | bytearray | None = None,  # noqa: Y041\n    ) -> Callable[[], float]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/string.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, overload\nfrom typing_extensions import LiteralString, TypeAlias\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\nascii_letters: LiteralString\nascii_lowercase: LiteralString\nascii_uppercase: LiteralString\ndigits: LiteralString\nhexdigits: LiteralString\noctdigits: LiteralString\npunctuation: LiteralString\nprintable: LiteralString\nwhitespace: LiteralString\n\ndef capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLiteralStr: ...\n\nif sys.version_info >= (3, 9):\n    _TemplateMetaclass: TypeAlias = type\nelse:\n    class _TemplateMetaclass(type):\n        pattern: ClassVar[str]\n        def __init__(cls, name: str, bases: tuple[type, ...], dct: dict[str, Any]) -> None: ...\n\nclass Template(metaclass=_TemplateMetaclass):\n    template: str\n    delimiter: ClassVar[str]\n    idpattern: ClassVar[str]\n    braceidpattern: ClassVar[str | None]\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/stringprep.pyi",
    "content": "b1_set: set[int]\nb3_exceptions: dict[int, str]\nc22_specials: set[int]\nc6_set: set[int]\nc7_set: set[int]\nc8_set: set[int]\nc9_set: 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 TracebackType\nfrom typing import IO, Any, AnyStr, Final, Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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    if sys.version_info >= (3, 9):\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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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\nelif sys.version_info >= (3, 9):\n    # 3.9 adds arguments \"user\", \"group\", \"extra_groups\" and \"umask\"\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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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\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[[], Any] | 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    ) -> 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[[], Any] | 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    ) -> 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[[], Any] | 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    ) -> 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[[], Any] | 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    ) -> 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[[], Any] | 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    ) -> 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[[], Any] | 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    ) -> 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[[], Any] | 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[[], Any] | 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\nelif sys.version_info >= (3, 9):\n    # 3.9 adds arguments \"user\", \"group\", \"extra_groups\" and \"umask\"\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[[], Any] | 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\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[[], Any] | 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    ) -> 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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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\nelif sys.version_info >= (3, 9):\n    # 3.9 adds arguments \"user\", \"group\", \"extra_groups\" and \"umask\"\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[[], Any] | 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 = ...,\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\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[[], Any] | 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 = ...,\n        *,\n        encoding: str | None = None,\n        text: bool | None = None,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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\nelif sys.version_info >= (3, 9):\n    # 3.9 adds arguments \"user\", \"group\", \"extra_groups\" and \"umask\"\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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[[], Any] | 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 = ...,\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\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[[], Any] | 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 = ...,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: Literal[True],\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[[], Any] | 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 = ...,\n        encoding: str,\n        errors: str | None = None,\n        text: bool | 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[[], Any] | 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 = ...,\n        encoding: str | None = None,\n        errors: str,\n        text: bool | 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[[], Any] | 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 = ...,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | 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[[], Any] | 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 = ...,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | 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[[], Any] | 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 = ...,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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    elif sys.version_info >= (3, 9):\n        # user, group, extra_groups, umask were added in 3.9\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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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[[], Any] | 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    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[[], Any] | 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        ) -> 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[[], Any] | 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        ) -> 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[[], Any] | 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        ) -> 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[[], Any] | 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        ) -> 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[[], Any] | 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        ) -> 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[[], Any] | 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        ) -> 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    if sys.version_info >= (3, 9):\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": "import sys\nfrom _typeshed import Unused\nfrom typing import IO, Any, 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: int\nAUDIO_FILE_ENCODING_MULAW_8: int\nAUDIO_FILE_ENCODING_LINEAR_8: int\nAUDIO_FILE_ENCODING_LINEAR_16: int\nAUDIO_FILE_ENCODING_LINEAR_24: int\nAUDIO_FILE_ENCODING_LINEAR_32: int\nAUDIO_FILE_ENCODING_FLOAT: int\nAUDIO_FILE_ENCODING_DOUBLE: int\nAUDIO_FILE_ENCODING_ADPCM_G721: int\nAUDIO_FILE_ENCODING_ADPCM_G722: int\nAUDIO_FILE_ENCODING_ADPCM_G723_3: int\nAUDIO_FILE_ENCODING_ADPCM_G723_5: int\nAUDIO_FILE_ENCODING_ALAW_8: int\nAUDIO_UNKNOWN_SIZE: int\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\nif sys.version_info < (3, 9):\n    openfp = open\n"
  },
  {
    "path": "mypy/typeshed/stdlib/symbol.pyi",
    "content": "single_input: int\nfile_input: int\neval_input: int\ndecorator: int\ndecorators: int\ndecorated: int\nasync_funcdef: int\nfuncdef: int\nparameters: int\ntypedargslist: int\ntfpdef: int\nvarargslist: int\nvfpdef: int\nstmt: int\nsimple_stmt: int\nsmall_stmt: int\nexpr_stmt: int\nannassign: int\ntestlist_star_expr: int\naugassign: int\ndel_stmt: int\npass_stmt: int\nflow_stmt: int\nbreak_stmt: int\ncontinue_stmt: int\nreturn_stmt: int\nyield_stmt: int\nraise_stmt: int\nimport_stmt: int\nimport_name: int\nimport_from: int\nimport_as_name: int\ndotted_as_name: int\nimport_as_names: int\ndotted_as_names: int\ndotted_name: int\nglobal_stmt: int\nnonlocal_stmt: int\nassert_stmt: int\ncompound_stmt: int\nasync_stmt: int\nif_stmt: int\nwhile_stmt: int\nfor_stmt: int\ntry_stmt: int\nwith_stmt: int\nwith_item: int\nexcept_clause: int\nsuite: int\ntest: int\ntest_nocond: int\nlambdef: int\nlambdef_nocond: int\nor_test: int\nand_test: int\nnot_test: int\ncomparison: int\ncomp_op: int\nstar_expr: int\nexpr: int\nxor_expr: int\nand_expr: int\nshift_expr: int\narith_expr: int\nterm: int\nfactor: int\npower: int\natom_expr: int\natom: int\ntestlist_comp: int\ntrailer: int\nsubscriptlist: int\nsubscript: int\nsliceop: int\nexprlist: int\ntestlist: int\ndictorsetmaker: int\nclassdef: int\narglist: int\nargument: int\ncomp_iter: int\ncomp_for: int\ncomp_if: int\nencoding_decl: int\nyield_expr: int\nyield_arg: int\nsync_comp_for: int\nfunc_body_suite: int\nfunc_type: int\nfunc_type_input: int\nnamedexpr_test: int\ntypelist: int\nsym_name: 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    if sys.version_info < (3, 9):\n        def has_exec(self) -> bool: ...\n\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, 16):\n        @deprecated(\"deprecated in Python 3.14, will be removed in Python 3.16\")\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, 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, type_check_only\nfrom typing_extensions import LiteralString, TypeAlias\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\nif sys.version_info >= (3, 9):\n    platlibdir: 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.8 and 3.9 are 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    # 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.8.14, 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: ...\ndef _clear_type_cache() -> None: ...\ndef _current_frames() -> dict[int, FrameType]: ...\ndef _getframe(depth: int = 0, /) -> FrameType: ...\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: ...\ndef getallocatedblocks() -> int: ...\ndef getdefaultencoding() -> str: ...\n\nif sys.platform != \"win32\":\n    def getdlopenflags() -> int: ...\n\ndef getfilesystemencoding() -> str: ...\ndef getfilesystemencodeerrors() -> str: ...\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    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\ndef intern(string: str, /) -> str: ...\n\nif sys.version_info >= (3, 13):\n    def _is_gil_enabled() -> 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\nif sys.version_info < (3, 9):\n    def getcheckinterval() -> int: ...  # deprecated\n    def setcheckinterval(n: int, /) -> None: ...  # deprecated\n\nif sys.version_info < (3, 9):\n    # An 11-tuple or None\n    def callstats() -> tuple[int, int, int, int, int, int, int, int, int, int, int] | None: ...\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    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, 3.9.14, and 3.8.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"
  },
  {
    "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\nfrom collections.abc import Callable\nfrom types import CodeType\nfrom typing import Any\n\nDEBUGGER_ID: int\nCOVERAGE_ID: int\nPROFILER_ID: int\nOPTIMIZER_ID: int\n\ndef use_tool_id(tool_id: int, name: str, /) -> None: ...\ndef free_tool_id(tool_id: int, /) -> None: ...\ndef get_tool(tool_id: int, /) -> str | None: ...\n\nevents: _events\n\nclass _events:\n    BRANCH: int\n    CALL: int\n    C_RAISE: int\n    C_RETURN: int\n    EXCEPTION_HANDLED: int\n    INSTRUCTION: int\n    JUMP: int\n    LINE: int\n    NO_EVENTS: int\n    PY_RESUME: int\n    PY_RETURN: int\n    PY_START: int\n    PY_THROW: int\n    PY_UNWIND: int\n    PY_YIELD: int\n    RAISE: int\n    RERAISE: int\n    STOP_ITERATION: 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, /) -> int: ...\ndef restart_events() -> None: ...\n\nDISABLE: object\nMISSING: object\n\ndef register_callback(tool_id: int, event: int, func: Callable[..., Any] | 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 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() -> str: ...\n    def get_preferred_scheme(key: Literal[\"prefix\", \"home\", \"user\"]) -> str: ...\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, 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 = ..., 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, Literal, Protocol, overload\nfrom typing_extensions import Self, TypeAlias\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    ]\n\n_FilterFunction: TypeAlias = Callable[[TarInfo, str], TarInfo | None]\n_TarfileFilter: TypeAlias = Literal[\"fully_trusted\", \"tar\", \"data\"] | _FilterFunction\n\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\nclass _Bz2ReadableFileobj(bz2._ReadableFileobj):\n    def close(self) -> object: ...\n\nclass _Bz2WritableFileobj(bz2._WritableFileobj):\n    def close(self) -> object: ...\n\n# tar constants\nNUL: bytes\nBLOCKSIZE: int\nRECORDSIZE: int\nGNU_MAGIC: bytes\nPOSIX_MAGIC: bytes\n\nLENGTH_NAME: int\nLENGTH_LINK: int\nLENGTH_PREFIX: int\n\nREGTYPE: bytes\nAREGTYPE: bytes\nLNKTYPE: bytes\nSYMTYPE: bytes\nCONTTYPE: bytes\nBLKTYPE: bytes\nDIRTYPE: bytes\nFIFOTYPE: bytes\nCHRTYPE: bytes\n\nGNUTYPE_LONGNAME: bytes\nGNUTYPE_LONGLINK: bytes\nGNUTYPE_SPARSE: bytes\n\nXHDTYPE: bytes\nXGLTYPE: bytes\nSOLARIS_XHDTYPE: bytes\n\nUSTAR_FORMAT: int\nGNU_FORMAT: int\nPAX_FORMAT: int\nDEFAULT_FORMAT: int\n\n# tarfile constants\n\nSUPPORTED_TYPES: tuple[bytes, ...]\nREGULAR_TYPES: tuple[bytes, ...]\nGNU_TYPES: tuple[bytes, ...]\nPAX_FIELDS: tuple[str, ...]\nPAX_NUMBER_FIELDS: dict[str, type]\nPAX_NAME_FIELDS: set[str]\n\nENCODING: str\n\n@overload\ndef open(\n    name: StrOrBytesPath | None = None,\n    mode: Literal[\"r\", \"r:*\", \"r:\", \"r:gz\", \"r:bz2\", \"r:xz\"] = \"r\",\n    fileobj: IO[bytes] | 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) -> TarFile: ...\n@overload\ndef open(\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) -> TarFile: ...\n@overload\ndef open(\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) -> TarFile: ...\n@overload\ndef open(\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) -> TarFile: ...\n@overload\ndef open(\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) -> TarFile: ...\n@overload\ndef open(\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) -> TarFile: ...\n@overload\ndef open(\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) -> TarFile: ...\n@overload\ndef open(\n    name: StrOrBytesPath | ReadableBuffer | None = None,\n    *,\n    mode: Literal[\"r|*\", \"r|\", \"r|gz\", \"r|bz2\", \"r|xz\"],\n    fileobj: IO[bytes] | 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: int | None = ...,\n) -> TarFile: ...\n@overload\ndef open(\n    name: StrOrBytesPath | WriteableBuffer | None = None,\n    *,\n    mode: Literal[\"w|\", \"w|gz\", \"w|bz2\", \"w|xz\"],\n    fileobj: IO[bytes] | 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: int | None = ...,\n) -> TarFile: ...\n\nclass ExFileObject(io.BufferedReader):\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 | None\n    format: int | None\n    tarinfo: type[TarInfo]\n    dereference: bool | None\n    ignore_zeros: bool | None\n    encoding: str | None\n    errors: str\n    fileobject: type[ExFileObject]\n    pax_headers: Mapping[str, str] | None\n    debug: int | None\n    errorlevel: int | None\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    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None = None,\n        mode: str = \"r\",\n        fileobj: IO[bytes] | None = None,  # depends on mode\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    @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    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: _list[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 = ...,\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 = ...,\n    ) -> None: ...\n    def _extract_member(\n        self, tarinfo: TarInfo, targetpath: str, set_attrs: bool = True, numeric_owner: bool = False\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 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\nif sys.version_info >= (3, 9):\n    def is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: ...\n\nelse:\n    def is_tarfile(name: StrOrBytesPath) -> 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\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    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    tarfile: TarFile | None\n    mode: int\n    type: bytes\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    @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: int | 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\nfrom typing_extensions import Self\n\n__all__ = [\"Telnet\"]\n\nDEBUGLEVEL: int\nTELNET_PORT: int\n\nIAC: bytes\nDONT: bytes\nDO: bytes\nWONT: bytes\nWILL: bytes\ntheNULL: bytes\n\nSE: bytes\nNOP: bytes\nDM: bytes\nBRK: bytes\nIP: bytes\nAO: bytes\nAYT: bytes\nEC: bytes\nEL: bytes\nGA: bytes\nSB: bytes\n\nBINARY: bytes\nECHO: bytes\nRCP: bytes\nSGA: bytes\nNAMS: bytes\nSTATUS: bytes\nTM: bytes\nRCTE: bytes\nNAOL: bytes\nNAOP: bytes\nNAOCRD: bytes\nNAOHTS: bytes\nNAOHTD: bytes\nNAOFFD: bytes\nNAOVTS: bytes\nNAOVTD: bytes\nNAOLFD: bytes\nXASCII: bytes\nLOGOUT: bytes\nBM: bytes\nDET: bytes\nSUPDUP: bytes\nSUPDUPOUTPUT: bytes\nSNDLOC: bytes\nTTYPE: bytes\nEOR: bytes\nTUID: bytes\nOUTMRK: bytes\nTTYLOC: bytes\nVT3270REGIME: bytes\nX3PAD: bytes\nNAWS: bytes\nTSPEED: bytes\nLFLOW: bytes\nLINEMODE: bytes\nXDISPLOC: bytes\nOLD_ENVIRON: bytes\nAUTHENTICATION: bytes\nENCRYPT: bytes\nNEW_ENVIRON: bytes\n\nTN3270E: bytes\nXAUTH: bytes\nCHARSET: bytes\nRSP: bytes\nCOM_PORT_OPTION: bytes\nSUPPRESS_LOCAL_ECHO: bytes\nTLS: bytes\nKERMIT: bytes\nSEND_URL: bytes\nFORWARD_X: bytes\nPRAGMA_LOGON: bytes\nSSPI_LOGON: bytes\nPRAGMA_HEARTBEAT: bytes\nEXOPL: bytes\nNOOPT: bytes\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 TracebackType\nfrom typing import IO, Any, AnyStr, Generic, Literal, overload\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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: 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\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    if sys.version_info >= (3, 9):\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    if sys.version_info >= (3, 9):\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: ...\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\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    B0: int\n    B110: int\n    B115200: int\n    B1200: int\n    B134: int\n    B150: int\n    B1800: int\n    B19200: int\n    B200: int\n    B230400: int\n    B2400: int\n    B300: int\n    B38400: int\n    B4800: int\n    B50: int\n    B57600: int\n    B600: int\n    B75: int\n    B9600: int\n    BRKINT: int\n    BS0: int\n    BS1: int\n    BSDLY: int\n    CDSUSP: int\n    CEOF: int\n    CEOL: int\n    CEOT: int\n    CERASE: int\n    CFLUSH: int\n    CINTR: int\n    CKILL: int\n    CLNEXT: int\n    CLOCAL: int\n    CQUIT: int\n    CR0: int\n    CR1: int\n    CR2: int\n    CR3: int\n    CRDLY: int\n    CREAD: int\n    CRPRNT: int\n    CRTSCTS: int\n    CS5: int\n    CS6: int\n    CS7: int\n    CS8: int\n    CSIZE: int\n    CSTART: int\n    CSTOP: int\n    CSTOPB: int\n    CSUSP: int\n    CWERASE: int\n    ECHO: int\n    ECHOCTL: int\n    ECHOE: int\n    ECHOK: int\n    ECHOKE: int\n    ECHONL: int\n    ECHOPRT: int\n    EXTA: int\n    EXTB: int\n    FF0: int\n    FF1: int\n    FFDLY: int\n    FIOASYNC: int\n    FIOCLEX: int\n    FIONBIO: int\n    FIONCLEX: int\n    FIONREAD: int\n    FLUSHO: int\n    HUPCL: int\n    ICANON: int\n    ICRNL: int\n    IEXTEN: int\n    IGNBRK: int\n    IGNCR: int\n    IGNPAR: int\n    IMAXBEL: int\n    INLCR: int\n    INPCK: int\n    ISIG: int\n    ISTRIP: int\n    IXANY: int\n    IXOFF: int\n    IXON: int\n    NCCS: int\n    NL0: int\n    NL1: int\n    NLDLY: int\n    NOFLSH: int\n    OCRNL: int\n    OFDEL: int\n    OFILL: int\n    ONLCR: int\n    ONLRET: int\n    ONOCR: int\n    OPOST: int\n    PARENB: int\n    PARMRK: int\n    PARODD: int\n    PENDIN: int\n    TAB0: int\n    TAB1: int\n    TAB2: int\n    TAB3: int\n    TABDLY: int\n    TCIFLUSH: int\n    TCIOFF: int\n    TCIOFLUSH: int\n    TCION: int\n    TCOFLUSH: int\n    TCOOFF: int\n    TCOON: int\n    TCSADRAIN: int\n    TCSAFLUSH: int\n    TCSANOW: int\n    TIOCCONS: int\n    TIOCEXCL: int\n    TIOCGETD: int\n    TIOCGPGRP: int\n    TIOCGWINSZ: int\n    TIOCM_CAR: int\n    TIOCM_CD: int\n    TIOCM_CTS: int\n    TIOCM_DSR: int\n    TIOCM_DTR: int\n    TIOCM_LE: int\n    TIOCM_RI: int\n    TIOCM_RNG: int\n    TIOCM_RTS: int\n    TIOCM_SR: int\n    TIOCM_ST: int\n    TIOCMBIC: int\n    TIOCMBIS: int\n    TIOCMGET: int\n    TIOCMSET: int\n    TIOCNOTTY: int\n    TIOCNXCL: int\n    TIOCOUTQ: int\n    TIOCPKT_DATA: int\n    TIOCPKT_DOSTOP: int\n    TIOCPKT_FLUSHREAD: int\n    TIOCPKT_FLUSHWRITE: int\n    TIOCPKT_NOSTOP: int\n    TIOCPKT_START: int\n    TIOCPKT_STOP: int\n    TIOCPKT: int\n    TIOCSCTTY: int\n    TIOCSETD: int\n    TIOCSPGRP: int\n    TIOCSTI: int\n    TIOCSWINSZ: int\n    TOSTOP: int\n    VDISCARD: int\n    VEOF: int\n    VEOL: int\n    VEOL2: int\n    VERASE: int\n    VINTR: int\n    VKILL: int\n    VLNEXT: int\n    VMIN: int\n    VQUIT: int\n    VREPRINT: int\n    VSTART: int\n    VSTOP: int\n    VSUSP: int\n    VT0: int\n    VT1: int\n    VTDLY: int\n    VTIME: int\n    VWERASE: int\n\n    if sys.version_info >= (3, 13):\n        EXTPROC: int\n        IUTF8: int\n\n    if sys.platform == \"darwin\" and sys.version_info >= (3, 13):\n        ALTWERASE: int\n        B14400: int\n        B28800: int\n        B7200: int\n        B76800: int\n        CCAR_OFLOW: int\n        CCTS_OFLOW: int\n        CDSR_OFLOW: int\n        CDTR_IFLOW: int\n        CIGNORE: int\n        CRTS_IFLOW: int\n        MDMBUF: int\n        NL2: int\n        NL3: int\n        NOKERNINFO: int\n        ONOEOT: int\n        OXTABS: int\n        VDSUSP: int\n        VSTATUS: int\n\n    if sys.platform == \"darwin\" and sys.version_info >= (3, 11):\n        TIOCGSIZE: int\n        TIOCSSIZE: int\n\n    if sys.platform == \"linux\":\n        B1152000: int\n        B576000: int\n        CBAUD: int\n        CBAUDEX: int\n        CIBAUD: int\n        IOCSIZE_MASK: int\n        IOCSIZE_SHIFT: int\n        IUCLC: int\n        N_MOUSE: int\n        N_PPP: int\n        N_SLIP: int\n        N_STRIP: int\n        N_TTY: int\n        NCC: int\n        OLCUC: int\n        TCFLSH: int\n        TCGETA: int\n        TCGETS: int\n        TCSBRK: int\n        TCSBRKP: int\n        TCSETA: int\n        TCSETAF: int\n        TCSETAW: int\n        TCSETS: int\n        TCSETSF: int\n        TCSETSW: int\n        TCXONC: int\n        TIOCGICOUNT: int\n        TIOCGLCKTRMIOS: int\n        TIOCGSERIAL: int\n        TIOCGSOFTCAR: int\n        TIOCINQ: int\n        TIOCLINUX: int\n        TIOCMIWAIT: int\n        TIOCTTYGSTRUCT: int\n        TIOCSER_TEMT: int\n        TIOCSERCONFIG: int\n        TIOCSERGETLSR: int\n        TIOCSERGETMULTI: int\n        TIOCSERGSTRUCT: int\n        TIOCSERGWILD: int\n        TIOCSERSETMULTI: int\n        TIOCSERSWILD: int\n        TIOCSLCKTRMIOS: int\n        TIOCSSERIAL: int\n        TIOCSSOFTCAR: int\n        VSWTC: int\n        VSWTCH: int\n        XCASE: int\n        XTABS: int\n\n    if sys.platform != \"darwin\":\n        B1000000: int\n        B1500000: int\n        B2000000: int\n        B2500000: int\n        B3000000: int\n        B3500000: int\n        B4000000: int\n        B460800: int\n        B500000: int\n        B921600: int\n\n    if sys.platform != \"linux\":\n        TCSASOFT: int\n\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        # not available on FreeBSD either.\n        CDEL: int\n        CEOL2: int\n        CESC: int\n        CNUL: int\n        COMMON: int\n        CSWTCH: int\n        IBSHIFT: int\n        INIT_C_CC: int\n        NSWTCH: 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 _excepthook, _ExceptHookArgs, get_native_id as get_native_id\nfrom _typeshed import ProfileFunction, TraceFunction\nfrom collections.abc import Callable, Iterable, Mapping\nfrom types import TracebackType\nfrom typing import Any, TypeVar, final\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: ...\ndef activeCount() -> int: ...  # deprecated alias for active_count()\ndef current_thread() -> Thread: ...\ndef currentThread() -> Thread: ...  # deprecated alias for current_thread()\ndef get_ident() -> int: ...\ndef enumerate() -> list[Thread]: ...\ndef main_thread() -> Thread: ...\ndef settrace(func: TraceFunction) -> 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: ...\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: 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    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    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    if sys.version_info < (3, 9):\n        def isAlive(self) -> bool: ...\n    # the following methods are all deprecated\n    def getName(self) -> str: ...\n    def setName(self, name: str) -> None: ...\n    def isDaemon(self) -> bool: ...\n    def setDaemon(self, daemonic: bool) -> 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\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 = ..., timeout: float = ...) -> bool: ...\n    def release(self) -> None: ...\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    def notifyAll(self) -> None: ...  # deprecated alias for notify_all()\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    if sys.version_info >= (3, 9):\n        def release(self, n: int = 1) -> None: ...\n    else:\n        def release(self) -> None: ...\n\nclass BoundedSemaphore(Semaphore): ...\n\nclass Event:\n    def is_set(self) -> bool: ...\n    def isSet(self) -> bool: ...  # deprecated alias for is_set()\n    def set(self) -> None: ...\n    def clear(self) -> None: ...\n    def wait(self, timeout: float | None = None) -> bool: ...\n\nexcepthook = _excepthook\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, final\nfrom typing_extensions import TypeAlias\n\n_TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int]\n\naltzone: int\ndaylight: int\ntimezone: int\ntzname: tuple[str, str]\n\nif sys.platform == \"linux\":\n    CLOCK_BOOTTIME: int\nif sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    CLOCK_PROF: int  # FreeBSD, NetBSD, OpenBSD\n    CLOCK_UPTIME: int  # FreeBSD, OpenBSD\n\nif sys.platform != \"win32\":\n    CLOCK_MONOTONIC: int\n    CLOCK_MONOTONIC_RAW: int\n    CLOCK_PROCESS_CPUTIME_ID: int\n    CLOCK_REALTIME: int\n    CLOCK_THREAD_CPUTIME_ID: int\n    if sys.platform != \"linux\" and sys.platform != \"darwin\":\n        CLOCK_HIGHRES: int  # Solaris only\n\nif sys.platform == \"darwin\":\n    CLOCK_UPTIME_RAW: int\n    if sys.version_info >= (3, 13):\n        CLOCK_UPTIME_RAW_APPROX: int\n        CLOCK_MONOTONIC_RAW_APPROX: int\n\nif sys.version_info >= (3, 9) and sys.platform == \"linux\":\n    CLOCK_TAI: 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: float | None = None, /) -> str: ...\ndef gmtime(seconds: float | None = None, /) -> struct_time: ...\ndef localtime(seconds: float | None = None, /) -> struct_time: ...\ndef mktime(time_tuple: _TimeTuple | struct_time, /) -> float: ...\ndef sleep(seconds: float, /) -> 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\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": "from 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, stmt: _Stmt = \"pass\", setup: _Stmt = \"pass\", timer: _Timer = ..., 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\", setup: _Stmt = \"pass\", timer: _Timer = ..., number: int = 1000000, globals: dict[str, Any] | None = None\n) -> float: ...\ndef repeat(\n    stmt: _Stmt = \"pass\",\n    setup: _Stmt = \"pass\",\n    timer: _Timer = ...,\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 Incomplete, MaybeNone, StrOrBytesPath\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom tkinter.constants import *\nfrom tkinter.font import _FontDescription\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Generic, Literal, NamedTuple, Protocol, TypedDict, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias, TypeVarTuple, Unpack, deprecated\n\nif sys.version_info >= (3, 11):\n    from enum import StrEnum\nelse:\n    from enum import Enum\n\nif sys.version_info >= (3, 9):\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: float\nTclVersion: float\nREADABLE = _tkinter.READABLE\nWRITABLE = _tkinter.WRITABLE\nEXCEPTION = _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# Some widgets have an option named -compound that accepts different values\n# than the _Compound defined here. Many other options have similar things.\n_Anchor: TypeAlias = Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"]  # manual page: Tk_GetAnchor\n_ButtonCommand: TypeAlias = str | Callable[[], Any]  # accepts string of tcl code, return value is returned from Button.invoke()\n_Compound: TypeAlias = Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"]  # -compound in manual page named 'options'\n# manual page: Tk_GetCursor\n_Cursor: TypeAlias = str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str]\n# example when it's sequence:  entry['invalidcommand'] = [entry.register(print), '%P']\n_EntryValidateCommand: TypeAlias = str | list[str] | tuple[str, ...] | Callable[[], bool]\n_ImageSpec: TypeAlias = _Image | str  # str can be from e.g. tkinter.image_names()\n_Relief: TypeAlias = Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"]  # manual page: Tk_GetRelief\n_ScreenUnits: TypeAlias = str | float  # Often the right type instead of int. Manual page: Tk_GetPixels\n# -xscrollcommand and -yscrollcommand in 'options' manual page\n_XYScrollCommand: TypeAlias = str | Callable[[float, float], object]\n_TakeFocusValue: TypeAlias = bool | Literal[0, 1, \"\"] | Callable[[str], bool | None]  # -takefocus in manual page named 'options'\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    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 = \"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\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)\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\ndef NoDefaultRoot() -> None: ...\n\nclass Variable:\n    def __init__(self, master: Misc | None = None, value: Incomplete | None = 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    @deprecated(\"use trace_add() instead of trace()\")\n    def trace(self, mode, callback): ...\n    @deprecated(\"use trace_add() instead of trace_variable()\")\n    def trace_variable(self, mode, callback): ...\n    @deprecated(\"use trace_remove() instead of trace_vdelete()\")\n    def trace_vdelete(self, mode, cbname) -> None: ...\n    @deprecated(\"use trace_info() instead of trace_vinfo()\")\n    def trace_vinfo(self): ...\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: Incomplete\ngetdouble: Incomplete\n\ndef getboolean(s): ...\n\n_Ts = TypeVarTuple(\"_Ts\")\n\nclass _GridIndexInfo(TypedDict, total=False):\n    minsize: _ScreenUnits\n    pad: _ScreenUnits\n    uniform: str | None\n    weight: int\n\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: Incomplete | None = 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): ...\n    def getdouble(self, s): ...\n    def getboolean(self, s): ...\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: Incomplete | None = 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: Incomplete | None = None) -> None: ...\n    def tkraise(self, aboveThis: Incomplete | None = 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]: ...  # Widget because it can't be Toplevel or Tk\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: _ScreenUnits) -> 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: _ScreenUnits) -> 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: _Anchor | 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: _ScreenUnits = ...,\n        pad: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        pad: _ScreenUnits = ...,\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: _ScreenUnits, y: _ScreenUnits) -> 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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        keycode: int = ...,\n        keysym: str = ...,\n        mode: str = ...,\n        override: bool = ...,\n        place: Literal[\"PlaceOnTop\", \"PlaceOnBottom\"] = ...,\n        root: Misc | int = ...,\n        rootx: _ScreenUnits = ...,\n        rooty: _ScreenUnits = ...,\n        sendevent: bool = ...,\n        serial: int = ...,\n        state: int | str = ...,\n        subwindow: Misc | int = ...,\n        time: int = ...,\n        warp: bool = ...,\n        width: _ScreenUnits = ...,\n        when: Literal[\"now\", \"tail\", \"head\", \"mark\"] = ...,\n        x: _ScreenUnits = ...,\n        y: _ScreenUnits = ...,\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): ...\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: _ScreenUnits, what: Literal[\"pixels\"]) -> None: ...\n\nclass YView:\n    @overload\n    def yview(self) -> tuple[float, float]: ...\n    @overload\n    def yview(self, *args): ...\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: _ScreenUnits, 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(\n        self,\n        baseWidth: Incomplete | None = None,\n        baseHeight: Incomplete | None = None,\n        widthInc: Incomplete | None = None,\n        heightInc: Incomplete | None = None,\n    ): ...\n    grid = wm_grid\n    def wm_group(self, pathName: Incomplete | None = None): ...\n    group = wm_group\n    def wm_iconbitmap(self, bitmap: Incomplete | None = None, default: Incomplete | None = None): ...\n    iconbitmap = wm_iconbitmap\n    def wm_iconify(self) -> None: ...\n    iconify = wm_iconify\n    def wm_iconmask(self, bitmap: Incomplete | None = None): ...\n    iconmask = wm_iconmask\n    def wm_iconname(self, newName: Incomplete | None = 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: Incomplete | None = 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    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        menu: Menu = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        takefocus: _TakeFocusValue = ...,\n        width: _ScreenUnits = ...,\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, /): ...\n    def call(self, command: Any, /, *args: Any) -> Any: ...\n    def createcommand(self, name, func, /): ...\n    if sys.platform != \"win32\":\n        def createfilehandler(self, file, mask, func, /): ...\n        def deletefilehandler(self, file, /): ...\n\n    def createtimerhandler(self, milliseconds, func, /): ...\n    def dooneevent(self, flags: int = ..., /): ...\n    def eval(self, script: str, /) -> str: ...\n    def evalfile(self, fileName, /): ...\n    def exprboolean(self, s, /): ...\n    def exprdouble(self, s, /): ...\n    def exprlong(self, s, /): ...\n    def exprstring(self, s, /): ...\n    def globalgetvar(self, *args, **kwargs): ...\n    def globalsetvar(self, *args, **kwargs): ...\n    def globalunsetvar(self, *args, **kwargs): ...\n    def interpaddr(self): ...\n    def loadtk(self) -> None: ...\n    def record(self, script, /): ...\n    if sys.version_info < (3, 11):\n        def split(self, arg, /): ...\n\n    def splitlist(self, arg, /): ...\n    def unsetvar(self, *args, **kwargs): ...\n    def wantobjects(self, *args, **kwargs): ...\n    def willdispatch(self): ...\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\nclass _PackInfo(_InMiscTotal):\n    # 'before' and 'after' never appear in _PackInfo\n    anchor: _Anchor\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 _ScreenUnits\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    # _ScreenUnits 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: _Anchor = ...,\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: _ScreenUnits = ...,\n        ipady: _ScreenUnits = ...,\n        padx: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ...,\n        pady: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ...,\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\nclass _PlaceInfo(_InMiscNonTotal):  # empty dict if widget hasn't been placed\n    anchor: _Anchor\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: _Anchor = ...,\n        bordermode: Literal[\"inside\", \"outside\", \"ignore\"] = ...,\n        width: _ScreenUnits = ...,\n        height: _ScreenUnits = ...,\n        x: _ScreenUnits = ...,\n        y: _ScreenUnits = ...,\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\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: _ScreenUnits = ...,\n        ipady: _ScreenUnits = ...,\n        padx: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ...,\n        pady: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ...,\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: Incomplete\n    def __init__(self, master, widgetName, 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: _ScreenUnits = 0,\n        bg: str = ...,\n        border: _ScreenUnits = 0,\n        borderwidth: _ScreenUnits = 0,\n        class_: str = \"Toplevel\",\n        colormap: Literal[\"new\", \"\"] | Misc = \"\",\n        container: bool = False,\n        cursor: _Cursor = \"\",\n        height: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 0,\n        menu: Menu = ...,\n        name: str = ...,\n        padx: _ScreenUnits = 0,\n        pady: _ScreenUnits = 0,\n        relief: _Relief = \"flat\",\n        screen: str = \"\",  # can't be changed after creating widget\n        takefocus: _TakeFocusValue = 0,\n        use: int = ...,\n        visual: str | tuple[str, int] = \"\",\n        width: _ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        menu: Menu = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        takefocus: _TakeFocusValue = ...,\n        width: _ScreenUnits = ...,\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: _Anchor = \"center\",\n        background: str = ...,\n        bd: _ScreenUnits = ...,  # same as borderwidth\n        bg: str = ...,  # same as background\n        bitmap: str = \"\",\n        border: _ScreenUnits = ...,  # same as borderwidth\n        borderwidth: _ScreenUnits = ...,\n        command: _ButtonCommand = \"\",\n        compound: _Compound = \"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        # ints are also valid _ScreenUnits\n        height: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 1,\n        image: _ImageSpec = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        overrelief: _Relief | Literal[\"\"] = \"\",\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: _TakeFocusValue = \"\",\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: _ScreenUnits = 0,\n        wraplength: _ScreenUnits = 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: _Anchor = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        command: _ButtonCommand = ...,\n        compound: _Compound = ...,\n        cursor: _Cursor = ...,\n        default: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        image: _ImageSpec = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        overrelief: _Relief | Literal[\"\"] = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        underline: int = ...,\n        width: _ScreenUnits = ...,\n        wraplength: _ScreenUnits = ...,\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: _ScreenUnits = 0,\n        bg: str = ...,\n        border: _ScreenUnits = 0,\n        borderwidth: _ScreenUnits = 0,\n        closeenough: float = 1.0,\n        confine: bool = True,\n        cursor: _Cursor = \"\",\n        # canvas manual page has a section named COORDINATES, and the first\n        # part of it describes _ScreenUnits.\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertwidth: _ScreenUnits = 2,\n        name: str = ...,\n        offset=...,  # undocumented\n        relief: _Relief = \"flat\",\n        # Setting scrollregion to None doesn't reset it back to empty,\n        # but setting it to () does.\n        scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = (),\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = 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: _TakeFocusValue = \"\",\n        width: _ScreenUnits = ...,\n        xscrollcommand: _XYScrollCommand = \"\",\n        xscrollincrement: _ScreenUnits = 0,\n        yscrollcommand: _XYScrollCommand = \"\",\n        yscrollincrement: _ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        closeenough: float = ...,\n        confine: bool = ...,\n        cursor: _Cursor = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertwidth: _ScreenUnits = ...,\n        offset=...,  # undocumented\n        relief: _Relief = ...,\n        scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        state: Literal[\"normal\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        width: _ScreenUnits = ...,\n        xscrollcommand: _XYScrollCommand = ...,\n        xscrollincrement: _ScreenUnits = ...,\n        yscrollcommand: _XYScrollCommand = ...,\n        yscrollincrement: _ScreenUnits = ...,\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: _ScreenUnits, y: _ScreenUnits, halo: _ScreenUnits | None = None, start: str | int | None = None\n    ) -> None: ...\n    def addtag_enclosed(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> None: ...\n    def addtag_overlapping(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> 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: _ScreenUnits, y: _ScreenUnits, halo: _ScreenUnits | None = None, start: str | int | None = None\n    ) -> tuple[int, ...]: ...\n    def find_enclosed(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> tuple[int, ...]: ...\n    def find_overlapping(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, 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: Incomplete | None = None): ...\n    def canvasy(self, screeny, gridspacing: Incomplete | None = 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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: _ScreenUnits = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: _ScreenUnits = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: _ScreenUnits = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\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: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: _ScreenUnits = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: _ScreenUnits = ...,\n        fill: str = ...,\n        offset: _ScreenUnits = ...,\n        outline: str = ...,\n        outlineoffset: _ScreenUnits = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _Anchor = ...,\n        angle: float | str = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        fill: str = ...,\n        font: _FontDescription = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offset: _ScreenUnits = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        text: float | str = ...,\n        width: _ScreenUnits = ...,\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: _Anchor = ...,\n        angle: float | str = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        fill: str = ...,\n        font: _FontDescription = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offset: _ScreenUnits = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        text: float | str = ...,\n        width: _ScreenUnits = ...,\n    ) -> int: ...\n    @overload\n    def create_window(\n        self,\n        x: float,\n        y: float,\n        /,\n        *,\n        anchor: _Anchor = ...,\n        height: _ScreenUnits = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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: _Anchor = ...,\n        height: _ScreenUnits = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: _ScreenUnits = ...,\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(\n        self, tagOrId: str | int, xOrigin: _ScreenUnits, yOrigin: _ScreenUnits, xScale: float, yScale: float, /\n    ) -> 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: _Anchor = \"center\",\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        command: _ButtonCommand = \"\",\n        compound: _Compound = \"none\",\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 1,\n        image: _ImageSpec = \"\",\n        indicatoron: bool = True,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        offrelief: _Relief = ...,\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: _Relief | Literal[\"\"] = \"\",\n        padx: _ScreenUnits = 1,\n        pady: _ScreenUnits = 1,\n        relief: _Relief = \"flat\",\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = \"\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: _TakeFocusValue = \"\",\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        tristateimage: _ImageSpec = \"\",\n        tristatevalue: Any = \"\",\n        underline: int = -1,\n        variable: Variable | Literal[\"\"] = ...,\n        width: _ScreenUnits = 0,\n        wraplength: _ScreenUnits = 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: _Anchor = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        command: _ButtonCommand = ...,\n        compound: _Compound = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offrelief: _Relief = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        overrelief: _Relief | Literal[\"\"] = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        tristateimage: _ImageSpec = ...,\n        tristatevalue: Any = ...,\n        underline: int = ...,\n        variable: Variable | Literal[\"\"] = ...,\n        width: _ScreenUnits = ...,\n        wraplength: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertwidth: _ScreenUnits = ...,\n        invalidcommand: _EntryValidateCommand = \"\",\n        invcmd: _EntryValidateCommand = \"\",  # same as invalidcommand\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        readonlybackground: str = ...,\n        relief: _Relief = \"sunken\",\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        show: str = \"\",\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = \"normal\",\n        takefocus: _TakeFocusValue = \"\",\n        textvariable: Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: _EntryValidateCommand = \"\",\n        vcmd: _EntryValidateCommand = \"\",  # same as validatecommand\n        width: int = 20,\n        xscrollcommand: _XYScrollCommand = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertwidth: _ScreenUnits = ...,\n        invalidcommand: _EntryValidateCommand = ...,\n        invcmd: _EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        readonlybackground: str = ...,\n        relief: _Relief = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        show: str = ...,\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        textvariable: Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: _EntryValidateCommand = ...,\n        vcmd: _EntryValidateCommand = ...,\n        width: int = ...,\n        xscrollcommand: _XYScrollCommand = ...,\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: _ScreenUnits = 0,\n        bg: str = ...,\n        border: _ScreenUnits = 0,\n        borderwidth: _ScreenUnits = 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: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 0,\n        name: str = ...,\n        padx: _ScreenUnits = 0,\n        pady: _ScreenUnits = 0,\n        relief: _Relief = \"flat\",\n        takefocus: _TakeFocusValue = 0,\n        visual: str | tuple[str, int] = \"\",  # can't be changed with configure()\n        width: _ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        takefocus: _TakeFocusValue = ...,\n        width: _ScreenUnits = ...,\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: _Anchor = \"center\",\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        compound: _Compound = \"none\",\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 0,\n        image: _ImageSpec = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        padx: _ScreenUnits = 1,\n        pady: _ScreenUnits = 1,\n        relief: _Relief = \"flat\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: _TakeFocusValue = 0,\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        underline: int = -1,\n        width: _ScreenUnits = 0,\n        wraplength: _ScreenUnits = 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: _Anchor = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        compound: _Compound = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        image: _ImageSpec = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        underline: int = ...,\n        width: _ScreenUnits = ...,\n        wraplength: _ScreenUnits = ...,\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: _ScreenUnits = 1,\n        bg: str = ...,\n        border: _ScreenUnits = 1,\n        borderwidth: _ScreenUnits = 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: _ScreenUnits = ...,\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: _Relief = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = 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: _TakeFocusValue = \"\",\n        width: int = 20,\n        xscrollcommand: _XYScrollCommand = \"\",\n        yscrollcommand: _XYScrollCommand = \"\",\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: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        listvariable: Variable = ...,\n        relief: _Relief = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        selectmode: str | Literal[\"single\", \"browse\", \"multiple\", \"extended\"] = ...,  # noqa: Y051\n        setgrid: bool = ...,\n        state: Literal[\"normal\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        width: int = ...,\n        xscrollcommand: _XYScrollCommand = ...,\n        yscrollcommand: _XYScrollCommand = ...,\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: Incomplete | None = 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: _ScreenUnits = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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: _Relief = ...,\n        selectcolor: str = ...,\n        takefocus: _TakeFocusValue = 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: _ScreenUnits = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        postcommand: Callable[[], object] | str = ...,\n        relief: _Relief = ...,\n        selectcolor: str = ...,\n        takefocus: _TakeFocusValue = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\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: _Compound = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = ...,\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: _Anchor = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        compound: _Compound = \"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: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 0,\n        image: _ImageSpec = \"\",\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        menu: Menu = ...,\n        name: str = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = \"flat\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: _TakeFocusValue = 0,\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        underline: int = -1,\n        width: _ScreenUnits = 0,\n        wraplength: _ScreenUnits = 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: _Anchor = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        compound: _Compound = ...,\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: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        menu: Menu = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        underline: int = ...,\n        width: _ScreenUnits = ...,\n        wraplength: _ScreenUnits = ...,\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: _Anchor = \"center\",\n        aspect: int = 150,\n        background: str = ...,\n        bd: _ScreenUnits = 1,\n        bg: str = ...,\n        border: _ScreenUnits = 1,\n        borderwidth: _ScreenUnits = 1,\n        cursor: _Cursor = \"\",\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 0,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = \"flat\",\n        takefocus: _TakeFocusValue = 0,\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        # there's width but no height\n        width: _ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        anchor: _Anchor = ...,\n        aspect: int = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        width: _ScreenUnits = ...,\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: _Anchor = \"center\",\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        command: _ButtonCommand = \"\",\n        compound: _Compound = \"none\",\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 1,\n        image: _ImageSpec = \"\",\n        indicatoron: bool = True,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        offrelief: _Relief = ...,\n        overrelief: _Relief | Literal[\"\"] = \"\",\n        padx: _ScreenUnits = 1,\n        pady: _ScreenUnits = 1,\n        relief: _Relief = \"flat\",\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = \"\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: _TakeFocusValue = \"\",\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        tristateimage: _ImageSpec = \"\",\n        tristatevalue: Any = \"\",\n        underline: int = -1,\n        value: Any = \"\",\n        variable: Variable | Literal[\"\"] = ...,\n        width: _ScreenUnits = 0,\n        wraplength: _ScreenUnits = 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: _Anchor = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        command: _ButtonCommand = ...,\n        compound: _Compound = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        image: _ImageSpec = ...,\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offrelief: _Relief = ...,\n        overrelief: _Relief | Literal[\"\"] = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        selectcolor: str = ...,\n        selectimage: _ImageSpec = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        tristateimage: _ImageSpec = ...,\n        tristatevalue: Any = ...,\n        underline: int = ...,\n        value: Any = ...,\n        variable: Variable | Literal[\"\"] = ...,\n        width: _ScreenUnits = ...,\n        wraplength: _ScreenUnits = ...,\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: _ScreenUnits = 1,\n        bg: str = ...,\n        bigincrement: float = 0.0,\n        border: _ScreenUnits = 1,\n        borderwidth: _ScreenUnits = 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: _ScreenUnits = ...,\n        label: str = \"\",\n        length: _ScreenUnits = 100,\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"vertical\",\n        relief: _Relief = \"flat\",\n        repeatdelay: int = 300,\n        repeatinterval: int = 100,\n        resolution: float = 1.0,\n        showvalue: bool = True,\n        sliderlength: _ScreenUnits = 30,\n        sliderrelief: _Relief = \"raised\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: _TakeFocusValue = \"\",\n        tickinterval: float = 0.0,\n        to: float = 100.0,\n        troughcolor: str = ...,\n        variable: IntVar | DoubleVar = ...,\n        width: _ScreenUnits = 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: _ScreenUnits = ...,\n        bg: str = ...,\n        bigincrement: float = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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: _ScreenUnits = ...,\n        label: str = ...,\n        length: _ScreenUnits = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        relief: _Relief = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        resolution: float = ...,\n        showvalue: bool = ...,\n        sliderlength: _ScreenUnits = ...,\n        sliderrelief: _Relief = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        tickinterval: float = ...,\n        to: float = ...,\n        troughcolor: str = ...,\n        variable: IntVar | DoubleVar = ...,\n        width: _ScreenUnits = ...,\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: _Relief = \"raised\",\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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: _ScreenUnits = -1,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 0,\n        jump: bool = False,\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"vertical\",\n        relief: _Relief = ...,\n        repeatdelay: int = 300,\n        repeatinterval: int = 100,\n        takefocus: _TakeFocusValue = \"\",\n        troughcolor: str = ...,\n        width: _ScreenUnits = ...,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activerelief: _Relief = ...,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        command: Callable[..., tuple[float, float] | None] | str = ...,\n        cursor: _Cursor = ...,\n        elementborderwidth: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        jump: bool = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        relief: _Relief = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        takefocus: _TakeFocusValue = ...,\n        troughcolor: str = ...,\n        width: _ScreenUnits = ...,\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: Incomplete | None = 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_TextIndex: TypeAlias = _tkinter.Tcl_Obj | str | float | Misc\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: _ScreenUnits = ...,\n        bg: str = ...,\n        blockcursor: bool = False,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\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 ScreenUnits.\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: _ScreenUnits = 24,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        inactiveselectbackground: str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertunfocussed: Literal[\"none\", \"hollow\", \"solid\"] = \"none\",\n        insertwidth: _ScreenUnits = ...,\n        maxundo: int = 0,\n        name: str = ...,\n        padx: _ScreenUnits = 1,\n        pady: _ScreenUnits = 1,\n        relief: _Relief = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        setgrid: bool = False,\n        spacing1: _ScreenUnits = 0,\n        spacing2: _ScreenUnits = 0,\n        spacing3: _ScreenUnits = 0,\n        startline: int | Literal[\"\"] = \"\",\n        state: Literal[\"normal\", \"disabled\"] = \"normal\",\n        # Literal inside Tuple doesn't actually work\n        tabs: _ScreenUnits | str | tuple[_ScreenUnits | str, ...] = \"\",\n        tabstyle: Literal[\"tabular\", \"wordprocessor\"] = \"tabular\",\n        takefocus: _TakeFocusValue = \"\",\n        undo: bool = False,\n        width: int = 80,\n        wrap: Literal[\"none\", \"char\", \"word\"] = \"char\",\n        xscrollcommand: _XYScrollCommand = \"\",\n        yscrollcommand: _XYScrollCommand = \"\",\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: _ScreenUnits = ...,\n        bg: str = ...,\n        blockcursor: bool = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        endline: int | Literal[\"\"] = ...,\n        exportselection: bool = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        inactiveselectbackground: str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertunfocussed: Literal[\"none\", \"hollow\", \"solid\"] = ...,\n        insertwidth: _ScreenUnits = ...,\n        maxundo: int = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        setgrid: bool = ...,\n        spacing1: _ScreenUnits = ...,\n        spacing2: _ScreenUnits = ...,\n        spacing3: _ScreenUnits = ...,\n        startline: int | Literal[\"\"] = ...,\n        state: Literal[\"normal\", \"disabled\"] = ...,\n        tabs: _ScreenUnits | str | tuple[_ScreenUnits | str, ...] = ...,\n        tabstyle: Literal[\"tabular\", \"wordprocessor\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        undo: bool = ...,\n        width: int = ...,\n        wrap: Literal[\"none\", \"char\", \"word\"] = ...,\n        xscrollcommand: _XYScrollCommand = ...,\n        yscrollcommand: _XYScrollCommand = ...,\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: _TextIndex) -> tuple[int, int, int, int] | None: ...  # type: ignore[override]\n    def compare(self, index1: _TextIndex, op: Literal[\"<\", \"<=\", \"==\", \">=\", \">\", \"!=\"], index2: _TextIndex) -> bool: ...\n    if sys.version_info >= (3, 13):\n        @overload\n        def count(self, index1: _TextIndex, index2: _TextIndex, *, return_ints: Literal[True]) -> int: ...\n        @overload\n        def count(\n            self, index1: _TextIndex, index2: _TextIndex, arg: _WhatToCount | Literal[\"update\"], /, *, return_ints: Literal[True]\n        ) -> int: ...\n        @overload\n        def count(\n            self,\n            index1: _TextIndex,\n            index2: _TextIndex,\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: _TextIndex,\n            index2: _TextIndex,\n            arg1: _WhatToCount,\n            arg2: Literal[\"update\"],\n            /,\n            *,\n            return_ints: Literal[True],\n        ) -> int: ...\n        @overload\n        def count(\n            self, index1: _TextIndex, index2: _TextIndex, arg1: _WhatToCount, arg2: _WhatToCount, /, *, return_ints: Literal[True]\n        ) -> tuple[int, int]: ...\n        @overload\n        def count(\n            self,\n            index1: _TextIndex,\n            index2: _TextIndex,\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(self, index1: _TextIndex, index2: _TextIndex, *, return_ints: Literal[False] = False) -> tuple[int] | None: ...\n        @overload\n        def count(\n            self,\n            index1: _TextIndex,\n            index2: _TextIndex,\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: _TextIndex,\n            index2: _TextIndex,\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: _TextIndex,\n            index2: _TextIndex,\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: _TextIndex,\n            index2: _TextIndex,\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: _TextIndex,\n            index2: _TextIndex,\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(self, index1: _TextIndex, index2: _TextIndex) -> tuple[int] | None: ...\n        @overload\n        def count(\n            self, index1: _TextIndex, index2: _TextIndex, arg: _WhatToCount | Literal[\"update\"], /\n        ) -> tuple[int] | None: ...\n        @overload\n        def count(self, index1: _TextIndex, index2: _TextIndex, arg1: Literal[\"update\"], arg2: _WhatToCount, /) -> int | None: ...\n        @overload\n        def count(self, index1: _TextIndex, index2: _TextIndex, arg1: _WhatToCount, arg2: Literal[\"update\"], /) -> int | None: ...\n        @overload\n        def count(self, index1: _TextIndex, index2: _TextIndex, arg1: _WhatToCount, arg2: _WhatToCount, /) -> tuple[int, int]: ...\n        @overload\n        def count(\n            self,\n            index1: _TextIndex,\n            index2: _TextIndex,\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(self, index1: _TextIndex, index2: _TextIndex | None = None) -> None: ...\n    def dlineinfo(self, index: _TextIndex) -> tuple[int, int, int, int, int] | None: ...\n    @overload\n    def dump(\n        self,\n        index1: _TextIndex,\n        index2: _TextIndex | 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: _TextIndex,\n        index2: _TextIndex | 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: _TextIndex,\n        index2: _TextIndex | 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(self, index1: _TextIndex, index2: _TextIndex | None = None) -> str: ...\n    @overload\n    def image_cget(self, index: _TextIndex, option: Literal[\"image\", \"name\"]) -> str: ...\n    @overload\n    def image_cget(self, index: _TextIndex, option: Literal[\"padx\", \"pady\"]) -> int: ...\n    @overload\n    def image_cget(self, index: _TextIndex, option: Literal[\"align\"]) -> Literal[\"baseline\", \"bottom\", \"center\", \"top\"]: ...\n    @overload\n    def image_cget(self, index: _TextIndex, option: str) -> Any: ...\n    @overload\n    def image_configure(self, index: _TextIndex, cnf: str) -> tuple[str, str, str, str, str | int]: ...\n    @overload\n    def image_configure(\n        self,\n        index: _TextIndex,\n        cnf: dict[str, Any] | None = {},\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        image: _ImageSpec = ...,\n        name: str = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n    ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ...\n    def image_create(\n        self,\n        index: _TextIndex,\n        cnf: dict[str, Any] | None = {},\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        image: _ImageSpec = ...,\n        name: str = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n    ) -> str: ...\n    def image_names(self) -> tuple[str, ...]: ...\n    def index(self, index: _TextIndex) -> str: ...\n    def insert(self, index: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> 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: _TextIndex) -> None: ...\n    def mark_unset(self, *markNames: str) -> None: ...\n    def mark_next(self, index: _TextIndex) -> str | None: ...\n    def mark_previous(self, index: _TextIndex) -> 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(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> 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: _TextIndex,\n        stopindex: _TextIndex | 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: _TextIndex) -> None: ...\n    def tag_add(self, tagName: str, index1: _TextIndex, *args: _TextIndex) -> 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: _ScreenUnits = ...,\n        border: _ScreenUnits = ...,  # alias for borderwidth\n        elide: bool = ...,\n        fgstipple: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        justify: Literal[\"left\", \"right\", \"center\"] = ...,\n        lmargin1: _ScreenUnits = ...,\n        lmargin2: _ScreenUnits = ...,\n        lmargincolor: str = ...,\n        offset: _ScreenUnits = ...,\n        overstrike: bool = ...,\n        overstrikefg: str = ...,\n        relief: _Relief = ...,\n        rmargin: _ScreenUnits = ...,\n        rmargincolor: str = ...,\n        selectbackground: str = ...,\n        selectforeground: str = ...,\n        spacing1: _ScreenUnits = ...,\n        spacing2: _ScreenUnits = ...,\n        spacing3: _ScreenUnits = ...,\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: _TextIndex | None = None) -> tuple[str, ...]: ...\n    def tag_nextrange(\n        self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = None\n    ) -> tuple[str, str] | tuple[()]: ...\n    def tag_prevrange(\n        self, tagName: str, index1: _TextIndex, index2: _TextIndex | 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(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = None) -> None: ...\n    @overload\n    def window_cget(self, index: _TextIndex, option: Literal[\"padx\", \"pady\"]) -> int: ...\n    @overload\n    def window_cget(self, index: _TextIndex, option: Literal[\"stretch\"]) -> bool: ...  # actually returns Literal[0, 1]\n    @overload\n    def window_cget(self, index: _TextIndex, option: Literal[\"align\"]) -> 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: _TextIndex, option: Literal[\"create\", \"window\"]) -> str: ...\n    @overload\n    def window_cget(self, index: _TextIndex, option: str) -> Any: ...\n    @overload\n    def window_configure(self, index: _TextIndex, cnf: str) -> tuple[str, str, str, str, str | int]: ...\n    @overload\n    def window_configure(\n        self,\n        index: _TextIndex,\n        cnf: dict[str, Any] | None = None,\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        create: str = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\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: _TextIndex,\n        cnf: dict[str, Any] | None = {},\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        create: str = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\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: Incomplete | None = None) -> None: ...\n    def __call__(self, *args) -> None: ...\n\n# manual page: tk_optionMenu\nclass OptionMenu(Menubutton):\n    widgetName: Incomplete\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__(\n        self, imgtype, name: Incomplete | None = None, cnf={}, master: Misc | _tkinter.TkappType | None = None, **kw\n    ) -> 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            | 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] | 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: Incomplete | None = 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: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        buttonbackground: str = ...,\n        buttoncursor: _Cursor = \"\",\n        buttondownrelief: _Relief = ...,\n        buttonuprelief: _Relief = ...,\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: _ScreenUnits = ...,\n        increment: float = 1.0,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertwidth: _ScreenUnits = ...,\n        invalidcommand: _EntryValidateCommand = \"\",\n        invcmd: _EntryValidateCommand = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        readonlybackground: str = ...,\n        relief: _Relief = \"sunken\",\n        repeatdelay: int = 400,\n        repeatinterval: int = 100,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = \"normal\",\n        takefocus: _TakeFocusValue = \"\",\n        textvariable: Variable = ...,\n        to: float = 0.0,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: _EntryValidateCommand = \"\",\n        vcmd: _EntryValidateCommand = \"\",\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = 20,\n        wrap: bool = False,\n        xscrollcommand: _XYScrollCommand = \"\",\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: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        buttonbackground: str = ...,\n        buttoncursor: _Cursor = ...,\n        buttondownrelief: _Relief = ...,\n        buttonuprelief: _Relief = ...,\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: _ScreenUnits = ...,\n        increment: float = ...,\n        insertbackground: str = ...,\n        insertborderwidth: _ScreenUnits = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertwidth: _ScreenUnits = ...,\n        invalidcommand: _EntryValidateCommand = ...,\n        invcmd: _EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        readonlybackground: str = ...,\n        relief: _Relief = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        selectbackground: str = ...,\n        selectborderwidth: _ScreenUnits = ...,\n        selectforeground: str = ...,\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = ...,\n        takefocus: _TakeFocusValue = ...,\n        textvariable: Variable = ...,\n        to: float = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: _EntryValidateCommand = ...,\n        vcmd: _EntryValidateCommand = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        wrap: bool = ...,\n        xscrollcommand: _XYScrollCommand = ...,\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: Incomplete | None = 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: Incomplete | None = 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: _ScreenUnits = 2,\n        bg: str = ...,\n        border: _ScreenUnits = 2,\n        borderwidth: _ScreenUnits = 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: _ScreenUnits = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = 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: _ScreenUnits = 0,\n        pady: _ScreenUnits = 0,\n        relief: _Relief = \"groove\",\n        takefocus: _TakeFocusValue = 0,\n        text: float | str = \"\",\n        visual: str | tuple[str, int] = \"\",  # can't be changed with configure()\n        width: _ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: _ScreenUnits = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: _ScreenUnits = ...,\n        labelanchor: Literal[\"nw\", \"n\", \"ne\", \"en\", \"e\", \"es\", \"se\", \"s\", \"sw\", \"ws\", \"w\", \"wn\"] = ...,\n        labelwidget: Misc = ...,\n        padx: _ScreenUnits = ...,\n        pady: _ScreenUnits = ...,\n        relief: _Relief = ...,\n        takefocus: _TakeFocusValue = ...,\n        text: float | str = ...,\n        width: _ScreenUnits = ...,\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: _ScreenUnits = 1,\n        bg: str = ...,\n        border: _ScreenUnits = 1,\n        borderwidth: _ScreenUnits = 1,\n        cursor: _Cursor = \"\",\n        handlepad: _ScreenUnits = 8,\n        handlesize: _ScreenUnits = 8,\n        height: _ScreenUnits = \"\",\n        name: str = ...,\n        opaqueresize: bool = True,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"horizontal\",\n        proxybackground: str = \"\",\n        proxyborderwidth: _ScreenUnits = 2,\n        proxyrelief: _Relief = \"flat\",\n        relief: _Relief = \"flat\",\n        sashcursor: _Cursor = \"\",\n        sashpad: _ScreenUnits = 0,\n        sashrelief: _Relief = \"flat\",\n        sashwidth: _ScreenUnits = 3,\n        showhandle: bool = False,\n        width: _ScreenUnits = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: _ScreenUnits = ...,\n        bg: str = ...,\n        border: _ScreenUnits = ...,\n        borderwidth: _ScreenUnits = ...,\n        cursor: _Cursor = ...,\n        handlepad: _ScreenUnits = ...,\n        handlesize: _ScreenUnits = ...,\n        height: _ScreenUnits = ...,\n        opaqueresize: bool = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        proxybackground: str = ...,\n        proxyborderwidth: _ScreenUnits = ...,\n        proxyrelief: _Relief = ...,\n        relief: _Relief = ...,\n        sashcursor: _Cursor = ...,\n        sashpad: _ScreenUnits = ...,\n        sashrelief: _Relief = ...,\n        sashwidth: _ScreenUnits = ...,\n        showhandle: bool = ...,\n        width: _ScreenUnits = ...,\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: Incomplete\n    def identify(self, x: int, y: int): ...\n    def proxy(self, *args): ...\n    def proxy_coord(self): ...\n    def proxy_forget(self): ...\n    def proxy_place(self, x, y): ...\n    def sash(self, *args): ...\n    def sash_coord(self, index): ...\n    def sash_mark(self, index): ...\n    def sash_place(self, index, x, y): ...\n    def panecget(self, child, option): ...\n    def paneconfigure(self, tagOrId, cnf: Incomplete | None = None, **kw): ...\n    paneconfig: Incomplete\n    def panes(self): ...\n\ndef _test() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/colorchooser.pyi",
    "content": "import sys\nfrom tkinter import Misc\nfrom tkinter.commondialog import Dialog\nfrom typing import ClassVar\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"Chooser\", \"askcolor\"]\n\nclass Chooser(Dialog):\n    command: ClassVar[str]\n\nif sys.version_info >= (3, 9):\n    def askcolor(\n        color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ...\n    ) -> tuple[None, None] | tuple[tuple[int, int, int], str]: ...\n\nelse:\n    def askcolor(\n        color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ...\n    ) -> tuple[None, None] | tuple[tuple[float, float, float], str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/commondialog.pyi",
    "content": "import sys\nfrom _typeshed import Incomplete\nfrom collections.abc import Mapping\nfrom typing import ClassVar\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"Dialog\"]\n\nclass Dialog:\n    command: ClassVar[str | None]\n    master: Incomplete | None\n    options: Mapping[str, Incomplete]\n    def __init__(self, master: Incomplete | None = None, **options) -> None: ...\n    def show(self, **options): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/constants.pyi",
    "content": "from typing import Final\n\n# These are not actually bools. See #4669\nNO: Final[bool]\nYES: Final[bool]\nTRUE: Final[bool]\nFALSE: Final[bool]\nON: Final[bool]\nOFF: Final[bool]\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": "import sys\nfrom _typeshed import Incomplete\nfrom collections.abc import Mapping\nfrom tkinter import Widget\nfrom typing import Any, Final\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"Dialog\"]\n\nDIALOG_ICON: Final = \"questhead\"\n\nclass Dialog(Widget):\n    widgetName: str\n    num: int\n    def __init__(self, master: Incomplete | None = None, cnf: Mapping[str, Any] = {}, **kw) -> None: ...\n    def destroy(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/dnd.pyi",
    "content": "import sys\nfrom tkinter import Event, Misc, Tk, Widget\nfrom typing import ClassVar, Protocol\n\nif sys.version_info >= (3, 9):\n    __all__ = [\"dnd_start\", \"DndHandler\"]\n\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": "import sys\nfrom _typeshed import Incomplete, StrOrBytesPath\nfrom collections.abc import Iterable\nfrom tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog\nfrom typing import IO, ClassVar, Literal\n\nif sys.version_info >= (3, 9):\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[Incomplete, tuple[Incomplete, Incomplete]]\n\nclass FileDialog:\n    title: str\n    master: Incomplete\n    directory: Incomplete | 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, title: Incomplete | None = None\n    ) -> None: ...  # title is usually a str or None, but e.g. int doesn't raise en exception either\n    how: Incomplete | None\n    def go(self, dir_or_file=\".\", pattern: str = \"*\", default: str = \"\", key: Incomplete | None = None): ...\n    def quit(self, how: Incomplete | None = None) -> None: ...\n    def dirs_double_event(self, event) -> None: ...\n    def dirs_select_event(self, event) -> None: ...\n    def files_double_event(self, event) -> None: ...\n    def files_select_event(self, event) -> None: ...\n    def ok_event(self, event) -> None: ...\n    def ok_command(self) -> None: ...\n    def filter_command(self, event: Incomplete | None = None) -> None: ...\n    def get_filter(self): ...\n    def get_selection(self): ...\n    def cancel_command(self, event: Incomplete | None = None) -> None: ...\n    def set_filter(self, dir, pat) -> None: ...\n    def set_selection(self, file) -> 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\nfrom typing_extensions import TypeAlias, Unpack\n\nif sys.version_info >= (3, 9):\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\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\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": "import sys\nfrom tkinter.commondialog import Dialog\nfrom typing import ClassVar, Final\n\nif sys.version_info >= (3, 9):\n    __all__ = [\n        \"showinfo\",\n        \"showwarning\",\n        \"showerror\",\n        \"askquestion\",\n        \"askokcancel\",\n        \"askyesno\",\n        \"askyesnocancel\",\n        \"askretrycancel\",\n    ]\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(title: str | None = None, message: str | None = None, **options) -> str: ...\ndef showwarning(title: str | None = None, message: str | None = None, **options) -> str: ...\ndef showerror(title: str | None = None, message: str | None = None, **options) -> str: ...\ndef askquestion(title: str | None = None, message: str | None = None, **options) -> str: ...\ndef askokcancel(title: str | None = None, message: str | None = None, **options) -> bool: ...\ndef askyesno(title: str | None = None, message: str | None = None, **options) -> bool: ...\ndef askyesnocancel(title: str | None = None, message: str | None = None, **options) -> bool | None: ...\ndef askretrycancel(title: str | None = None, message: str | None = None, **options) -> 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 tkinter\nfrom _typeshed import Incomplete, MaybeNone\nfrom collections.abc import Callable\nfrom tkinter.font import _FontDescription\nfrom typing import Any, Literal, TypedDict, overload\nfrom typing_extensions import TypeAlias\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: Incomplete | None = None): ...\n\n_Padding: TypeAlias = (\n    tkinter._ScreenUnits\n    | tuple[tkinter._ScreenUnits]\n    | tuple[tkinter._ScreenUnits, tkinter._ScreenUnits]\n    | tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits]\n    | tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits]\n)\n\n# from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound\n_TtkCompound: TypeAlias = Literal[\"\", \"text\", \"image\", tkinter._Compound]\n\nclass Style:\n    master: Incomplete\n    tk: _tkinter.TkappType\n    def __init__(self, master: tkinter.Misc | None = None) -> None: ...\n    def configure(self, style, query_opt: Incomplete | None = None, **kw): ...\n    def map(self, style, query_opt: Incomplete | None = None, **kw): ...\n    def lookup(self, style, option, state: Incomplete | None = None, default: Incomplete | None = None): ...\n    def layout(self, style, layoutspec: Incomplete | None = None): ...\n    def element_create(self, elementname, etype, *args, **kw) -> None: ...\n    def element_names(self): ...\n    def element_options(self, elementname): ...\n    def theme_create(self, themename, parent: Incomplete | None = None, settings: Incomplete | None = None) -> None: ...\n    def theme_settings(self, themename, settings) -> 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, kw: Incomplete | None = None) -> None: ...\n    def identify(self, x: int, y: int) -> str: ...\n    def instate(self, statespec, callback: Incomplete | None = None, *args, **kw): ...\n    def state(self, statespec: Incomplete | None = None): ...\n\nclass Button(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        command: tkinter._ButtonCommand = \"\",\n        compound: _TtkCompound = \"\",\n        cursor: tkinter._Cursor = \"\",\n        default: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        image: tkinter._ImageSpec = \"\",\n        name: str = ...,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ButtonCommand = ...,\n        compound: _TtkCompound = ...,\n        cursor: tkinter._Cursor = ...,\n        default: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        image: tkinter._ImageSpec = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ButtonCommand = \"\",\n        compound: _TtkCompound = \"\",\n        cursor: tkinter._Cursor = \"\",\n        image: tkinter._ImageSpec = \"\",\n        name: str = ...,\n        offvalue: Any = 0,\n        onvalue: Any = 1,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ButtonCommand = ...,\n        compound: _TtkCompound = ...,\n        cursor: tkinter._Cursor = ...,\n        image: tkinter._ImageSpec = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._EntryValidateCommand = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        show: str = \"\",\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: tkinter._EntryValidateCommand = \"\",\n        width: int = 20,\n        xscrollcommand: tkinter._XYScrollCommand = \"\",\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: tkinter._EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        show: str = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: tkinter._EntryValidateCommand = ...,\n        width: int = ...,\n        xscrollcommand: tkinter._XYScrollCommand = ...,\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: tkinter._EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        show: str = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: tkinter._EntryValidateCommand = ...,\n        width: int = ...,\n        xscrollcommand: tkinter._XYScrollCommand = ...,\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: tkinter._EntryValidateCommand = ...,  # 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: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,  # undocumented\n        validatecommand: tkinter._EntryValidateCommand = ...,  # undocumented\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = 20,\n        xscrollcommand: tkinter._XYScrollCommand = ...,  # 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: tkinter._EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        postcommand: Callable[[], object] | str = ...,\n        show=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: tkinter._EntryValidateCommand = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        xscrollcommand: tkinter._XYScrollCommand = ...,\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: tkinter._EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        postcommand: Callable[[], object] | str = ...,\n        show=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: tkinter._EntryValidateCommand = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        xscrollcommand: tkinter._XYScrollCommand = ...,\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: tkinter._ScreenUnits = ...,\n        borderwidth: tkinter._ScreenUnits = ...,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        height: tkinter._ScreenUnits = 0,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: tkinter._Relief = ...,\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = \"\",\n        width: tkinter._ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        border: tkinter._ScreenUnits = ...,\n        borderwidth: tkinter._ScreenUnits = ...,\n        cursor: tkinter._Cursor = ...,\n        height: tkinter._ScreenUnits = ...,\n        padding: _Padding = ...,\n        relief: tkinter._Relief = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        width: tkinter._ScreenUnits = ...,\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: tkinter._Anchor = ...,\n        background: str = \"\",\n        border: tkinter._ScreenUnits = ...,  # alias for borderwidth\n        borderwidth: tkinter._ScreenUnits = ...,  # undocumented\n        class_: str = \"\",\n        compound: _TtkCompound = \"\",\n        cursor: tkinter._Cursor = \"\",\n        font: _FontDescription = ...,\n        foreground: str = \"\",\n        image: tkinter._ImageSpec = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: tkinter._Relief = ...,\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = \"\",\n        text: float | str = \"\",\n        textvariable: tkinter.Variable = ...,\n        underline: int = -1,\n        width: int | Literal[\"\"] = \"\",\n        wraplength: tkinter._ScreenUnits = ...,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        anchor: tkinter._Anchor = ...,\n        background: str = ...,\n        border: tkinter._ScreenUnits = ...,\n        borderwidth: tkinter._ScreenUnits = ...,\n        compound: _TtkCompound = ...,\n        cursor: tkinter._Cursor = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        image: tkinter._ImageSpec = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        padding: _Padding = ...,\n        relief: tkinter._Relief = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        text: float | str = ...,\n        textvariable: tkinter.Variable = ...,\n        underline: int = ...,\n        width: int | Literal[\"\"] = ...,\n        wraplength: tkinter._ScreenUnits = ...,\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: tkinter._ScreenUnits = ...,\n        borderwidth: tkinter._ScreenUnits = ...,  # undocumented\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        height: tkinter._ScreenUnits = 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: tkinter._Relief = ...,  # undocumented\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = \"\",\n        text: float | str = \"\",\n        underline: int = -1,\n        width: tkinter._ScreenUnits = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        border: tkinter._ScreenUnits = ...,\n        borderwidth: tkinter._ScreenUnits = ...,\n        cursor: tkinter._Cursor = ...,\n        height: tkinter._ScreenUnits = ...,\n        labelanchor: Literal[\"nw\", \"n\", \"ne\", \"en\", \"e\", \"es\", \"se\", \"s\", \"sw\", \"ws\", \"w\", \"wn\"] = ...,\n        labelwidget: tkinter.Misc = ...,\n        padding: _Padding = ...,\n        relief: tkinter._Relief = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        text: float | str = ...,\n        underline: int = ...,\n        width: tkinter._ScreenUnits = ...,\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: _TtkCompound = \"\",\n        cursor: tkinter._Cursor = \"\",\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = \"below\",\n        image: tkinter._ImageSpec = \"\",\n        menu: tkinter.Menu = ...,\n        name: str = ...,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\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: _TtkCompound = ...,\n        cursor: tkinter._Cursor = ...,\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = ...,\n        image: tkinter._ImageSpec = ...,\n        menu: tkinter.Menu = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = ...,\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: tkinter._Compound = ...,\n        underline: int = ...,\n    ) -> None: ...\n    def forget(self, tab_id) -> None: ...\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: Incomplete | None = None): ...\n    def tab(self, tab_id, option: Incomplete | None = 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: tkinter._TakeFocusValue = \"\",\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: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = ...,\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: Incomplete\n    def insert(self, pos, child, **kw) -> None: ...\n    def pane(self, pane, option: Incomplete | None = None, **kw): ...\n    def sashpos(self, index, newpos: Incomplete | None = 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: tkinter._ScreenUnits = 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: tkinter._TakeFocusValue = \"\",\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: tkinter._ScreenUnits = ...,\n        maximum: float = ...,\n        mode: Literal[\"determinate\", \"indeterminate\"] = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        phase: int = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ButtonCommand = \"\",\n        compound: _TtkCompound = \"\",\n        cursor: tkinter._Cursor = \"\",\n        image: tkinter._ImageSpec = \"\",\n        name: str = ...,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ButtonCommand = ...,\n        compound: _TtkCompound = ...,\n        cursor: tkinter._Cursor = ...,\n        image: tkinter._ImageSpec = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ScreenUnits = 100,\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"horizontal\",\n        state: str = ...,  # undocumented\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ScreenUnits = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._ScreenUnits = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = \"\",\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: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = \"\",\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: tkinter._TakeFocusValue = ...,\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: tkinter._TakeFocusValue = \"\",\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: tkinter._TakeFocusValue = ...,\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: tkinter._EntryValidateCommand = ...,  # undocumented\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,  # undocumented\n        name: str = ...,\n        show=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,  # undocumented\n        to: float = 0,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: tkinter._EntryValidateCommand = \"\",\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,  # undocumented\n        wrap: bool = False,\n        xscrollcommand: tkinter._XYScrollCommand = \"\",\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: tkinter._EntryValidateCommand = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        show=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: tkinter._TakeFocusValue = ...,\n        textvariable: tkinter.Variable = ...,\n        to: float = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: tkinter._EntryValidateCommand = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        wrap: bool = ...,\n        xscrollcommand: tkinter._XYScrollCommand = ...,\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\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\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\nclass _TreeviewHeaderDict(TypedDict):\n    text: str\n    image: list[str] | Literal[\"\"]\n    anchor: tkinter._Anchor\n    command: str\n    state: str  # Doesn't seem to appear anywhere else than in these dicts\n\nclass _TreeviewColumnDict(TypedDict):\n    width: int\n    minwidth: int\n    stretch: bool  # actually 0 or 1\n    anchor: tkinter._Anchor\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: tkinter._TakeFocusValue = ...,\n        xscrollcommand: tkinter._XYScrollCommand = \"\",\n        yscrollcommand: tkinter._XYScrollCommand = \"\",\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: tkinter._TakeFocusValue = ...,\n        xscrollcommand: tkinter._XYScrollCommand = ...,\n        yscrollcommand: tkinter._XYScrollCommand = ...,\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: tkinter._Anchor = ...,\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._ImageSpec = ...,\n        anchor: tkinter._Anchor = ...,\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._ImageSpec = ...,\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._ImageSpec = ...,\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) -> 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._ImageSpec = ...,\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: tkinter._ScreenUnits = ...,\n        borderwidth: tkinter._ScreenUnits = ...,\n        class_: str = \"\",\n        compound: Literal[\"top\", \"bottom\"] = \"top\",\n        cursor: tkinter._Cursor = \"\",\n        height: tkinter._ScreenUnits = 0,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: tkinter._Relief = ...,\n        style: str = \"\",\n        takefocus: tkinter._TakeFocusValue = \"\",\n        width: tkinter._ScreenUnits = 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\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\nENDMARKER: int\nNAME: int\nNUMBER: int\nSTRING: int\nNEWLINE: int\nINDENT: int\nDEDENT: int\nLPAR: int\nRPAR: int\nLSQB: int\nRSQB: int\nCOLON: int\nCOMMA: int\nSEMI: int\nPLUS: int\nMINUS: int\nSTAR: int\nSLASH: int\nVBAR: int\nAMPER: int\nLESS: int\nGREATER: int\nEQUAL: int\nDOT: int\nPERCENT: int\nLBRACE: int\nRBRACE: int\nEQEQUAL: int\nNOTEQUAL: int\nLESSEQUAL: int\nGREATEREQUAL: int\nTILDE: int\nCIRCUMFLEX: int\nLEFTSHIFT: int\nRIGHTSHIFT: int\nDOUBLESTAR: int\nPLUSEQUAL: int\nMINEQUAL: int\nSTAREQUAL: int\nSLASHEQUAL: int\nPERCENTEQUAL: int\nAMPEREQUAL: int\nVBAREQUAL: int\nCIRCUMFLEXEQUAL: int\nLEFTSHIFTEQUAL: int\nRIGHTSHIFTEQUAL: int\nDOUBLESTAREQUAL: int\nDOUBLESLASH: int\nDOUBLESLASHEQUAL: int\nAT: int\nRARROW: int\nELLIPSIS: int\nATEQUAL: int\nif sys.version_info < (3, 13):\n    AWAIT: int\n    ASYNC: int\nOP: int\nERRORTOKEN: int\nN_TOKENS: int\nNT_OFFSET: int\ntok_name: dict[int, str]\nCOMMENT: int\nNL: int\nENCODING: int\nTYPE_COMMENT: int\nTYPE_IGNORE: int\nCOLONEQUAL: int\nEXACT_TOKEN_TYPES: dict[str, int]\nif sys.version_info >= (3, 10):\n    SOFT_KEYWORD: int\n\nif sys.version_info >= (3, 12):\n    EXCLAMATION: int\n    FSTRING_END: int\n    FSTRING_MIDDLE: int\n    FSTRING_START: 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 token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES\nfrom typing import Any, NamedTuple, TextIO, type_check_only\nfrom typing_extensions import TypeAlias\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\ncookie_re: Pattern[str]\nblank_re: 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\nclass 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    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# the docstring says \"returns bytes\" but is incorrect --\n# if the ENCODING token is missing, it skips the encode\ndef untokenize(iterable: Iterable[_Token]) -> 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: str  # undocumented\nComment: str  # undocumented\nIgnore: str  # undocumented\nName: str  # undocumented\n\nHexnumber: str  # undocumented\nBinnumber: str  # undocumented\nOctnumber: str  # undocumented\nDecnumber: str  # undocumented\nIntnumber: str  # undocumented\nExponent: str  # undocumented\nPointfloat: str  # undocumented\nExpfloat: str  # undocumented\nFloatnumber: str  # undocumented\nImagnumber: str  # undocumented\nNumber: str  # undocumented\n\ndef _all_string_prefixes() -> set[str]: ...  # undocumented\n\nStringPrefix: str  # undocumented\n\nSingle: str  # undocumented\nDouble: str  # undocumented\nSingle3: str  # undocumented\nDouble3: str  # undocumented\nTriple: str  # undocumented\nString: str  # undocumented\n\nSpecial: str  # undocumented\nFunny: str  # undocumented\n\nPlainToken: str  # undocumented\nToken: str  # undocumented\n\nContStr: str  # undocumented\nPseudoExtras: str  # undocumented\nPseudoToken: str  # undocumented\n\nendpats: dict[str, str]  # undocumented\nsingle_quoted: set[str]  # undocumented\ntriple_quoted: set[str]  # undocumented\n\ntabsize: int  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tomllib.pyi",
    "content": "from _typeshed import SupportsRead\nfrom collections.abc import Callable\nfrom typing import Any\n\n__all__ = (\"loads\", \"load\", \"TOMLDecodeError\")\n\nclass 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    if sys.version_info >= (3, 9):\n        def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ...\n    else:\n        def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ...\n\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, 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\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]: ...\n\n# undocumented\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 in 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, 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: int) -> Any: ...\n    @overload\n    def __getitem__(self, pos: slice) -> 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    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    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    @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\nif sys.version_info >= (3, 9):\n    _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]]\nelse:\n    _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple]]\n\nclass 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    if sys.version_info >= (3, 9):\n        @property\n        def total_nframe(self) -> int | None: ...\n        def __init__(self, frames: Sequence[_FrameTuple], total_nframe: int | None = None) -> None: ...\n    else:\n        def __init__(self, frames: Sequence[_FrameTuple]) -> None: ...\n\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) -> 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[int]\n    OFLAG: Final[int]\n    CFLAG: Final[int]\n    LFLAG: Final[int]\n    ISPEED: Final[int]\n    OSPEED: Final[int]\n    CC: Final[int]\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 collections.abc import Callable, Sequence\nfrom tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar\nfrom typing import Any, ClassVar, Literal, TypedDict, overload\nfrom typing_extensions import Self, TypeAlias\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, 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\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\nclass 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__(self, type_: str, data: _PolygonCoords | PhotoImage | None = None) -> None: ...\n    def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = None) -> None: ...\n\nclass TurtleScreen(TurtleScreenBase):\n    def __init__(self, cv: Canvas, mode: str = \"standard\", colormode: float = 1.0, delay: int = 10) -> None: ...\n    def clear(self) -> None: ...\n    @overload\n    def mode(self, mode: None = None) -> str: ...\n    @overload\n    def mode(self, mode: str) -> 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    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: Any | 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    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: str = \"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: str = \"noresize\") -> None: ...\n    @overload\n    def resizemode(self, rmode: None = None) -> str: ...\n    @overload\n    def resizemode(self, rmode: str) -> 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: str = ...,\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        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    def begin_fill(self) -> None: ...\n    def end_fill(self) -> None: ...\n    def dot(self, size: int | None = None, *color: _Color) -> 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    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# Note: it's somewhat unfortunate that we have to copy the function signatures.\n# It would be nice if we could partially reduce the redundancy by doing something\n# like the following:\n#\n#     _screen: Screen\n#     clear = _screen.clear\n#\n# However, it seems pytype does not support this type of syntax in pyi files.\n\n# Functions copied from TurtleScreenBase:\n\n# Note: mainloop() was always present in the global scope, but was added to\n# TurtleScreenBase in Python 3.0\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: str) -> 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: ...\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: Any | 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\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: str) -> 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: str = ...,\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    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: ...\ndef begin_fill() -> None: ...\ndef end_fill() -> None: ...\ndef dot(size: int | None = None, *color: _Color) -> None: ...\ndef write(arg: object, move: bool = False, align: str = \"left\", font: tuple[str, int, str] = (\"Arial\", 8, \"normal\")) -> None: ...\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: Any | None = None) -> None: ...\ndef ondrag(fun: Callable[[float, float], object], btn: int = 1, add: Any | 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 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    MutableSequence,\n    ValuesView,\n)\nfrom importlib.machinery import ModuleSpec\n\n# pytype crashes if types.MappingProxyType inherits from collections.abc.Mapping instead of typing.Mapping\nfrom typing import Any, Generic, ClassVar, Mapping, TypeVar, final, overload  # noqa: Y022\nfrom typing_extensions import ParamSpec, Self, TypeVarTuple, deprecated, TypeAlias\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]\n\nif sys.version_info >= (3, 9):\n    __all__ += [\"GenericAlias\"]\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_out_T = TypeVar(\"_out_T\", covariant=True)\n_T2 = TypeVar(\"_T2\")\n_KT = TypeVar(\"_KT\")\n_KT_co = TypeVar(\"_KT_co\", covariant=True)\n_VT_co = TypeVar(\"_VT_co\", covariant=True)\n_P = ParamSpec(\"_P\")\n\n# Make sure this class definition stays roughly in line with `builtins.function`\n# This class is special-cased\n# is actually `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, Any]\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(\"Will be removed in Python 3.14. Use the co_lines() method 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\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]):\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[unsafe-variance]\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  # type: ignore[override]\n    def get(self, key: _KT_co, /) -> _VT_co | None: ...  # type: ignore[unsafe-variance]\n    @overload\n    def get(self, key: _KT_co, default: _VT_co | _T2, /) -> _VT_co | _T2: ...  # type: ignore[unsafe-variance]\n    if sys.version_info >= (3, 9):\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\nclass SimpleNamespace:\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    if sys.version_info >= (3, 13):\n        def __init__(self, mapping_or_iterable: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), /, **kwargs: Any) -> 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\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    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)\n_ReturnT_co = TypeVar(\"_ReturnT_co\", covariant=True)\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: ...\n    @property\n    def gi_running(self) -> bool: ...\n    @property\n    def gi_yieldfrom(self) -> GeneratorType[_YieldT_co, _SendT_contra, Any] | 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: ...\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@final\nclass CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_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: ...\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_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# is actually `builtins.method`\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    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n\n# this class is not generic at runtime and is special-cased by basedmypy\n@final\nclass BuiltinFunctionType(Generic[_P, _out_T]):\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: _P.args, **kwargs: _P.kwargs) -> _out_T: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n\nBuiltinMethodType = BuiltinFunctionType[_P, _out_T]\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\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# Actually a different type, but `property` is special and we want that too.\nDynamicClassAttribute = property\n\n_Fn = TypeVar(\"_Fn\", bound=Callable[..., object])\n_R = TypeVar(\"_R\")\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\nif sys.version_info >= (3, 9):\n    class GenericAlias:\n        @property\n        def __origin__(self) -> type: ...\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        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    # ideally, this would have a `: TypeAlias`, but it makes mypy output\n    #  an invalid error on this line\n    NoneType = type(None)\n\n    EllipsisType: TypeAlias = ellipsis\n    from builtins import _NotImplementedType\n\n    NotImplementedType = _NotImplementedType\n    @final\n    class UnionType:\n        @property\n        def __args__(self) -> tuple[Any, ...]: ...\n        def __or__(self, value: Any, /) -> UnionType: ...\n        def __ror__(self, value: Any, /) -> UnionType: ...\n        def __eq__(self, value: object, /) -> bool: ...\n        def __hash__(self) -> int: ...\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# ruff: noqa: F811\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, SupportsKeysAndGetItem\nfrom abc import ABCMeta, abstractmethod\nfrom re import Match as Match, Pattern as Pattern\nfrom types import (\n    BuiltinFunctionType,\n    CodeType,\n    FunctionType,\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, 9):\n    from types import GenericAlias\nif sys.version_info >= (3, 10):\n    from types import UnionType\n\n__all__ = [\n    \"AbstractSet\",\n    \"Any\",\n    \"AnyStr\",\n    \"AsyncContextManager\",\n    \"AsyncGenerator\",\n    \"AsyncIterable\",\n    \"AsyncIterator\",\n    \"Awaitable\",\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    \"FrozenSet\",\n    \"Generator\",\n    \"Generic\",\n    \"Hashable\",\n    \"ItemsView\",\n    \"Iterable\",\n    \"Iterator\",\n    \"KeysView\",\n    \"List\",\n    \"Literal\",\n    \"Mapping\",\n    \"MappingView\",\n    \"MutableMapping\",\n    \"MutableSequence\",\n    \"MutableSet\",\n    \"NamedTuple\",\n    \"NewType\",\n    \"Optional\",\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    \"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    \"type_check_only\",\n    \"ForwardRef\",\n    \"NoReturn\",\n    \"OrderedDict\",\n]\n\nif sys.version_info >= (3, 9):\n    __all__ += [\"Annotated\", \"BinaryIO\", \"IO\", \"Match\", \"Pattern\", \"TextIO\"]\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\nAny: _SpecialForm = ...\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: ...\n    @property\n    def __constraints__(self) -> tuple[Any, ...]: ...\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: ...\n    if sys.version_info >= (3, 13):\n        def __new__(\n            cls,\n            name: str,\n            *constraints: Any,\n            bound: Any | None = None,\n            contravariant: bool = False,\n            covariant: bool = False,\n            infer_variance: bool = False,\n            default: Any = ...,\n        ) -> Self: ...\n    elif sys.version_info >= (3, 12):\n        def __new__(\n            cls,\n            name: str,\n            *constraints: Any,\n            bound: Any | None = None,\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, name: str, *constraints: Any, bound: Any | None = None, covariant: bool = False, contravariant: bool = False\n        ) -> Self: ...\n    else:\n        def __init__(\n            self, name: str, *constraints: Any, bound: Any | None = None, covariant: bool = False, contravariant: bool = False\n        ) -> None: ...\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    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\n# Used for an undocumented mypy feature. Does not exist at runtime.\n_promote = object()\n\n# N.B. Keep this definition in sync with typing_extensions._SpecialForm\n@final\nclass _SpecialForm(_Final):\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\nGeneric: _SpecialForm\nProtocol: _SpecialForm\n\n@runtime_checkable\n# special cased: this paramspec is specified within a type list\nclass Callable(Protocol[_P, _T_co]):\n    @abstractmethod\n    def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T_co: ...\n\n# Internal mypy fallback type for named callables (does not exist at runtime)\n@type_check_only\nclass _NamedCallable(Callable, metaclass=ABCMeta):\n    \"\"\"Fake protocol for the different representations of functions that have names\"\"\"\n\n    __name__: str\n    __qualname__: str\n\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: ...\n            def has_default(self) -> bool: ...\n        if sys.version_info >= (3, 13):\n            def __new__(cls, name: str, *, default: Any = ...) -> Self: ...\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\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: ...\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: ...\n        if sys.version_info >= (3, 13):\n            def __new__(\n                cls,\n                name: str,\n                *,\n                bound: Any | None = None,\n                contravariant: bool = False,\n                covariant: bool = False,\n                infer_variance: bool = False,\n                default: Any = ...,\n            ) -> Self: ...\n        elif sys.version_info >= (3, 12):\n            def __new__(\n                cls,\n                name: str,\n                *,\n                bound: Any | None = None,\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, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False\n            ) -> Self: ...\n        else:\n            def __init__(\n                self, name: str, *, bound: Any | None = None, contravariant: bool = False, 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\n    Concatenate: _SpecialForm\n    TypeAlias: _SpecialForm\n    TypeGuard: _SpecialForm\n\n    class NewType:\n        def __init__(self, name: str, tp: Any) -> None: ...\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\nelse:\n    def NewType(name: str, tp: Any) -> Any: ...\n\n_F = TypeVar(\"_F\", bound=Callable[..., object])\n_P = _ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\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: ...\ndef 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: _F) -> _F: ...\n\n# Type aliases and type constructors\n\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\nif sys.version_info >= (3, 9):\n    Annotated: _SpecialForm\n\n# Predefined type variables.\nAnyStr = TypeVar(\"AnyStr\", str, bytes)  # noqa: Y001\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    @abstractmethod\n    def __int__(self) -> int: ...\n\n@runtime_checkable\nclass SupportsFloat(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __float__(self) -> float: ...\n\n@runtime_checkable\nclass SupportsComplex(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __complex__(self) -> complex: ...\n\n@runtime_checkable\nclass SupportsBytes(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __bytes__(self) -> bytes: ...\n\n@runtime_checkable\nclass SupportsIndex(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __index__(self) -> int: ...\n\n@runtime_checkable\nclass SupportsAbs(Protocol[_T_co]):\n    @abstractmethod\n    def __abs__(self) -> _T_co: ...\n\n@runtime_checkable\nclass SupportsRound(Protocol[_T_co]):\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 couroutines, and `AwaitableGenerator` having a 4th type parameter.\n_SendT_contra_nd = TypeVar(\"_SendT_contra_nd\", contravariant=True)\n_ReturnT_co_nd = TypeVar(\"_ReturnT_co_nd\", covariant=True)\n\nclass Coroutine(Awaitable[_ReturnT_co_nd], Generic[_YieldT_co, _SendT_contra_nd, _ReturnT_co_nd]):\n    __name__: str\n    __qualname__: str\n\n    @abstractmethod\n    def send(self, value: _SendT_contra_nd, /) -> _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@type_check_only\nclass AwaitableGenerator(\n    Awaitable[_ReturnT_co_nd],\n    Generator[_YieldT_co, _SendT_contra_nd, _ReturnT_co_nd],\n    Generic[_YieldT_co, _SendT_contra_nd, _ReturnT_co_nd, _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) -> 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) -> 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, 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) -> 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    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    def __init__(self, mapping: Mapping[Any, Any]) -> 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: Mapping[_KT_co, _VT_co]) -> None: ...  # undocumented\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: object) -> bool: ...\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: Mapping[_KT_co, Any]) -> None: ...  # undocumented\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: Mapping[Any, _VT_co]) -> None: ...  # undocumented\n    def __contains__(self, value: object) -> bool: ...\n    def __iter__(self) -> Iterator[_VT_co]: ...\n\nclass Mapping(Collection[_KT_co], Generic[_KT_co, _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    # Based: it is covariant\n    #  Implementations in the wild that misuse the invariant key type could potentially be unsafe,\n    #  But that is a tiny tradeoff compared to the benefit.\n    @abstractmethod\n    def __getitem__(self, key: _KT_co, /) -> _VT_co: ...  # type: ignore[unsafe-variance]\n    # Mixin methods\n    @overload\n    # in reality `key` is keyword, but `dict`s isn't, which sucks\n    def get(self, key: _KT_co, /) -> _VT_co | None: ...  # type: ignore[unsafe-variance]\n    @overload\n    def get(self, key: _KT_co, /, default: _VT_co | _T) -> _VT_co | _T: ...  # type: ignore[unsafe-variance]\n    def items(self) -> ItemsView[_KT_co, _VT_co]: ...\n    def keys(self) -> KeysView[_KT_co]: ...\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], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, m: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, **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    @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    @abstractmethod\n    def __enter__(self) -> BinaryIO: ...\n\nclass TextIO(IO[str]):\n    # See comment regarding the @properties in the `IO` class\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\nif sys.version_info < (3, 14):\n    ByteString: 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[..., Any]\n    | BuiltinFunctionType\n    | MethodType\n    | ModuleType\n    | WrapperDescriptorType\n    | MethodWrapperType\n    | MethodDescriptorType\n)\n\nif sys.version_info >= (3, 9):\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]: ...\n\nelse:\n    def get_type_hints(\n        obj: _get_type_hints_obj_allowed_types, globalns: dict[str, Any] | None = None, localns: Mapping[str, Any] | None = None\n    ) -> dict[str, Any]: ...\n\ndef get_args(tp: Any) -> tuple[Any, ...]: ...\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\nif sys.version_info >= (3, 9):\n    @overload\n    def get_origin(tp: GenericAlias) -> type: ...\n    @overload\n    def get_origin(tp: Any) -> object: ...\n\nelse:\n    def get_origin(tp: Any) -> object: ...\n\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: ...\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\nclass NamedTuple(tuple[Any, ...]):\n    if sys.version_info < (3, 9):\n        _field_types: ClassVar[dict[str, type]]\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# 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@type_check_only\nclass _TypedDict(Mapping[str, object], metaclass=ABCMeta):\n    __total__: ClassVar[bool]\n    if sys.version_info >= (3, 9):\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\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: _T, m: _T, /) -> 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    if sys.version_info >= (3, 9):\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@final\nclass ForwardRef(_Final):\n    __forward_arg__: str\n    __forward_code__: CodeType\n    __forward_evaluated__: bool\n    __forward_value__: Any | None\n    __forward_is_argument__: bool\n    __forward_is_class__: bool\n    __forward_module__: Any | None\n    if sys.version_info >= (3, 9):\n        # The module and is_class arguments were added in later Python 3.9 versions.\n        def __init__(self, arg: str, is_argument: bool = True, module: Any | None = None, *, is_class: bool = False) -> None: ...\n    else:\n        def __init__(self, arg: str, is_argument: bool = True) -> 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: ...\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: ...\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: ...\n    elif sys.version_info >= (3, 9):\n        def _evaluate(\n            self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, recursive_guard: frozenset[str]\n        ) -> Any | None: ...\n    else:\n        def _evaluate(self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None) -> Any | None: ...\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\nclass _Final:\n    \"\"\"Mixin to prohibit subclassing\"\"\"\n\n    def __init_subclass__(__cls, *args: object, **kwds: object): ...\n\n\nclass _BaseGenericAlias(_Final, _root=True):\n    __origin__: type\n    def __init__(self, origin: type, *, inst: bool = ..., name: str | None = ...) -> None:\n        self._inst = inst\n        self._name = name\n        self.__origin__ = origin\n\n_Params = Union[type, Tuple[type, ...]]\n\nclass _GenericAlias(_BaseGenericAlias, _root=True):\n    def __init__(\n        self,\n        origin: type,\n        params: _Params,\n        *,\n        inst: bool = ...,\n        name: str | None = ...,\n        _typevar_types: Type[TypeVar] = ...,\n        _paramspec_tvars: bool = ...,\n    ):\n        self.__args__: tuple[type, ...]\n        self.__parameters__: tuple[TypeVar, ...]\n        self._typevar_types = _typevar_types\n        self._paramspec_tvars = _paramspec_tvars\n        self.__module__ = origin.__module__\n    # def __eq__(self, other: object) -> bool:\n    #     ...\n    def __hash__(self) -> int: ...\n    def __or__(self, right: object) -> _SpecialForm: ...\n    def __ror__(self, left: object) -> _SpecialForm: ...\n    def __getitem__(self: _T, params: _Params) -> _T: ...\n    def copy_with(self: _T, params: _Params) -> _T: ...\n    # def __reduce__(self):\n    #     if self._name:\n    #         origin = globals()[self._name]\n    #     else:\n    #         origin = self.__origin__\n    #     args = tuple(self.__args__)\n    #     if len(args) == 1 and not isinstance(args[0], tuple):\n    #         args, = args\n    #     return operator.getitem, (origin, args)\n    def __mro_entries__(self, bases: tuple[type, ...]) -> tuple[type, ...]: ...\n\ndef _type_repr(obj: object) -> str: ...\n\nif sys.version_info >= (3, 12):\n    def override(method: _F, /) -> _F: ...\n    @final\n    class TypeAliasType:\n        def __new__(cls, name: str, value: Any, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ()) -> Self: ...\n        @property\n        def __value__(self) -> Any: ...\n        @property\n        def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ...\n        @property\n        def __parameters__(self) -> tuple[Any, ...]: ...\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: ...\n        def __or__(self, right: Any) -> _SpecialForm: ...\n        def __ror__(self, left: Any) -> _SpecialForm: ...\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    class _NoDefaultType: ...\n\n    NoDefault: _NoDefaultType\n    TypeIs: _SpecialForm\n    ReadOnly: _SpecialForm\n"
  },
  {
    "path": "mypy/typeshed/stdlib/typing_extensions.pyi",
    "content": "# Since this module defines \"Self\" it is not recognized by Ruff as typing_extensions.Self\n# ruff: noqa: PYI034\nimport abc\nimport sys\nimport typing\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import IdentityFunction\nfrom contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager\nfrom typing import (  # noqa: Y022,Y037,Y038,Y039\n    IO as IO,\n    TYPE_CHECKING as TYPE_CHECKING,\n    AbstractSet as AbstractSet,\n    Any as Any,\n    AnyStr as AnyStr,\n    AsyncGenerator as AsyncGenerator,\n    AsyncIterable as AsyncIterable,\n    AsyncIterator as AsyncIterator,\n    Awaitable as Awaitable,\n    BinaryIO as BinaryIO,\n    Callable as Callable,\n    ChainMap as ChainMap,\n    ClassVar as ClassVar,\n    Collection as Collection,\n    Container as Container,\n    Coroutine as Coroutine,\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    Generator as Generator,\n    Generic as Generic,\n    Hashable as Hashable,\n    ItemsView as ItemsView,\n    Iterable as Iterable,\n    Iterator as Iterator,\n    KeysView as KeysView,\n    List as List,\n    Mapping as Mapping,\n    MappingView as MappingView,\n    Match as Match,\n    MutableMapping as MutableMapping,\n    MutableSequence as MutableSequence,\n    MutableSet as MutableSet,\n    NoReturn as NoReturn,\n    Optional as Optional,\n    Pattern as Pattern,\n    Reversible as Reversible,\n    Sequence as Sequence,\n    Set as Set,\n    Sized as Sized,\n    Text as Text,\n    TextIO as TextIO,\n    Tuple as Tuple,\n    Type as Type,\n    TypedDict as TypedDict,\n    Union as Union,\n    ValuesView as ValuesView,\n    _Alias,\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\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\n__all__ = [\n    \"Any\",\n    \"Buffer\",\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    \"Awaitable\",\n    \"AsyncIterator\",\n    \"AsyncIterable\",\n    \"Coroutine\",\n    \"AsyncGenerator\",\n    \"AsyncContextManager\",\n    \"CapsuleType\",\n    \"ChainMap\",\n    \"ContextManager\",\n    \"Counter\",\n    \"Deque\",\n    \"DefaultDict\",\n    \"NamedTuple\",\n    \"OrderedDict\",\n    \"TypedDict\",\n    \"SupportsIndex\",\n    \"SupportsAbs\",\n    \"SupportsRound\",\n    \"SupportsBytes\",\n    \"SupportsComplex\",\n    \"SupportsFloat\",\n    \"SupportsInt\",\n    \"Annotated\",\n    \"assert_never\",\n    \"assert_type\",\n    \"dataclass_transform\",\n    \"deprecated\",\n    \"final\",\n    \"IntVar\",\n    \"is_typeddict\",\n    \"Literal\",\n    \"NewType\",\n    \"overload\",\n    \"override\",\n    \"Protocol\",\n    \"reveal_type\",\n    \"runtime\",\n    \"runtime_checkable\",\n    \"Text\",\n    \"TypeAlias\",\n    \"TypeAliasType\",\n    \"TypeGuard\",\n    \"TYPE_CHECKING\",\n    \"Never\",\n    \"NoReturn\",\n    \"Required\",\n    \"NotRequired\",\n    \"clear_overloads\",\n    \"get_args\",\n    \"get_origin\",\n    \"get_original_bases\",\n    \"get_overloads\",\n    \"get_type_hints\",\n    \"AbstractSet\",\n    \"AnyStr\",\n    \"BinaryIO\",\n    \"Callable\",\n    \"Collection\",\n    \"Container\",\n    \"Dict\",\n    \"Doc\",\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    \"NoDefault\",\n    \"Optional\",\n    \"Pattern\",\n    \"Reversible\",\n    \"Sequence\",\n    \"Set\",\n    \"Sized\",\n    \"TextIO\",\n    \"Tuple\",\n    \"Union\",\n    \"ValuesView\",\n    \"cast\",\n    \"get_protocol_members\",\n    \"is_protocol\",\n    \"no_type_check\",\n    \"no_type_check_decorator\",\n    \"ReadOnly\",\n    \"TypeIs\",\n]\n\n_T = typing.TypeVar(\"_T\")\n_F = typing.TypeVar(\"_F\", bound=Callable[..., Any])\n_TC = typing.TypeVar(\"_TC\", bound=type[object])\n_T_co = typing.TypeVar(\"_T_co\", covariant=True)  # Any type covariant containers.\n\nclass _Final: ...  # This should be imported from typing but that breaks pytype\n\n# unfortunately we have to duplicate this class definition from typing.pyi or we break pytype\nclass _SpecialForm(_Final):\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\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: ...\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]\n    __extra_items__: ClassVar[Any]\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: _T, m: _T, /) -> 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        @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        def __ior__(self, value: Self, /) -> Self: ...  # type: ignore[misc]\n\nOrderedDict = _Alias()\n\ndef get_type_hints(\n    obj: Callable[..., Any],\n    globalns: dict[str, Any] | None = None,\n    localns: Mapping[str, Any] | None = None,\n    include_extras: bool = False,\n) -> dict[str, Any]: ...\ndef get_args(tp: Any) -> tuple[Any, ...]: ...\n\nif sys.version_info >= (3, 10):\n    @overload\n    def get_origin(tp: UnionType) -> type[UnionType]: ...\n\nif sys.version_info >= (3, 9):\n    @overload\n    def get_origin(tp: GenericAlias) -> type: ...\n\n@overload\ndef get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ...\n@overload\ndef get_origin(tp: Any) -> Any | 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: Any, /) -> _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        if sys.version_info < (3, 9):\n            _field_types: ClassVar[dict[str, type]]\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: Any) -> None: ...\n        def __call__(self, obj: _T, /) -> _T: ...\n        __supertype__: type | NewType\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        TypeAliasType as TypeAliasType,\n        override as override,\n    )\nelse:\n    def override(arg: _F, /) -> _F: ...\n    def get_original_bases(cls: type, /) -> tuple[Any, ...]: ...\n    @final\n    class TypeAliasType:\n        def __init__(\n            self, name: str, value: Any, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ()\n        ) -> None: ...\n        @property\n        def __value__(self) -> Any: ...\n        @property\n        def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ...\n        @property\n        def __parameters__(self) -> tuple[Any, ...]: ...\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: Any) -> Any: ...\n        if sys.version_info >= (3, 10):\n            def __or__(self, right: Any) -> _SpecialForm: ...\n            def __ror__(self, left: Any) -> _SpecialForm: ...\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        @abc.abstractmethod\n        def __int__(self) -> int: ...\n\n    @runtime_checkable\n    class SupportsFloat(Protocol, metaclass=abc.ABCMeta):\n        @abc.abstractmethod\n        def __float__(self) -> float: ...\n\n    @runtime_checkable\n    class SupportsComplex(Protocol, metaclass=abc.ABCMeta):\n        @abc.abstractmethod\n        def __complex__(self) -> complex: ...\n\n    @runtime_checkable\n    class SupportsBytes(Protocol, metaclass=abc.ABCMeta):\n        @abc.abstractmethod\n        def __bytes__(self) -> bytes: ...\n\n    @runtime_checkable\n    class SupportsIndex(Protocol, metaclass=abc.ABCMeta):\n        @abc.abstractmethod\n        def __index__(self) -> int: ...\n\n    @runtime_checkable\n    class SupportsAbs(Protocol[_T_co]):\n        @abc.abstractmethod\n        def __abs__(self) -> _T_co: ...\n\n    @runtime_checkable\n    class SupportsRound(Protocol[_T_co]):\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, 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    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) -> Any | None: ...\n        @property\n        def __constraints__(self) -> tuple[Any, ...]: ...\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) -> Any: ...\n        def __init__(\n            self,\n            name: str,\n            *constraints: Any,\n            bound: Any | None = None,\n            covariant: bool = False,\n            contravariant: bool = False,\n            default: Any = ...,\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) -> Any | 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) -> Any: ...\n        def __init__(\n            self,\n            name: str,\n            *,\n            bound: None | type[Any] | str = None,\n            contravariant: bool = False,\n            covariant: bool = False,\n            default: Any = ...,\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) -> Any: ...\n        def __init__(self, name: str, *, default: Any = ...) -> 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\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"
  },
  {
    "path": "mypy/typeshed/stdlib/unicodedata.pyi",
    "content": "import sys\nfrom _typeshed import ReadOnlyBuffer\nfrom typing import Any, Literal, TypeVar, final, overload\nfrom typing_extensions import TypeAlias\n\nucd_3_2_0: UCD\nunidata_version: 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    if sys.version_info >= (3, 9):\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 collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet\nfrom contextlib import AbstractContextManager\nfrom re import Pattern\nfrom types import TracebackType\nfrom typing import (\n    Any,\n    AnyStr,\n    ClassVar,\n    Final,\n    Generic,\n    NamedTuple,\n    NoReturn,\n    Protocol,\n    SupportsAbs,\n    SupportsRound,\n    TypeVar,\n    overload,\n)\nfrom typing_extensions import ParamSpec, Self, TypeAlias\nfrom warnings import WarningMessage\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\n\nif sys.version_info >= (3, 10):\n    from types import UnionType\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_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\nif sys.version_info >= (3, 9):\n    from unittest._log import _AssertLogsContext, _LoggingWatcher\nelse:\n    # Unused dummy for _AssertLogsContext. Starting with Python 3.10,\n    # this is generic over the logging watcher, but in lower versions\n    # the watcher is hard-coded.\n    _L = TypeVar(\"_L\")\n\n    class _LoggingWatcher(NamedTuple):\n        records: list[logging.LogRecord]\n        output: list[str]\n\n    class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]):\n        LOGGING_FORMAT: ClassVar[str]\n        logger_name: str\n        level: int\n        msg: None\n        def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ...\n        def __enter__(self) -> _LoggingWatcher: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None\n        ) -> bool | None: ...\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\nclass _SupportsAbsAndDunderGE(SupportsDunderGE[Any], SupportsAbs[Any], Protocol): ...\n\n# Keep this alias in sync with builtins._ClassInfo\n# We can't import it from builtins or pytype crashes,\n# due to the fact that pytype uses a custom builtins stub rather than typeshed's builtins stub\nif sys.version_info >= (3, 10):\n    _ClassInfo: TypeAlias = type | UnionType | tuple[_ClassInfo, ...]\nelse:\n    _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...]\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\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    if sys.version_info >= (3, 9):\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    @deprecated(\"Deprecated in Python 3.11; removal scheduled for 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 in Python 3.11; removal scheduled for 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 in Python 3.11; removal scheduled for Python 3.13\")\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\nfrom typing_extensions import deprecated\n\nMAIN_EXAMPLES: Final[str]\nMODULE_EXAMPLES: Final[str]\n\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        @deprecated(\"Deprecated in Python 3.11; removal scheduled for Python 3.13\")\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 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\nfrom typing_extensions import ParamSpec, Self, TypeAlias\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\nif sys.version_info < (3, 9):\n    __version__: Final[str]\n\nFILTER_DIR: Any\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: Any\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\nclass _Call(tuple[Any, ...]):\n    def __new__(\n        cls, value: _CallValue = (), name: str | None = \"\", parent: Any | None = None, two: bool = False, from_kall: bool = True\n    ) -> Self: ...\n    name: Any\n    parent: Any\n    from_kall: Any\n    def __init__(\n        self,\n        value: _CallValue = (),\n        name: str | None = None,\n        parent: Any | 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: Any\n    call_args_list: _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: ...\nclass _patch_default_new(_patch[MagicMock | AsyncMock]):\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.\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__(\n        self,\n        target: 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: Any,\n    ) -> _patch[_T]: ...\n    @overload\n    def __call__(\n        self,\n        target: str,\n        *,\n        spec: Any | None = ...,\n        create: bool = ...,\n        spec_set: Any | None = ...,\n        autospec: Any | None = ...,\n        new_callable: Any | None = ...,\n        **kwargs: Any,\n    ) -> _patch_default_new: ...\n    @overload\n    @staticmethod\n    def object(\n        target: 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: Any,\n    ) -> _patch[_T]: ...\n    @overload\n    @staticmethod\n    def object(\n        target: Any,\n        attribute: str,\n        *,\n        spec: Any | None = ...,\n        create: bool = ...,\n        spec_set: Any | None = ...,\n        autospec: Any | None = ...,\n        new_callable: Any | None = ...,\n        **kwargs: Any,\n    ) -> _patch[MagicMock | AsyncMock]: ...\n    @staticmethod\n    def multiple(\n        target: Any,\n        spec: Any | None = ...,\n        create: bool = ...,\n        spec_set: Any | None = ...,\n        autospec: Any | None = ...,\n        new_callable: Any | None = ...,\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\nclass _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\nfrom typing_extensions import Never, TypeAlias\nfrom warnings import _ActionKind\n\n_ResultClassType: TypeAlias = Callable[[_TextTestStream, bool, int], TextTestResult[Any]]\n\nclass _SupportsWriteAndFlush(SupportsWrite[str], SupportsFlush, Protocol): ...\n\n# All methods used by unittest.runner.TextTestResult's stream\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, TypeVar\nfrom typing_extensions import TypeAlias\n\n_T = TypeVar(\"_T\")\n_Mismatch: TypeAlias = tuple[_T, _T, int]\n\n_MAX_LENGTH: Final[int]\n_PLACEHOLDER_LEN: Final[int]\n_MIN_BEGIN_LEN: Final[int]\n_MIN_END_LEN: Final[int]\n_MIN_COMMON_LEN: Final[int]\n_MIN_DIFF_LEN: Final[int]\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: Any, y: Any) -> int: ...\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    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    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 Callable, Iterable, Mapping, Sequence\nfrom typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload\nfrom typing_extensions import TypeAlias\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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: list[str]\nuses_netloc: list[str]\nuses_params: list[str]\nnon_hierarchical: list[str]\nuses_query: list[str]\nuses_fragment: list[str]\nscheme_chars: str\nif sys.version_info < (3, 11):\n    MAX_CACHE_SIZE: int\n\nclass _ResultMixinStr:\n    def encode(self, encoding: str = \"ascii\", errors: str = \"strict\") -> _ResultMixinBytes: ...\n\nclass _ResultMixinBytes:\n    def decode(self, encoding: str = \"ascii\", errors: str = \"strict\") -> _ResultMixinStr: ...\n\nclass _NetlocResultMixinBase(Generic[AnyStr]):\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    if sys.version_info >= (3, 9):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ...\nclass _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ...\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: ...\n\nif sys.version_info >= (3, 9):\n    def unquote(string: str | bytes, encoding: str = \"utf-8\", errors: str = \"replace\") -> str: ...\n\nelse:\n    def unquote(string: str, encoding: str = \"utf-8\", errors: str = \"replace\") -> str: ...\n\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_Q = TypeVar(\"_Q\", bound=str | Iterable[int])\n_QueryType: TypeAlias = (\n    Mapping[Any, Any] | Mapping[Any, Sequence[Any]] | Sequence[tuple[Any, Any]] | Sequence[tuple[Any, Sequence[Any]]]\n)\n\n@overload\ndef urlencode(\n    query: _QueryType,\n    doseq: bool = False,\n    safe: str = \"\",\n    encoding: str | None = None,\n    errors: str | None = None,\n    quote_via: Callable[[AnyStr, str, str, str], str] = ...,\n) -> str: ...\n@overload\ndef urlencode(\n    query: _QueryType,\n    doseq: bool,\n    safe: _Q,\n    encoding: str | None = None,\n    errors: str | None = None,\n    quote_via: Callable[[AnyStr, _Q, str, str], str] = ...,\n) -> str: ...\n@overload\ndef urlencode(\n    query: _QueryType,\n    doseq: bool = False,\n    *,\n    safe: _Q,\n    encoding: str | None = None,\n    errors: str | None = None,\n    quote_via: Callable[[AnyStr, _Q, str, str], str] = ...,\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, NoReturn, Protocol, TypeVar, overload\nfrom typing_extensions import TypeAlias\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    \"URLopener\",\n    \"FancyURLopener\",\n    \"HTTPSHandler\",\n]\n\n_T = TypeVar(\"_T\")\n_UrlopenRet: TypeAlias = Any\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    def urlopen(\n        url: str | Request,\n        data: _DataType | None = None,\n        timeout: float | None = ...,\n        *,\n        cafile: str | None = None,\n        capath: str | None = None,\n        cadefault: bool = False,\n        context: ssl.SSLContext | None = None,\n    ) -> _UrlopenRet: ...\n\ndef install_opener(opener: OpenerDirector) -> None: ...\ndef build_opener(*handlers: BaseHandler | Callable[[], BaseHandler]) -> OpenerDirector: ...\n\nif sys.platform == \"win32\":\n    from nturl2path import pathname2url as pathname2url, url2pathname as url2pathname\nelse:\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\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\nclass 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\nclass 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 sys\nimport 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\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\n    if sys.version_info >= (3, 9):\n        @property\n        def status(self) -> int | None: ...\n\n    def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = None) -> None: ...\n    def geturl(self) -> str: ...\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_extensions import 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    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 = ...,\n    ) -> None: ...\n    @property\n    def is_safe(self) -> SafeUUID: ...\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 int(self) -> builtins.int: ...\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 __str__(self) -> builtins.str: ...\n\nif sys.version_info >= (3, 9):\n    def getnode() -> int: ...\n\nelse:\n    def getnode(*, getters: Unused = None) -> int: ...  # undocumented\n\ndef uuid1(node: int | None = None, clock_seq: 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\nNAMESPACE_DNS: UUID\nNAMESPACE_URL: UUID\nNAMESPACE_OID: UUID\nNAMESPACE_X500: UUID\nRESERVED_NCS: str\nRFC_4122: str\nRESERVED_MICROSOFT: str\nRESERVED_FUTURE: str\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, TypeVar, overload\nfrom typing_extensions import LiteralString, TypeAlias\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 = TypeVar(\"_W\", bound=list[WarningMessage] | None)\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]):\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: catch_warnings[list[WarningMessage] | None],\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__(\n            self: catch_warnings[list[WarningMessage] | None], *, record: bool, module: ModuleType | None = None\n        ) -> None: ...\n\n    def __enter__(self) -> _W: ...\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\nif sys.version_info >= (3, 9):\n    __all__ = [\"open\", \"Error\", \"Wave_read\", \"Wave_write\"]\nelse:\n    __all__ = [\"open\", \"openfp\", \"Error\", \"Wave_read\", \"Wave_write\"]\n\n_File: TypeAlias = str | IO[bytes]\n\nclass Error(Exception): ...\n\nWAVE_FORMAT_PCM: Final = 1\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    @deprecated(\"Deprecated in Python 3.13; removal scheduled for Python 3.15\")\n    def getmarkers(self) -> None: ...\n    @deprecated(\"Deprecated in Python 3.13; removal scheduled for Python 3.15\")\n    def getmark(self, id: Any) -> NoReturn: ...\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    @deprecated(\"Deprecated in Python 3.13; removal scheduled for Python 3.15\")\n    def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ...\n    @deprecated(\"Deprecated in Python 3.13; removal scheduled for Python 3.15\")\n    def getmark(self, id: Any) -> NoReturn: ...\n    @deprecated(\"Deprecated in Python 3.13; removal scheduled for Python 3.15\")\n    def getmarkers(self) -> None: ...\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\nif sys.version_info < (3, 9):\n    openfp = open\n"
  },
  {
    "path": "mypy/typeshed/stdlib/weakref.pyi",
    "content": "import sys\nfrom _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 typing import Any, ClassVar, Generic, TypeVar, final, overload\nfrom typing_extensions import ParamSpec, Self\n\nif sys.version_info >= (3, 9):\n    from types import GenericAlias\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\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    if sys.version_info >= (3, 9):\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    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: _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    if sys.version_info >= (3, 9):\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    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: _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    if sys.version_info >= (3, 9):\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    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        @deprecated(\"Deprecated in 3.11, to be removed in 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    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, reserved: int = 0, access: int = 131097) -> HKEYType: ...\n    def OpenKeyEx(key: _KeyType, sub_key: str, 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, 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: int\n    HKEY_CURRENT_USER: int\n    HKEY_LOCAL_MACHINE: int\n    HKEY_USERS: int\n    HKEY_PERFORMANCE_DATA: int\n    HKEY_CURRENT_CONFIG: int\n    HKEY_DYN_DATA: 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\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    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 overload\nfrom typing_extensions import TypeAlias\n\n_HeaderList: TypeAlias = list[tuple[str, str]]\n\ntspecials: 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 TypeVar, overload\n\nfrom .handlers import SimpleHandler\n\n__all__ = [\"WSGIServer\", \"WSGIRequestHandler\", \"demo_app\", \"make_server\"]\n\nserver_version: str  # undocumented\nsys_version: str  # undocumented\nsoftware_version: 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": "class NodeFilter:\n    FILTER_ACCEPT: int\n    FILTER_REJECT: int\n    FILTER_SKIP: int\n\n    SHOW_ALL: int\n    SHOW_ELEMENT: int\n    SHOW_ATTRIBUTE: int\n    SHOW_TEXT: int\n    SHOW_CDATA_SECTION: int\n    SHOW_ENTITY_REFERENCE: int\n    SHOW_ENTITY: int\n    SHOW_PROCESSING_INSTRUCTION: int\n    SHOW_COMMENT: int\n    SHOW_DOCUMENT: int\n    SHOW_DOCUMENT_TYPE: int\n    SHOW_DOCUMENT_FRAGMENT: int\n    SHOW_NOTATION: int\n    def acceptNode(self, node) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/__init__.pyi",
    "content": "from typing import Any, Final\n\nfrom .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation\n\nclass Node:\n    ELEMENT_NODE: int\n    ATTRIBUTE_NODE: int\n    TEXT_NODE: int\n    CDATA_SECTION_NODE: int\n    ENTITY_REFERENCE_NODE: int\n    ENTITY_NODE: int\n    PROCESSING_INSTRUCTION_NODE: int\n    COMMENT_NODE: int\n    DOCUMENT_NODE: int\n    DOCUMENT_TYPE_NODE: int\n    DOCUMENT_FRAGMENT_NODE: int\n    NOTATION_NODE: int\n\n# ExceptionCode\nINDEX_SIZE_ERR: Final[int]\nDOMSTRING_SIZE_ERR: Final[int]\nHIERARCHY_REQUEST_ERR: Final[int]\nWRONG_DOCUMENT_ERR: Final[int]\nINVALID_CHARACTER_ERR: Final[int]\nNO_DATA_ALLOWED_ERR: Final[int]\nNO_MODIFICATION_ALLOWED_ERR: Final[int]\nNOT_FOUND_ERR: Final[int]\nNOT_SUPPORTED_ERR: Final[int]\nINUSE_ATTRIBUTE_ERR: Final[int]\nINVALID_STATE_ERR: Final[int]\nSYNTAX_ERR: Final[int]\nINVALID_MODIFICATION_ERR: Final[int]\nNAMESPACE_ERR: Final[int]\nINVALID_ACCESS_ERR: Final[int]\nVALIDATION_ERR: Final[int]\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): ...\nclass DomstringSizeErr(DOMException): ...\nclass HierarchyRequestErr(DOMException): ...\nclass WrongDocumentErr(DOMException): ...\nclass InvalidCharacterErr(DOMException): ...\nclass NoDataAllowedErr(DOMException): ...\nclass NoModificationAllowedErr(DOMException): ...\nclass NotFoundErr(DOMException): ...\nclass NotSupportedErr(DOMException): ...\nclass InuseAttributeErr(DOMException): ...\nclass InvalidStateErr(DOMException): ...\nclass SyntaxErr(DOMException): ...\nclass InvalidModificationErr(DOMException): ...\nclass NamespaceErr(DOMException): ...\nclass InvalidAccessErr(DOMException): ...\nclass ValidationErr(DOMException): ...\n\nclass UserDataHandler:\n    NODE_CLONED: int\n    NODE_IMPORTED: int\n    NODE_DELETED: int\n    NODE_RENAMED: int\n\nXML_NAMESPACE: Final[str]\nXMLNS_NAMESPACE: Final[str]\nXHTML_NAMESPACE: Final[str]\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 Incomplete, ReadableBuffer, SupportsRead\nfrom typing import Any, NoReturn\nfrom xml.dom.minidom import Document, DOMImplementation, Node, TypeInfo\nfrom xml.dom.xmlbuilder import DOMBuilderFilter, Options\n\nTEXT_NODE = Node.TEXT_NODE\nCDATA_SECTION_NODE = Node.CDATA_SECTION_NODE\nDOCUMENT_NODE = Node.DOCUMENT_NODE\nFILTER_ACCEPT = DOMBuilderFilter.FILTER_ACCEPT\nFILTER_REJECT = DOMBuilderFilter.FILTER_REJECT\nFILTER_SKIP = DOMBuilderFilter.FILTER_SKIP\nFILTER_INTERRUPT = DOMBuilderFilter.FILTER_INTERRUPT\ntheDOMImplementation: DOMImplementation | None\n\nclass ElementInfo:\n    tagName: Incomplete\n    def __init__(self, tagName, model: Incomplete | None = None) -> None: ...\n    def getAttributeType(self, aname) -> TypeInfo: ...\n    def getAttributeTypeNS(self, namespaceURI, localName) -> TypeInfo: ...\n    def isElementContent(self) -> bool: ...\n    def isEmpty(self) -> bool: ...\n    def isId(self, aname) -> bool: ...\n    def isIdNS(self, euri, ename, auri, aname) -> bool: ...\n\nclass ExpatBuilder:\n    document: Document  # Created in self.reset()\n    curNode: Incomplete  # Created in self.reset()\n    def __init__(self, options: Options | None = None) -> None: ...\n    def createParser(self): ...\n    def getParser(self): ...\n    def reset(self) -> None: ...\n    def install(self, parser) -> None: ...\n    def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> Document: ...\n    def parseString(self, string: str | ReadableBuffer) -> Document: ...\n    def start_doctype_decl_handler(self, doctypeName, systemId, publicId, has_internal_subset) -> None: ...\n    def end_doctype_decl_handler(self) -> None: ...\n    def pi_handler(self, target, data) -> None: ...\n    def character_data_handler_cdata(self, data) -> None: ...\n    def character_data_handler(self, data) -> None: ...\n    def start_cdata_section_handler(self) -> None: ...\n    def end_cdata_section_handler(self) -> None: ...\n    def entity_decl_handler(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName) -> None: ...\n    def notation_decl_handler(self, notationName, base, systemId, publicId) -> None: ...\n    def comment_handler(self, data) -> None: ...\n    def external_entity_ref_handler(self, context, base, systemId, publicId) -> int: ...\n    def first_element_handler(self, name, attributes) -> None: ...\n    def start_element_handler(self, name, attributes) -> None: ...\n    def end_element_handler(self, name) -> None: ...\n    def element_decl_handler(self, name, model) -> None: ...\n    def attlist_decl_handler(self, elem, name, type, default, required) -> None: ...\n    def xml_decl_handler(self, version, encoding, standalone) -> None: ...\n\nclass FilterVisibilityController:\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    def __init__(self, builder) -> None: ...\n\nclass Rejecter(FilterCrutch):\n    def start_element_handler(self, *args: Any) -> None: ...\n    def end_element_handler(self, *args: Any) -> None: ...\n\nclass Skipper(FilterCrutch):\n    def start_element_handler(self, *args: Any) -> None: ...\n    def end_element_handler(self, *args: Any) -> None: ...\n\nclass FragmentBuilder(ExpatBuilder):\n    fragment: Incomplete | None\n    originalDocument: Incomplete\n    context: Incomplete\n    def __init__(self, context, options: Options | None = None) -> None: ...\n\nclass Namespaces:\n    def createParser(self): ...\n    def install(self, parser) -> None: ...\n    def start_namespace_decl_handler(self, prefix, uri) -> None: ...\n    def start_element_handler(self, name, attributes) -> None: ...\n    def end_element_handler(self, name) -> None: ...\n\nclass ExpatBuilderNS(Namespaces, ExpatBuilder): ...\nclass FragmentBuilderNS(Namespaces, FragmentBuilder): ...\nclass ParseEscape(Exception): ...\n\nclass InternalSubsetExtractor(ExpatBuilder):\n    subset: Any | None\n    def getSubset(self) -> Any | None: ...\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(self, name, publicId, systemId, has_internal_subset) -> None: ...  # type: ignore[override]\n    def end_doctype_decl_handler(self) -> NoReturn: ...\n    def start_element_handler(self, name, attrs) -> NoReturn: ...\n\ndef parse(file: str | SupportsRead[ReadableBuffer | str], namespaces: bool = True): ...\ndef parseString(string: str | ReadableBuffer, namespaces: bool = True): ...\ndef parseFragment(file, context, namespaces: bool = True): ...\ndef parseFragmentString(string: str, context, namespaces: bool = True): ...\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    @property\n    def length(self) -> int: ...\n    def item(self, index: int) -> _T | None: ...\n\nclass EmptyNodeList(tuple[()]):\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 sys\nimport xml.dom\nfrom _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite\nfrom typing import ClassVar, Literal, NoReturn, TypeVar, overload\nfrom typing_extensions import Self\nfrom xml.dom.minicompat import NodeList\nfrom xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS\nfrom xml.sax.xmlreader import XMLReader\n\n_N = TypeVar(\"_N\", bound=Node)\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: ...\ndef getDOMImplementation(features=None) -> DOMImplementation | None: ...\n\nclass Node(xml.dom.Node):\n    namespaceURI: str | None\n    parentNode: Incomplete\n    ownerDocument: Incomplete\n    nextSibling: Incomplete\n    previousSibling: Incomplete\n    prefix: Incomplete\n    @property\n    def firstChild(self) -> Node | None: ...\n    @property\n    def lastChild(self) -> Node | None: ...\n    @property\n    def localName(self) -> str | None: ...\n    def __bool__(self) -> Literal[True]: ...\n    if sys.version_info >= (3, 9):\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    else:\n        @overload\n        def toxml(self, encoding: str) -> bytes: ...\n        @overload\n        def toxml(self, encoding: 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        ) -> 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        ) -> 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\n            *,\n            encoding: str,\n        ) -> bytes: ...\n\n    def hasChildNodes(self) -> bool: ...\n    def insertBefore(self, newChild, refChild): ...\n    def appendChild(self, node: _N) -> _N: ...\n    def replaceChild(self, newChild, oldChild): ...\n    def removeChild(self, oldChild): ...\n    def normalize(self) -> None: ...\n    def cloneNode(self, deep): ...\n    def isSupported(self, feature, version): ...\n    def isSameNode(self, other): ...\n    def getInterface(self, feature): ...\n    def getUserData(self, key): ...\n    def setUserData(self, key, data, handler): ...\n    childNodes: Incomplete\n    def unlink(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, et, ev, tb) -> None: ...\n\nclass DocumentFragment(Node):\n    nodeType: int\n    nodeName: str\n    nodeValue: Incomplete\n    attributes: Incomplete\n    parentNode: Incomplete\n    childNodes: Incomplete\n    def __init__(self) -> None: ...\n\nclass Attr(Node):\n    name: str\n    nodeType: int\n    attributes: Incomplete\n    specified: bool\n    ownerElement: Incomplete\n    namespaceURI: str | None\n    childNodes: Incomplete\n    nodeName: Incomplete\n    nodeValue: str\n    value: str\n    prefix: Incomplete\n    def __init__(\n        self, qName: str, namespaceURI: str | None = None, localName: str | None = None, prefix: Incomplete | None = None\n    ) -> None: ...\n    def unlink(self) -> None: ...\n    @property\n    def isId(self) -> bool: ...\n    @property\n    def schemaType(self): ...\n\nclass NamedNodeMap:\n    def __init__(self, attrs, attrsNS, ownerElement) -> None: ...\n    def item(self, index): ...\n    def items(self): ...\n    def itemsNS(self): ...\n    def __contains__(self, key): ...\n    def keys(self): ...\n    def keysNS(self): ...\n    def values(self): ...\n    def get(self, name: str, value: Incomplete | None = 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: tuple[str, str | None] | str): ...\n    def __setitem__(self, attname: str, value: Attr | str) -> None: ...\n    def getNamedItem(self, name: str) -> Attr | None: ...\n    def getNamedItemNS(self, namespaceURI: str, localName: str | None) -> Attr | None: ...\n    def removeNamedItem(self, name: str) -> Attr: ...\n    def removeNamedItemNS(self, namespaceURI: str, localName: str | None): ...\n    def setNamedItem(self, node: Attr) -> Attr: ...\n    def setNamedItemNS(self, node: Attr) -> Attr: ...\n    def __delitem__(self, attname_or_tuple: tuple[str, str | None] | str) -> None: ...\n    @property\n    def length(self) -> int: ...\n\nAttributeList = NamedNodeMap\n\nclass TypeInfo:\n    namespace: Incomplete | None\n    name: str\n    def __init__(self, namespace: Incomplete | None, name: str) -> None: ...\n\nclass Element(Node):\n    nodeType: int\n    nodeValue: Incomplete\n    schemaType: Incomplete\n    parentNode: Incomplete\n    tagName: str\n    nodeName: str\n    prefix: Incomplete\n    namespaceURI: str | None\n    childNodes: Incomplete\n    nextSibling: Incomplete\n    def __init__(\n        self, tagName, namespaceURI: str | None = None, prefix: Incomplete | None = None, localName: Incomplete | None = None\n    ) -> None: ...\n    def unlink(self) -> None: ...\n    def getAttribute(self, attname: str) -> str: ...\n    def getAttributeNS(self, namespaceURI: str, localName): ...\n    def setAttribute(self, attname: str, value: str) -> None: ...\n    def setAttributeNS(self, namespaceURI: str, qualifiedName: str, value) -> None: ...\n    def getAttributeNode(self, attrname: str): ...\n    def getAttributeNodeNS(self, namespaceURI: str, localName): ...\n    def setAttributeNode(self, attr): ...\n    setAttributeNodeNS: Incomplete\n    def removeAttribute(self, name: str) -> None: ...\n    def removeAttributeNS(self, namespaceURI: str, localName) -> None: ...\n    def removeAttributeNode(self, node): ...\n    removeAttributeNodeNS: Incomplete\n    def hasAttribute(self, name: str) -> bool: ...\n    def hasAttributeNS(self, namespaceURI: str, localName) -> bool: ...\n    def getElementsByTagName(self, name: str) -> NodeList[Element]: ...\n    def getElementsByTagNameNS(self, namespaceURI: str, 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) -> None: ...\n    def setIdAttributeNS(self, namespaceURI: str, localName) -> None: ...\n    def setIdAttributeNode(self, idAttr) -> None: ...\n    @property\n    def attributes(self) -> NamedNodeMap: ...\n\nclass Childless:\n    attributes: Incomplete\n    childNodes: Incomplete\n    firstChild: Incomplete\n    lastChild: Incomplete\n    def appendChild(self, node) -> NoReturn: ...\n    def hasChildNodes(self) -> bool: ...\n    def insertBefore(self, newChild, refChild) -> NoReturn: ...\n    def removeChild(self, oldChild) -> NoReturn: ...\n    def normalize(self) -> None: ...\n    def replaceChild(self, newChild, oldChild) -> NoReturn: ...\n\nclass ProcessingInstruction(Childless, Node):\n    nodeType: int\n    target: Incomplete\n    data: Incomplete\n    def __init__(self, target, data) -> None: ...\n    nodeValue: Incomplete\n    nodeName: Incomplete\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass CharacterData(Childless, Node):\n    ownerDocument: Incomplete\n    previousSibling: Incomplete\n    def __init__(self) -> None: ...\n    def __len__(self) -> int: ...\n    data: str\n    nodeValue: Incomplete\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    @property\n    def length(self) -> int: ...\n\nclass Text(CharacterData):\n    nodeType: int\n    nodeName: str\n    attributes: Incomplete\n    data: Incomplete\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) -> Self | None: ...\n    @property\n    def isWhitespaceInElementContent(self) -> bool: ...\n    @property\n    def wholeText(self) -> str: ...\n\nclass Comment(CharacterData):\n    nodeType: int\n    nodeName: str\n    def __init__(self, data) -> None: ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass CDATASection(Text):\n    nodeType: int\n    nodeName: str\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass ReadOnlySequentialNamedNodeMap:\n    def __init__(self, seq=()) -> None: ...\n    def __len__(self) -> int: ...\n    def getNamedItem(self, name): ...\n    def getNamedItemNS(self, namespaceURI: str, localName): ...\n    def __getitem__(self, name_or_tuple): ...\n    def item(self, index): ...\n    def removeNamedItem(self, name) -> None: ...\n    def removeNamedItemNS(self, namespaceURI: str, localName) -> None: ...\n    def setNamedItem(self, node) -> None: ...\n    def setNamedItemNS(self, node) -> None: ...\n    @property\n    def length(self) -> int: ...\n\nclass Identified:\n    publicId: str | None\n    systemId: str | None\n\nclass DocumentType(Identified, Childless, Node):\n    nodeType: int\n    nodeValue: Incomplete\n    name: Incomplete\n    internalSubset: Incomplete\n    entities: Incomplete\n    notations: Incomplete\n    nodeName: Incomplete\n    def __init__(self, qualifiedName: str) -> None: ...\n    def cloneNode(self, deep): ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass Entity(Identified, Node):\n    attributes: Incomplete\n    nodeType: int\n    nodeValue: Incomplete\n    actualEncoding: Incomplete\n    encoding: Incomplete\n    version: Incomplete\n    nodeName: Incomplete\n    notationName: Incomplete\n    childNodes: Incomplete\n    def __init__(self, name, publicId, systemId, notation) -> None: ...\n    def appendChild(self, newChild) -> NoReturn: ...\n    def insertBefore(self, newChild, refChild) -> NoReturn: ...\n    def removeChild(self, oldChild) -> NoReturn: ...\n    def replaceChild(self, newChild, oldChild) -> NoReturn: ...\n\nclass Notation(Identified, Childless, Node):\n    nodeType: int\n    nodeValue: Incomplete\n    nodeName: Incomplete\n    def __init__(self, name, publicId, systemId) -> 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    tagName: Incomplete\n    def __init__(self, name) -> None: ...\n    def getAttributeType(self, aname): ...\n    def getAttributeTypeNS(self, namespaceURI: str, localName): ...\n    def isElementContent(self): ...\n    def isEmpty(self): ...\n    def isId(self, aname): ...\n    def isIdNS(self, namespaceURI: str, localName): ...\n\nclass Document(Node, DocumentLS):\n    implementation: Incomplete\n    nodeType: int\n    nodeName: str\n    nodeValue: Incomplete\n    attributes: Incomplete\n    parentNode: Incomplete\n    previousSibling: Incomplete\n    nextSibling: Incomplete\n    actualEncoding: Incomplete\n    encoding: str | None\n    standalone: bool | None\n    version: Incomplete\n    strictErrorChecking: bool\n    errorHandler: Incomplete\n    documentURI: Incomplete\n    doctype: DocumentType | None\n    childNodes: Incomplete\n    def __init__(self) -> None: ...\n    def appendChild(self, node: _N) -> _N: ...\n    documentElement: Incomplete\n    def removeChild(self, oldChild): ...\n    def unlink(self) -> None: ...\n    def cloneNode(self, deep): ...\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, data): ...\n    def createAttribute(self, qName) -> Attr: ...\n    def createElementNS(self, namespaceURI: str, qualifiedName: str): ...\n    def createAttributeNS(self, namespaceURI: str, 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, localName: str) -> NodeList[Element]: ...\n    def isSupported(self, feature: str, version: str | None) -> bool: ...\n    def importNode(self, node, deep): ...\n    if sys.version_info >= (3, 9):\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    else:\n        def writexml(\n            self,\n            writer: SupportsWrite[str],\n            indent: str = \"\",\n            addindent: str = \"\",\n            newl: str = \"\",\n            encoding: Incomplete | None = None,\n        ) -> None: ...\n\n    def renameNode(self, n, namespaceURI: str, name): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/pulldom.pyi",
    "content": "import sys\nfrom _typeshed import Incomplete, SupportsRead\nfrom collections.abc import Sequence\nfrom typing import Final, Literal\nfrom typing_extensions import TypeAlias\nfrom xml.dom.minidom import Document, DOMImplementation, Element, Text\nfrom xml.sax.handler import ContentHandler\nfrom xml.sax.xmlreader import 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_DocumentFactory: TypeAlias = DOMImplementation | None\n_Node: TypeAlias = Document | Element | Text\n\n_Event: TypeAlias = tuple[\n    Literal[\n        Literal[\"START_ELEMENT\"],\n        Literal[\"END_ELEMENT\"],\n        Literal[\"COMMENT\"],\n        Literal[\"START_DOCUMENT\"],\n        Literal[\"END_DOCUMENT\"],\n        Literal[\"PROCESSING_INSTRUCTION\"],\n        Literal[\"IGNORABLE_WHITESPACE\"],\n        Literal[\"CHARACTERS\"],\n    ],\n    _Node,\n]\n\nclass PullDOM(ContentHandler):\n    document: Document | None\n    documentFactory: _DocumentFactory\n    firstEvent: Incomplete\n    lastEvent: Incomplete\n    elementStack: Sequence[Incomplete]\n    pending_events: Sequence[Incomplete]\n    def __init__(self, documentFactory: _DocumentFactory = None) -> None: ...\n    def pop(self) -> Element: ...\n    def setDocumentLocator(self, locator) -> None: ...\n    def startPrefixMapping(self, prefix, uri) -> None: ...\n    def endPrefixMapping(self, prefix) -> None: ...\n    def startElementNS(self, name, tagName, attrs) -> None: ...\n    def endElementNS(self, name, tagName) -> None: ...\n    def startElement(self, name, attrs) -> None: ...\n    def endElement(self, name) -> None: ...\n    def comment(self, s) -> None: ...\n    def processingInstruction(self, target, data) -> None: ...\n    def ignorableWhitespace(self, chars) -> None: ...\n    def characters(self, chars) -> None: ...\n    def startDocument(self) -> None: ...\n    def buildDocument(self, uri, tagname): ...\n    def endDocument(self) -> None: ...\n    def clear(self) -> None: ...\n\nclass ErrorHandler:\n    def warning(self, exception) -> None: ...\n    def error(self, exception) -> None: ...\n    def fatalError(self, exception) -> None: ...\n\nclass DOMEventStream:\n    stream: SupportsRead[bytes] | SupportsRead[str]\n    parser: XMLReader\n    bufsize: int\n    def __init__(self, stream: SupportsRead[bytes] | SupportsRead[str], parser: XMLReader, bufsize: int) -> None: ...\n    pulldom: Incomplete\n    if sys.version_info < (3, 11):\n        def __getitem__(self, pos): ...\n\n    def __next__(self): ...\n    def __iter__(self): ...\n    def getEvent(self) -> _Event: ...\n    def expandNode(self, node: _Node) -> None: ...\n    def reset(self) -> None: ...\n    def clear(self) -> None: ...\n\nclass SAX2DOM(PullDOM):\n    def startElementNS(self, name, tagName, attrs) -> None: ...\n    def startElement(self, name, attrs) -> None: ...\n    def processingInstruction(self, target, data) -> None: ...\n    def ignorableWhitespace(self, chars) -> None: ...\n    def characters(self, chars) -> None: ...\n\ndefault_bufsize: int\n\ndef parse(\n    stream_or_string: str | SupportsRead[bytes] | SupportsRead[str], parser: XMLReader | None = None, 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 Incomplete, Unused\nfrom typing import Any, Literal, NoReturn\nfrom typing_extensions import TypeAlias\nfrom urllib.request import OpenerDirector\nfrom xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS\nfrom xml.dom.minidom import Node\n\n__all__ = [\"DOMBuilder\", \"DOMEntityResolver\", \"DOMInputSource\"]\n\n# UNKNOWN TYPES:\n# - `Options.errorHandler`.\n#       The same as `_DOMBuilderErrorHandlerType`?\n#       Maybe `xml.sax.handler.ErrorHandler`?\n# - Return type of DOMBuilder.getFeature().\n#       We could get rid of the `Incomplete` if we knew more\n#       about `Options.errorHandler`.\n\n# ALIASES REPRESENTING MORE UNKNOWN TYPES:\n\n# probably the same as `Options.errorHandler`?\n# Maybe `xml.sax.handler.ErrorHandler`?\n_DOMBuilderErrorHandlerType: TypeAlias = Incomplete | None\n# probably some kind of IO...\n_DOMInputSourceCharacterStreamType: TypeAlias = Incomplete | None\n# probably a string??\n_DOMInputSourceStringDataType: TypeAlias = Incomplete | None\n# probably a string??\n_DOMInputSourceEncodingType: TypeAlias = Incomplete | None\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: Any | None\n    filter: DOMBuilderFilter | None  # a guess, but seems likely\n\nclass DOMBuilder:\n    entityResolver: DOMEntityResolver | None  # a guess, but seems likely\n    errorHandler: _DOMBuilderErrorHandlerType\n    filter: DOMBuilderFilter | None  # a guess, but seems likely\n    ACTION_REPLACE: Literal[1]\n    ACTION_APPEND_AS_CHILDREN: Literal[2]\n    ACTION_INSERT_AFTER: Literal[3]\n    ACTION_INSERT_BEFORE: Literal[4]\n    def setFeature(self, name: str, state: int) -> None: ...\n    def supportsFeature(self, name: str) -> bool: ...\n    def canSetFeature(self, name: str, state: int) -> 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) -> ExpatBuilder | ExpatBuilderNS: ...\n    def parse(self, input: DOMInputSource) -> ExpatBuilder | ExpatBuilderNS: ...\n    # `input` and `cnode` argtypes for `parseWithContext` are unknowable\n    # as the function does nothing with them, and always raises an exception.\n    # But `input` is *probably* `DOMInputSource`?\n    def parseWithContext(self, input: Unused, cnode: Unused, action: Literal[1, 2, 3, 4]) -> NoReturn: ...\n\nclass DOMEntityResolver:\n    def resolveEntity(self, publicId: str | None, systemId: str) -> DOMInputSource: ...\n\nclass DOMInputSource:\n    byteStream: OpenerDirector | None\n    characterStream: _DOMInputSourceCharacterStreamType\n    stringData: _DOMInputSourceStringDataType\n    encoding: _DOMInputSourceEncodingType\n    publicId: str | None\n    systemId: str | None\n    baseURI: str | None\n\nclass DOMBuilderFilter:\n    FILTER_ACCEPT: Literal[1]\n    FILTER_REJECT: Literal[2]\n    FILTER_SKIP: Literal[3]\n    FILTER_INTERRUPT: Literal[4]\n    whatToShow: int\n    def acceptNode(self, element: Unused) -> Literal[1]: ...\n    def startContainer(self, element: Unused) -> Literal[1]: ...\n\nclass DocumentLS:\n    async_: bool\n    def abort(self) -> NoReturn: ...\n    # `load()` and `loadXML()` always raise exceptions\n    # so the argtypes of `uri` and `source` are unknowable.\n    # `source` is *probably* `DOMInputSource`?\n    # `uri` is *probably* a str? (see DOMBuilder.parseURI())\n    def load(self, uri: Unused) -> NoReturn: ...\n    def loadXML(self, source: Unused) -> NoReturn: ...\n    def saveXML(self, snode: Node | None) -> str: ...\n\nclass DOMImplementationLS:\n    MODE_SYNCHRONOUS: Literal[1]\n    MODE_ASYNCHRONOUS: Literal[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": "import sys\nfrom _typeshed import FileDescriptorOrPath\nfrom collections.abc import Callable\nfrom typing import Final\nfrom xml.etree.ElementTree import Element\n\nXINCLUDE: Final[str]\nXINCLUDE_INCLUDE: Final[str]\nXINCLUDE_FALLBACK: Final[str]\n\nif sys.version_info >= (3, 9):\n    DEFAULT_MAX_INCLUSION_DEPTH: Final = 6\n\nclass FatalIncludeError(SyntaxError): ...\n\ndef default_loader(href: FileDescriptorOrPath, parse: str, encoding: str | None = None) -> str | Element: ...\n\n# TODO: loader is of type default_loader ie it takes a callable that has the\n# same signature as default_loader. But default_loader has a keyword argument\n# Which can't be represented using Callable...\nif sys.version_info >= (3, 9):\n    def include(\n        elem: Element, loader: Callable[..., str | Element] | None = None, base_url: str | None = None, max_depth: int | None = 6\n    ) -> None: ...\n\n    class LimitedRecursiveIncludeError(FatalIncludeError): ...\n\nelse:\n    def include(elem: Element, loader: Callable[..., str | Element] | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/etree/ElementPath.pyi",
    "content": "from collections.abc import Callable, Generator\nfrom re import Pattern\nfrom typing import TypeVar\nfrom typing_extensions import TypeAlias\nfrom xml.etree.ElementTree import Element\n\nxpath_tokenizer_re: Pattern[str]\n\n_Token: TypeAlias = tuple[str, str]\n_Next: TypeAlias = Callable[[], _Token]\n_Callback: TypeAlias = Callable[[_SelectorContext, list[Element]], Generator[Element, None, None]]\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: ...\ndef prepare_parent(next: _Next, token: _Token) -> _Callback: ...\ndef prepare_predicate(next: _Next, token: _Token) -> _Callback: ...\n\nops: dict[str, Callable[[_Next, _Token], _Callback]]\n\nclass _SelectorContext:\n    parent_map: dict[Element, Element] | None\n    root: Element\n    def __init__(self, root: Element) -> None: ...\n\n_T = TypeVar(\"_T\")\n\ndef iterfind(elem: Element, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ...\ndef find(elem: Element, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ...\ndef findall(elem: Element, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ...\ndef findtext(elem: Element, path: str, default: _T | None = None, 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, Literal, SupportsIndex, TypeVar, overload\nfrom typing_extensions import TypeAlias, TypeGuard, deprecated\n\n__all__ = [\n    \"C14NWriterTarget\",\n    \"Comment\",\n    \"dump\",\n    \"Element\",\n    \"ElementTree\",\n    \"canonicalize\",\n    \"fromstring\",\n    \"fromstringlist\",\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\nif sys.version_info >= (3, 9):\n    __all__ += [\"indent\"]\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\nclass Element:\n    tag: str\n    attrib: dict[str, str]\n    text: str | None\n    tail: str | None\n    def __init__(self, tag: str, attrib: dict[str, str] = ..., **extra: str) -> None: ...\n    def append(self, subelement: Element, /) -> None: ...\n    def clear(self) -> None: ...\n    def extend(self, elements: Iterable[Element], /) -> 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, /) -> None: ...\n    def items(self) -> ItemsView[str, str]: ...\n    def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ...\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: str, attrib: dict[str, str], /) -> Element: ...\n    def remove(self, subelement: Element, /) -> None: ...\n    def set(self, key: str, value: str, /) -> None: ...\n    def __copy__(self) -> Element: ...  # 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, /) -> 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, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice, value: Iterable[Element], /) -> 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    if sys.version_info < (3, 9):\n        def getchildren(self) -> list[Element]: ...\n        def getiterator(self, tag: str | None = None) -> list[Element]: ...\n\ndef SubElement(parent: Element, tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ...\ndef Comment(text: str | None = None) -> Element: ...\ndef ProcessingInstruction(target: str, text: str | None = None) -> Element: ...\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\nclass ElementTree:\n    def __init__(self, element: Element | None = None, file: _FileRead | None = None) -> None: ...\n    def getroot(self) -> Element | Any: ...\n    def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ...\n    def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ...\n    if sys.version_info < (3, 9):\n        def getiterator(self, tag: str | None = None) -> list[Element]: ...\n\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    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: str | None = None,\n        *,\n        short_empty_elements: bool = True,\n    ) -> None: ...\n    def write_c14n(self, file: _FileWriteC14N) -> None: ...\n\ndef register_namespace(prefix: str, uri: str) -> None: ...\n@overload\ndef tostring(\n    element: Element,\n    encoding: None = None,\n    method: str | 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,\n    encoding: Literal[\"unicode\"],\n    method: str | 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,\n    encoding: str,\n    method: str | 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,\n    encoding: None = None,\n    method: str | 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,\n    encoding: Literal[\"unicode\"],\n    method: str | 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,\n    encoding: str,\n    method: str | 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) -> None: ...\n\nif sys.version_info >= (3, 9):\n    def indent(tree: Element | ElementTree, space: str = \"  \", level: int = 0) -> None: ...\n\ndef parse(source: _FileRead, parser: XMLParser | None = None) -> ElementTree: ...\n\nclass _IterParseIterator(Iterator[tuple[str, Any]]):\n    def __next__(self) -> tuple[str, Any]: ...\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\ndef iterparse(source: _FileRead, events: Sequence[str] | None = None, parser: XMLParser | None = None) -> _IterParseIterator: ...\n\nclass XMLPullParser:\n    def __init__(self, events: Sequence[str] | None = None, *, _parser: XMLParser | None = None) -> None: ...\n    def feed(self, data: str | ReadableBuffer) -> None: ...\n    def close(self) -> None: ...\n    # Second element in the tuple could be `Element`, `tuple[str, str]` or `None`.\n    # Use `Any` to avoid false-positive errors.\n    def read_events(self) -> Iterator[tuple[str, Any]]: ...\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\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 = ...,\n        *,\n        comment_factory: Callable[[str | None], Element] | None = ...,\n        pi_factory: Callable[[str, str | None], Element] | None = ...,\n        insert_comments: bool = ...,\n        insert_pis: bool = ...,\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: ...\n    def pi(self, target: str, text: str | None = None, /) -> Element: ...\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\nclass XMLParser:\n    parser: Any\n    target: Any\n    # TODO-what is entity used for???\n    entity: Any\n    version: str\n    def __init__(self, *, target: Any = ..., encoding: str | None = ...) -> None: ...\n    def close(self) -> Any: ...\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": "from _typeshed import ReadableBuffer, StrPath, SupportsRead, _T_co\nfrom collections.abc import Iterable\nfrom typing import Protocol\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 XMLReader\n\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: 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"
  },
  {
    "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: ...\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: ...\n    def getLineNumber(self) -> int: ...\n    def getPublicId(self): ...\n    def getSystemId(self): ...\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 Unused\nfrom xml.sax import xmlreader\n\nversion: str\nAttributesImpl = xmlreader.AttributesImpl\nAttributesNSImpl = xmlreader.AttributesNSImpl\n\nclass _ClosedParser: ...\n\nclass ExpatLocator(xmlreader.Locator):\n    def __init__(self, parser: ExpatParser) -> None: ...\n    def getColumnNumber(self) -> int: ...\n    def getLineNumber(self) -> int: ...\n    def getPublicId(self): ...\n    def getSystemId(self): ...\n\nclass ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):\n    def __init__(self, namespaceHandling: int = 0, bufsize: int = 65516) -> None: ...\n    def parse(self, source) -> None: ...\n    def prepareParser(self, source) -> None: ...\n    def setContentHandler(self, handler) -> None: ...\n    def getFeature(self, name: str): ...\n    def setFeature(self, name: str, state) -> None: ...\n    def getProperty(self, name: str): ...\n    def setProperty(self, name: str, value) -> None: ...\n    if sys.version_info >= (3, 9):\n        def feed(self, data, isFinal: bool = False) -> None: ...\n    else:\n        def feed(self, data, isFinal: int = 0) -> None: ...\n\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): ...\n    def getSystemId(self): ...\n    def start_element(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ...\n    def end_element(self, name: str) -> None: ...\n    def start_element_ns(self, name: str, attrs) -> 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: Unused) -> None: ...\n    def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name) -> None: ...\n    def notation_decl(self, name, base, sysid, pubid) -> None: ...\n    def external_entity_ref(self, context, base, sysid, pubid): ...\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 NoReturn\nfrom xml.sax import xmlreader\n\nversion: str\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\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, str], qname: str, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str, str], qname: str) -> 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 DTDHandler:\n    def notationDecl(self, name, publicId, systemId): ...\n    def unparsedEntityDecl(self, name, publicId, systemId, ndata): ...\n\nclass EntityResolver:\n    def resolveEntity(self, publicId, systemId): ...\n\nfeature_namespaces: str\nfeature_namespace_prefixes: str\nfeature_string_interning: str\nfeature_validation: str\nfeature_external_ges: str\nfeature_external_pes: str\nall_features: list[str]\nproperty_lexical_handler: str\nproperty_declaration_handler: str\nproperty_dom_node: str\nproperty_xml_string: str\nproperty_encoding: str\nproperty_interning_dict: str\nall_properties: list[str]\n\nif sys.version_info >= (3, 10):\n    class LexicalHandler:\n        def comment(self, content: str) -> object: ...\n        def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> object: ...\n        def endDTD(self) -> object: ...\n        def startCDATA(self) -> object: ...\n        def endCDATA(self) -> object: ...\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 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 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, str], qname: str, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str, str], qname: str) -> 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    def error(self, exception): ...\n    def fatalError(self, exception): ...\n    def warning(self, exception): ...\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, str], qname: str, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str, str], qname: str) -> 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    def notationDecl(self, name, publicId, systemId): ...\n    def unparsedEntityDecl(self, name, publicId, systemId, ndata): ...\n    def resolveEntity(self, publicId, systemId): ...\n    def parse(self, source: _Source) -> None: ...\n    def setLocale(self, locale): ...\n    def getFeature(self, name: str) -> object: ...\n    def setFeature(self, name: str, state: object) -> None: ...\n    def getProperty(self, name: str) -> object: ...\n    def setProperty(self, name: str, value: object) -> None: ...\n    def getParent(self) -> xmlreader.XMLReader: ...\n    def setParent(self, parent: xmlreader.XMLReader) -> None: ...\n\ndef prepare_input_source(source, base=\"\"): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/xmlreader.pyi",
    "content": "from collections.abc import Mapping\nfrom typing import overload\nfrom typing_extensions import Self, TypeAlias\nfrom xml.sax.handler import ContentHandler, DTDHandler, EntityResolver, ErrorHandler\n\nclass XMLReader:\n    def parse(self, source): ...\n    def getContentHandler(self) -> ContentHandler: ...\n    def setContentHandler(self, handler: ContentHandler) -> None: ...\n    def getDTDHandler(self) -> DTDHandler: ...\n    def setDTDHandler(self, handler: DTDHandler) -> None: ...\n    def getEntityResolver(self) -> EntityResolver: ...\n    def setEntityResolver(self, resolver: EntityResolver) -> None: ...\n    def getErrorHandler(self) -> ErrorHandler: ...\n    def setErrorHandler(self, handler: ErrorHandler) -> None: ...\n    def setLocale(self, locale): ...\n    def getFeature(self, name: str) -> object: ...\n    def setFeature(self, name: str, state: object) -> 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): ...\n    def feed(self, data): ...\n    def prepareParser(self, source): ...\n    def close(self): ...\n    def reset(self): ...\n\nclass Locator:\n    def getColumnNumber(self): ...\n    def getLineNumber(self): ...\n    def getPublicId(self): ...\n    def getSystemId(self): ...\n\nclass InputSource:\n    def __init__(self, system_id: str | None = None) -> None: ...\n    def setPublicId(self, public_id): ...\n    def getPublicId(self): ...\n    def setSystemId(self, system_id): ...\n    def getSystemId(self): ...\n    def setEncoding(self, encoding): ...\n    def getEncoding(self): ...\n    def setByteStream(self, bytefile): ...\n    def getByteStream(self): ...\n    def setCharacterStream(self, charfile): ...\n    def getCharacterStream(self): ...\n\nclass AttributesImpl:\n    def __init__(self, attrs: Mapping[str, str]) -> None: ...\n    def getLength(self) -> int: ...\n    def getType(self, name: str) -> str: ...\n    def getValue(self, name: str) -> str: ...\n    def getValueByQName(self, name: str) -> str: ...\n    def getNameByQName(self, name: str) -> str: ...\n    def getQNameByName(self, name: str) -> str: ...\n    def getNames(self) -> list[str]: ...\n    def getQNames(self) -> list[str]: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, name: str) -> str: ...\n    def keys(self) -> list[str]: ...\n    def __contains__(self, name: str) -> bool: ...\n    @overload\n    def get(self, name: str, alternative: None = None) -> str | None: ...\n    @overload\n    def get(self, name: str, alternative: str) -> str: ...\n    def copy(self) -> Self: ...\n    def items(self) -> list[tuple[str, str]]: ...\n    def values(self) -> list[str]: ...\n\n_NSName: TypeAlias = tuple[str | None, str]\n\nclass AttributesNSImpl(AttributesImpl):\n    def __init__(self, attrs: Mapping[_NSName, str], qnames: Mapping[_NSName, str]) -> None: ...\n    def getType(self, name: _NSName) -> str: ...  # type: ignore[override]\n    def getValue(self, name: _NSName) -> str: ...  # type: ignore[override]\n    def getNameByQName(self, name: str) -> _NSName: ...  # type: ignore[override]\n    def getQNameByName(self, name: _NSName) -> str: ...  # type: ignore[override]\n    def getNames(self) -> list[_NSName]: ...  # type: ignore[override]\n    def __getitem__(self, name: _NSName) -> str: ...  # type: ignore[override]\n    def keys(self) -> list[_NSName]: ...  # type: ignore[override]\n    def __contains__(self, name: _NSName) -> bool: ...  # type: ignore[override]\n    @overload  # type: ignore[override]\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]]: ...  # type: ignore[override]\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\nfrom typing_extensions import Self, TypeAlias\n\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\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\nclass _DispatchArity0(Protocol):\n    def __call__(self) -> _Marshallable: ...\n\nclass _DispatchArity1(Protocol):\n    def __call__(self, arg1: _Marshallable, /) -> _Marshallable: ...\n\nclass _DispatchArity2(Protocol):\n    def __call__(self, arg1: _Marshallable, arg2: _Marshallable, /) -> _Marshallable: ...\n\nclass _DispatchArity3(Protocol):\n    def __call__(self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, /) -> _Marshallable: ...\n\nclass _DispatchArity4(Protocol):\n    def __call__(\n        self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, arg4: _Marshallable, /\n    ) -> _Marshallable: ...\n\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\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\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_ReadWriteBinaryMode: TypeAlias = Literal[\"r\", \"w\", \"rb\", \"wb\"]\n\nclass BadZipFile(Exception): ...\n\nBadZipfile = BadZipFile\nerror = BadZipfile\n\nclass LargeZipFile(Exception): ...\n\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().\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\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\nclass _Writer(Protocol):\n    def write(self, s: str, /) -> object: ...\n\nclass _ZipReadable(Protocol):\n    def seek(self, offset: int, whence: int = 0, /) -> int: ...\n    def read(self, n: int = -1, /) -> bytes: ...\n\nclass _ZipTellable(Protocol):\n    def tell(self) -> int: ...\n\nclass _ZipReadableTellable(_ZipReadable, _ZipTellable, Protocol): ...\n\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    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\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        if sys.version_info >= (3, 9):\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 = ...,\n                write_through: bool = ...,\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        else:\n            def open(\n                self, mode: _ReadWriteBinaryMode = \"r\", pwd: bytes | None = None, *, force_zip64: bool = False\n            ) -> 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 = ...,\n            errors: str | None = ...,\n            newline: str | None = ...,\n            line_buffering: bool = ...,\n            write_through: bool = ...,\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        if sys.version_info >= (3, 12):\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\n        def __truediv__(self, add: StrPath) -> Path: ...\n\ndef is_zipfile(filename: StrOrBytesPath | _SupportsReadSeekTell) -> bool: ...\n\nZIP_STORED: Final[int]\nZIP_DEFLATED: Final[int]\nZIP64_LIMIT: Final[int]\nZIP_FILECOUNT_LIMIT: Final[int]\nZIP_MAX_COMMENT: Final[int]\nZIP_BZIP2: Final[int]\nZIP_LZMA: 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, TypeAlias\nfrom zipfile import ZipFile\n\n_ReadWriteBinaryMode: TypeAlias = Literal[\"r\", \"w\", \"rb\", \"wb\"]\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        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        if sys.version_info >= (3, 9):\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 = ...,\n                write_through: bool = ...,\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        else:\n            def open(\n                self, mode: _ReadWriteBinaryMode = \"r\", pwd: bytes | None = None, *, force_zip64: bool = False\n            ) -> 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 = ...,\n            errors: str | None = ...,\n            newline: str | None = ...,\n            line_buffering: bool = ...,\n            write_through: bool = ...,\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        if sys.version_info >= (3, 12):\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\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        def __init__(self, seps: str = ...) -> None: ...\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.abc import ResourceReader\nfrom importlib.machinery import ModuleSpec\nfrom types import CodeType, ModuleType\nfrom typing_extensions import deprecated\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        def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ...  # undocumented\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    def get_resource_reader(self, fullname: str) -> ResourceReader | None: ...  # undocumented\n    def get_source(self, fullname: str) -> str | None: ...\n    def is_package(self, fullname: str) -> bool: ...\n    @deprecated(\"Deprecated since 3.10; use exec_module() instead\")\n    def load_module(self, fullname: str) -> ModuleType: ...\n    if sys.version_info >= (3, 10):\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"
  },
  {
    "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: int  # can change\nDEF_BUF_SIZE: Final = 16384\nMAX_WBITS: int\nZLIB_VERSION: str  # can change\nZLIB_RUNTIME_VERSION: str  # can change\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\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\n\n# TODO: remove this version check\n# In theory we shouldn't need this version check. Pyright complains about the imports\n# from zoneinfo.* when run on 3.8 and 3.7 without this. Updates to typeshed's\n# pyright test script are probably needed, see #11189\nif sys.version_info >= (3, 9):\n    from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes\n    from 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    class 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        @classmethod\n        def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ...\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\n    def __dir__() -> list[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zoneinfo/_common.pyi",
    "content": "import io\nfrom typing import Any, Protocol\n\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/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\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\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\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"
  },
  {
    "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\nfrom typing_extensions import 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    IntersectionType,\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        t.default.accept(self)\n\n    def visit_parameters(self, t: Parameters, /) -> None:\n        self.traverse_types(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_types(t.args)\n\n    def visit_callable_type(self, t: CallableType, /) -> None:\n        # FIX generics\n        self.traverse_types(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_types(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_types(t.items)\n\n    def visit_intersection_type(self, t: IntersectionType) -> None:\n        self.traverse_types(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_types(t.args)\n\n    def visit_type_list(self, t: TypeList, /) -> None:\n        self.traverse_types(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_types(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_types(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"
  },
  {
    "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, scopename=typ.name)\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 operator\nimport os\nimport re\nimport shutil\nimport sys\nimport time\nfrom builtins import getattr as builtins_getattr\nfrom collections.abc import Container, Iterable, Sequence, Sized\nfrom importlib import resources as importlib_resources\nfrom typing import IO, Any, Callable, Final, Literal, TypeVar, overload\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\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(\"_\")\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, 9):  # noqa: UP036, RUF100\n        sys.exit(\n            \"Running {name} with Python 3.8 or lower is not supported; \"\n            \"please upgrade to 3.9 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 parse_gray_color(cup: bytes) -> str:\n    \"\"\"Reproduce a gray color in ANSI escape sequence\"\"\"\n    if sys.platform == \"win32\":\n        assert False, \"curses is not available on Windows\"\n    set_color = \"\".join([cup[:-1].decode(), \"m\"])  # type: ignore[unreachable, unused-ignore]\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,\n        f_out: IO[str],\n        f_err: IO[str],\n        hide_error_codes: bool,\n        hide_success: bool = False,\n        color=True,\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        # TODO: handle NO_COLOR and FORCE_COLOR\n        if not color:\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        assert sys.platform == \"win32\"\n        if sys.platform == \"win32\":\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),  # type: ignore[any, unused-ignore]\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        return False  # type: ignore[unreachable, unused-ignore]\n\n    def initialize_unix_colors(self) -> bool:\n        \"\"\"Return True if initialization was successful and we can use colors, False otherwise\"\"\"\n        if sys.platform == \"win32\" or not CURSES_ENABLED:\n            return False\n        try:  # type: ignore[unreachable, unused-ignore]\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()  # type: ignore[any, unused-ignore]\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)  # type: ignore[any, unused-ignore]\n        except curses.error:\n            # Most likely terminfo not found.\n            term = os.environ.get(\"TERM\")\n            if term == \"ansi\":\n                return False\n            # Try again with TERM='ansi'\n            try:\n                os.environ[\"TERM\"] = \"ansi\"\n                return self.initialize_unix_colors()\n            finally:\n                if term is None:\n                    del os.environ[\"TERM\"]\n                else:\n                    os.environ[\"TERM\"] = term\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 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        if not os.environ.get(\"COLUMNS\"):\n            # Only wrap if there is actually a terminal\n            try:\n                os.get_terminal_size(safe(sys.__stdout__).fileno())\n            except (AttributeError, ValueError, OSError):\n                return messages\n        width = fixed_terminal_width or get_terminal_width()\n        new_messages = messages.copy()\n        for i, error in enumerate(messages):\n            if \": 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            if error.startswith(\" \" * DEFAULT_SOURCE_OFFSET) and \"^\" not in error:\n                # TODO: detecting source code highlights through an indent can be surprising.\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        if \": 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        elif error.startswith(\" \" * DEFAULT_SOURCE_OFFSET):\n            # TODO: detecting source code highlights through an indent can be surprising.\n            if \"^\" not in error:\n                return self.style(error, \"none\", dim=True)\n            return self.style(error, \"red\")\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        new_errors: int = -1,\n    ) -> str:\n        \"\"\"Format a short summary in case of errors.\"\"\"\n        msg = f\"Found {n_errors} error{plural_s(n_errors)} \"\n        if new_errors != -1:\n            msg += f\"({new_errors} new error{plural_s(new_errors)}) \"\n        msg += f\"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 safe(value: T | None, message=\"A value was unexpectedly 'None'.\") -> T:\n    assert value is not None, message\n    return value\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\n_default = object()\n\n\n@overload\ndef getattr(value: object, name: str) -> Any: ...\n@overload\ndef getattr(value: object, name: str, default: T) -> Any | T: ...\ndef getattr(value, name, default: object = _default):\n    if default is _default:\n        return builtins_getattr(value, name)\n    return builtins_getattr(value, name, default)\n\n\ndef attrgetter(name: str) -> operator.attrgetter[Any]:\n    return operator.attrgetter(name)\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\nfrom mypy.versionutil import VersionInfo\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.15.0+dev\"\nbase_version = __version__\n\n# friendly version information\nbased_version_info = VersionInfo(\n    2, 11, 0, \"dev\", 0, __version__.split(\"+dev\")[0], \"dev\" if \"+dev\" in __version__ else \"final\"\n)\n# simple string version with git info\n__based_version__ = based_version_info.simple_str()\n# simple string version without git info\nbase_based_version = __based_version__\n\nmypy_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\nif based_version_info.release_level == \"dev\" and git.is_git_repo(mypy_dir) and git.have_git():\n    __based_version__ += \".\" + git.git_revision(mypy_dir).decode(\"utf-8\")\n    if git.is_dirty(mypy_dir):\n        __based_version__ += \".dirty\"\ndel mypy_dir\n"
  },
  {
    "path": "mypy/versionutil.py",
    "content": "from typing import NamedTuple\n\n\nclass VersionInfo(NamedTuple):\n    # UNSTABLE, subject to change\n\n    major: int\n    minor: int\n    patch: int\n    release_level: str\n    iteration: int\n    mypy_version: str\n    mypy_release_level: str\n\n    def simple_str(self) -> str:\n        result = f\"{self.major}.{self.minor}.{self.patch}\"\n        if self.release_level == \"dev\":\n            result += \"+dev\"\n        if self.release_level == \"alpha\":\n            result += \"a\"\n        elif self.release_level == \"beta\":\n            result += \"b\"\n        elif self.release_level == \"rc\":\n            result += \"rc\"\n        if self.iteration:\n            result += str(self.iteration)\n        return result\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_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_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 return None by default,\n    subclasses do not always need to override all the methods.\n\n    TODO: make the default return value explicit, then turn on\n          empty body checking in mypy_self_check.ini.\n    \"\"\"\n\n    # Not in superclasses:\n\n    def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T:\n        pass\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        pass\n\n    # Module structure\n\n    def visit_import(self, o: mypy.nodes.Import, /) -> T:\n        pass\n\n    def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T:\n        pass\n\n    def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T:\n        pass\n\n    # Definitions\n\n    def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T:\n        pass\n\n    def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T:\n        pass\n\n    def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T:\n        pass\n\n    def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T:\n        pass\n\n    def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T:\n        pass\n\n    def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T:\n        pass\n\n    def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> T:\n        pass\n\n    def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> T:\n        pass\n\n    # Statements\n\n    def visit_block(self, o: mypy.nodes.Block, /) -> T:\n        pass\n\n    def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T:\n        pass\n\n    def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T:\n        pass\n\n    def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T:\n        pass\n\n    def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T:\n        pass\n\n    def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T:\n        pass\n\n    def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T:\n        pass\n\n    def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T:\n        pass\n\n    def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T:\n        pass\n\n    def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T:\n        pass\n\n    def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T:\n        pass\n\n    def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T:\n        pass\n\n    def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T:\n        pass\n\n    def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T:\n        pass\n\n    def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T:\n        pass\n\n    def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T:\n        pass\n\n    def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T:\n        pass\n\n    def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T:\n        pass\n\n    # Expressions (default no-op implementation)\n\n    def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T:\n        pass\n\n    def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T:\n        pass\n\n    def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T:\n        pass\n\n    def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T:\n        pass\n\n    def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T:\n        pass\n\n    def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T:\n        pass\n\n    def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T:\n        pass\n\n    def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T:\n        pass\n\n    def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T:\n        pass\n\n    def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T:\n        pass\n\n    def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T:\n        pass\n\n    def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T:\n        pass\n\n    def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T:\n        pass\n\n    def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T:\n        pass\n\n    def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T:\n        pass\n\n    def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T:\n        pass\n\n    def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T:\n        pass\n\n    def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T:\n        pass\n\n    def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T:\n        pass\n\n    def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T:\n        pass\n\n    def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T:\n        pass\n\n    def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T:\n        pass\n\n    def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T:\n        pass\n\n    def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T:\n        pass\n\n    def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T:\n        pass\n\n    def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T:\n        pass\n\n    def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T:\n        pass\n\n    def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T:\n        pass\n\n    def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T:\n        pass\n\n    def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T:\n        pass\n\n    def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T:\n        pass\n\n    def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T:\n        pass\n\n    def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T:\n        pass\n\n    def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T:\n        pass\n\n    def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T:\n        pass\n\n    def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T:\n        pass\n\n    def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T:\n        pass\n\n    def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T:\n        pass\n\n    def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T:\n        pass\n\n    def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T:\n        pass\n\n    def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T:\n        pass\n\n    def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T:\n        pass\n\n    def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T:\n        pass\n\n    def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T:\n        pass\n\n    # Patterns\n\n    def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T:\n        pass\n\n    def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T:\n        pass\n\n    def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T:\n        pass\n\n    def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T:\n        pass\n\n    def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T:\n        pass\n\n    def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T:\n        pass\n\n    def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T:\n        pass\n\n    def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T:\n        pass\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\nbasedtyping>=0.1.4\ntyping_extensions>=4.6.0\nmypy_extensions>=1.0.0\ntomli>=1.1.0; python_version<'3.11'\n"
  },
  {
    "path": "mypy_bootstrap.ini",
    "content": "[mypy]\nstrict = True\nwarn_unused_ignores = False\nshow_traceback = True\nalways_true = MYPYC\ninfer_function_types = True\nbare_literals = True\nwork_not_properly_function_names = 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\nstrict = True\ndisallow_any_unimported = True\nshow_traceback = True\npretty = True\nalways_false = MYPYC\nplugins = mypy.plugins.proper_plugin\npython_version = 3.9\nexclude = mypy/typeshed/|mypyc/test-data/|mypyc/lib-rt/\nenable_error_code = ignore-without-code,bad-cast\nenable_incomplete_feature = PreciseTupleTypes\nshow_error_code_links = True\nallow_any_expr = True\nallow_any_explicit = True\nallow_any_decorated = True\nno_warn_unreachable = True\nimplicit_reexport = True\ndisallow_redefinition = True\ndisable_error_code = truthy-bool, truthy-iterable, no-untyped-usage, possibly-undefined, explicit-override, redundant-expr\nwork_not_properly_function_names = True\n\n[mypy-_pytest.*,pytest.*]\nincomplete_is_typed = True\ninfer_function_types = False\ndefault_return = False\n\n[mypy-mypy.visitor]\n# See docstring for NodeVisitor for motivation.\ndisable_error_code = empty-body\n"
  },
  {
    "path": "mypy_self_check_strict.ini",
    "content": "[mypy]\ndisallow_untyped_calls = True\ndisallow_untyped_defs = True\ndisallow_incomplete_defs = True\ncheck_untyped_defs = True\ndisallow_subclassing_any = True\nwarn_no_return = True\nstrict_optional = True\nstrict_equality = True\nno_implicit_optional = True\ndisallow_any_generics = True\ndisallow_any_unimported = True\nwarn_redundant_casts = True\nwarn_unused_ignores = True\nwarn_unused_configs = True\nshow_traceback = True\npretty = True\nalways_false = MYPYC\nplugins = mypy.plugins.proper_plugin\npython_version = 3.9\nexclude = mypy/typeshed/|mypyc/test-data/|mypyc/lib-rt/\ndisallow_redefinition = True\nwork_not_properly_function_names = True\nenable_error_code = helpful-string\ndisable_error_code =  explicit-override\n\n[mypy-_pytest.*,pytest.*]\nincomplete_is_typed = True\ninfer_function_types = False\ndefault_return = False\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(name='mypyc_output',\n      ext_modules=mypycify({}, opt_level=\"{}\", debug_level=\"{}\", strict_dunder_typing={}),\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\n    setup_file = os.path.join(build_dir, \"setup.py\")\n    with open(setup_file, \"w\") as f:\n        f.write(setup_format.format(sys.argv[1:], opt_level, debug_level, strict_dunder_typing))\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    ):\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)\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)\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(cl, 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/dataflow.py",
    "content": "\"\"\"Data-flow analyses.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Iterable, Iterator\nfrom typing import 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    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElementPtr,\n    Goto,\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    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\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]) -> CFG:\n    \"\"\"Calculate basic block control-flow graph.\n\n    The result is a dictionary like this:\n\n         basic block index -> (successors blocks, predecesssor blocks)\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        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[set[T], set[T]]\n\n\nclass BaseAnalysisVisitor(OpVisitor[GenAndKill[T]]):\n    def visit_goto(self, op: Goto) -> GenAndKill[T]:\n        return set(), set()\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_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_ptr(self, op: GetElementPtr) -> 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 set(), set()\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:\n        return set(), set()\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 set(), set()\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:\n        return set(), set()\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 set(), set()\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_assign(self, op: Assign) -> GenAndKill[Value]:\n        if op.dest in self.args:\n            return set(), {op.dest}\n        return set(), set()\n\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:\n        return set(), set()\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 set(), set()\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        return set(), set()\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return set(), set()\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 set(), set()\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)):\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 set(), set()\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return set(), set()\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\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            gen = (gen - opkill) | opgen\n            kill = (kill - opgen) | opkill\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 = worklist[::-1]  # 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            cur = (cur - opkill) | 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    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\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    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RPrimitive,\n    RType,\n    RUnion,\n    bytes_rprimitive,\n    dict_rprimitive,\n    int_rprimitive,\n    is_float_rprimitive,\n    is_object_rprimitive,\n    list_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):\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}\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):\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\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 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, bool):\n            expected_type = \"builtins.object\"\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_non_float(op, op.lhs)\n        self.expect_non_float(op, op.rhs)\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\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_ptr(self, op: GetElementPtr) -> 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 CFG, MAYBE_ANALYSIS, AnalysisResult, run_analysis\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    Extend,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElementPtr,\n    Goto,\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    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Unreachable,\n)\nfrom mypyc.ir.rtypes import RInstance\n\nGenAndKill = tuple[set[None], set[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_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)\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_ptr(self, op: GetElementPtr) -> 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/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, NoReturn, Union, cast\n\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.codegen import emitmodule\nfrom mypyc.common import RUNTIME_C_FILES, shared_lib_name\nfrom mypyc.errors import Errors\nfrom mypyc.ir.pprint import format_modules\nfrom mypyc.namegen import exported_name\nfrom mypyc.options import CompilerOptions\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_extensions import TypeAlias\n\n        from setuptools import Extension as _setuptools_Extension\n\n        Extension: TypeAlias = Union[_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)\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    # 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(), \"module_shim.tmpl\")) 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]:\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 and (for debugging) the pretty printed IR.\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 = 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    return ctext, \"\\n\".join(format_modules(modules))\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 of the\n    others import and then one shim extension module for each\n    module in the build, that 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) -> 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            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: Any | None = None,\n    always_use_shared_lib: bool = False,\n) -> tuple[emitmodule.Groups, list[tuple[list[str], list[str]]]]:\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)\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    if not skip_cgen_input:\n        group_cfiles, ops_text = 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\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            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\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: Any | None = None,\n    target_dir: str | None = None,\n    include_runtime_files: bool | None = None,\n    strict_dunder_typing: 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    \"\"\"\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    )\n\n    # Generate all the actual important C code\n    groups, group_cfilenames = 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: list[str] = []\n    if compiler.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    elif compiler.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        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\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        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            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    return extensions\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 typing import Callable, Final\n\nfrom mypyc.codegen.literals import Literals\nfrom mypyc.common import (\n    ATTR_PREFIX,\n    BITMAP_BITS,\n    FAST_ISINSTANCE_MAX_SUBCLASSES,\n    NATIVE_PREFIX,\n    REG_PREFIX,\n    STATIC_PREFIX,\n    TYPE_PREFIX,\n    use_vectorcall,\n)\nfrom mypyc.ir.class_ir import ClassIR, all_concrete_classes\nfrom mypyc.ir.func_ir import FuncDecl\nfrom mypyc.ir.ops import BasicBlock, Value\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RPrimitive,\n    RTuple,\n    RType,\n    RUnion,\n    int_rprimitive,\n    is_bit_rprimitive,\n    is_bool_rprimitive,\n    is_bytes_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_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)\nfrom mypyc.namegen import NameGenerator, exported_name\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\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        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\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    ) -> 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\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 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        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 use_vectorcall(self) -> bool:\n        return use_vectorcall(self.capi_version)\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        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        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        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 not rtype.is_unboxed:\n            # Always inline, since this is a simple op\n            self.emit_line(\"CPy_INCREF(%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 not rtype.is_unboxed:\n            if rare:\n                self.emit_line(f\"CPy_{x}DecRef({dest});\")\n            else:\n                # Inlined\n                self.emit_line(f\"CPy_{x}DECREF({dest});\")\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_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_rprimitive(typ)\n            or is_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_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_rprimitive(typ) or is_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({}) || 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 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        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)\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            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)\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_rprimitive(typ) or is_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\n        else:\n            assert False, \"Unboxing not implemented: %s\" % typ\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_rprimitive(typ) or is_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            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            # 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        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 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 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 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_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        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\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"
  },
  {
    "path": "mypyc/codegen/emitclass.py",
    "content": "\"\"\"Code generation for native classes and related wrappers.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Mapping\nfrom typing import Callable\n\nfrom mypyc.codegen.emit import Emitter, HeaderDeclaration, ReturnHandler\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 BITMAP_BITS, BITMAP_TYPE, NATIVE_PREFIX, PREFIX, REG_PREFIX\nfrom mypyc.ir.class_ir import ClassIR, VTableEntries\nfrom mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD, FuncDecl, FuncIR\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 wrapper_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    return f\"{PREFIX}{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}\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    if emitter.use_vectorcall():\n        # Use vectorcall wrapper if supported (PEP 590).\n        return \"PyVectorcall_Call\"\n    else:\n        # On older Pythons use the legacy wrapper.\n        return wrapper_slot(cl, fn, emitter)\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(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 = f\"{name_prefix}_setup\"\n    new_name = f\"{name_prefix}_new\"\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\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        fields[\"tp_traverse\"] = f\"(traverseproc){name_prefix}_traverse\"\n        fields[\"tp_clear\"] = f\"(inquiry){name_prefix}_clear\"\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        # 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        emitter.emit_line(f\"static PyObject *{setup_name}(PyTypeObject *type);\")\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        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, 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    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, emitter)\n    emit_line()\n\n    flags = [\"Py_TPFLAGS_DEFAULT\", \"Py_TPFLAGS_HEAPTYPE\", \"Py_TPFLAGS_BASETYPE\"]\n    if generate_full:\n        flags.append(\"Py_TPFLAGS_HAVE_GC\")\n    if cl.has_method(\"__call__\") and emitter.use_vectorcall():\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    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    emitter.emit_line()\n    if generate_full:\n        generate_setup_for_class(\n            cl, setup_name, defaults_fn, vtable_name, shadow_vtable_name, emitter\n        )\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[tuple[str, RType]] = set()\n    lines: list[str] = []\n    lines += [\"typedef struct {\", \"PyObject_HEAD\", \"CPyVTableItem *vtable;\"]\n    if cl.has_method(\"__call__\") and emitter.use_vectorcall():\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                if (attr, rtype) not in seen_attrs:\n                    lines.append(f\"{emitter.ctype_spaced(rtype)}{emitter.attr(attr)};\")\n                    seen_attrs.add((attr, rtype))\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    func_name: str,\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(\"static PyObject *\")\n    emitter.emit_line(f\"{func_name}(PyTypeObject *type)\")\n    emitter.emit_line(\"{\")\n    emitter.emit_line(f\"{cl.struct_name(emitter.names)} *self;\")\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    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    if cl.has_method(\"__call__\") and emitter.use_vectorcall():\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.emit_line(rf\"self->{emitter.attr(attr)} = {value};\")\n\n    # Initialize attributes to default values, if necessary\n    if defaults_fn is not None:\n        emitter.emit_lines(\n            \"if ({}{}((PyObject *)self) == 0) {{\".format(\n                NATIVE_PREFIX, defaults_fn.cname(emitter.names)\n            ),\n            \"Py_DECREF(self);\",\n            \"return NULL;\",\n            \"}\",\n        )\n\n    emitter.emit_line(\"return (PyObject *)self;\")\n    emitter.emit_line(\"}\")\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    emitter.emit_line(f\"PyObject *self = {setup_name}({emitter.type_struct_name(cl)});\")\n    emitter.emit_line(\"if (self == NULL)\")\n    emitter.emit_line(\"    return NULL;\")\n    args = \", \".join([\"self\"] + [REG_PREFIX + arg.name for arg in fn.sig.args])\n    if init_fn is not None:\n        emitter.emit_line(\n            \"char res = {}{}{}({});\".format(\n                emitter.get_group_prefix(init_fn.decl),\n                NATIVE_PREFIX,\n                init_fn.cname(emitter.names),\n                args,\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:\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    if not init_fn or cl.allow_interpreted_subclasses or cl.builtin_base or cl.is_serializable():\n        # Match Python semantics -- __new__ doesn't call __init__.\n        emitter.emit_line(f\"return {setup_name}(type);\")\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(f\"PyObject *self = {setup_name}(type);\")\n        emitter.emit_lines(\"if (self == NULL)\", \"    return NULL;\")\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, dealloc_func_name: str, clear_func_name: str, 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    emitter.emit_line(\"PyObject_GC_UnTrack(self);\")\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(\"}\")\n\n\ndef generate_methods_table(cl: ClassIR, name: str, emitter: Emitter) -> None:\n    emitter.emit_line(f\"static PyMethodDef {name}[] = {{\")\n    for fn in cl.methods.values():\n        if fn.decl.is_prop_setter or fn.decl.is_prop_getter:\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        emitter.emit_line(\" {}, NULL}},\".format(\" | \".join(flags)))\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.emit_line(f\"    self->{attr_field} = {emitter.c_undefined_value(rtype)};\")\n        if rtype.error_overlap:\n            emitter.emit_attr_bitmap_clear(\"self\", rtype, cl, attr)\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"
  },
  {
    "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 DEBUG_ERRORS, Emitter, TracebackAndGotoHandler, c_array_initializer\nfrom mypyc.common import (\n    MODULE_PREFIX,\n    NATIVE_PREFIX,\n    REG_PREFIX,\n    STATIC_PREFIX,\n    TYPE_PREFIX,\n    TYPE_VAR_PREFIX,\n)\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_MODULE,\n    NAMESPACE_STATIC,\n    NAMESPACE_TYPE,\n    NAMESPACE_TYPE_VAR,\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    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    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\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    is_int32_rprimitive,\n    is_int64_rprimitive,\n    is_int_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)\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            # inbetween 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 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            typ = op.value.type\n            compare = \"!=\" if negated else \"==\"\n            if isinstance(typ, RTuple):\n                # TODO: What about empty tuple?\n                cond = self.emitter.tuple_undefined_check_cond(\n                    typ, self.reg(op.value), self.c_error_value, compare\n                )\n            else:\n                cond = f\"{self.reg(op.value)} {compare} {self.c_error_value(typ)}\"\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            # We sometimes assign from an integer prepresentation of a pointer\n            # to a real pointer, and C compilers insist on a cast.\n            if op.src.type.is_unboxed and not op.dest.type.is_unboxed:\n                src = f\"(void *){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)\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        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\"{self.reg(op)} = {tmp};\")\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        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, repr(op.attr), 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 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    PREFIX_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    def visit_load_static(self, op: LoadStatic) -> None:\n        dest = self.reg(op)\n        prefix = self.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 = self.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)\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        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        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\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_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)\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_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 = self.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        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        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,\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"
  },
  {
    "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\nfrom collections.abc import Iterable\nfrom typing import Any, Optional, TypeVar, cast\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.codegen.cstring import c_string_initializer\nfrom mypyc.codegen.emit import Emitter, EmitterContext, HeaderDeclaration, c_array_initializer\nfrom mypyc.codegen.emitclass import generate_class, 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    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    use_vectorcall,\n)\nfrom mypyc.errors import Errors\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.lower import lower_ir\nfrom mypyc.transform.refcount import insert_ref_count_opcodes\nfrom mypyc.transform.uninit import insert_uninit_checks\n\n# All of 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], Optional[str]]\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: Any = 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 of 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    result = build(\n        sources=sources,\n        options=options,\n        alt_lib_path=alt_lib_path,\n        fscache=fscache,\n        extra_plugins=[MypycPlugin(options, compiler_options, groups)],\n    )\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 compiled or\n    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    for module in modules.values():\n        for fn in module.functions:\n            # Insert uninit checks.\n            insert_uninit_checks(fn)\n            # Insert exception handling.\n            insert_exception_handling(fn)\n            # Insert refcount handling.\n            insert_ref_count_opcodes(fn)\n            # Switch to lower abstraction level IR.\n            lower_ir(fn, compiler_options)\n            # Perform optimizations.\n            do_copy_propagation(fn, compiler_options)\n            do_flag_elimination(fn, compiler_options)\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]\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)\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([[source.module for source in sources] for sources, _ in groups])\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    return meta_path.replace(\".meta.json\", \".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 of 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: cast(\n            Any,\n            json.loads(\n                result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname]))\n            ),\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 compile_modules_to_c(\n    result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups\n) -> tuple[ModuleIRs, list[FileContents]]:\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 of 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 {}, []\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]\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:\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            multi_file: Whether to put each module in its own source file regardless\n                        of group structure.\n        \"\"\"\n        self.modules = modules\n        self.source_paths = source_paths\n        self.context = EmitterContext(names, group_name, group_map)\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\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        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)\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:\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_{emitter.names.private_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\n        declarations = Emitter(self.context)\n        declarations.emit_line(f\"#ifndef MYPYC_NATIVE_INTERNAL{self.group_suffix}_H\")\n        declarations.emit_line(f\"#define MYPYC_NATIVE_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            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            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 of 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 of 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        emitter.emit_lines(\n            \"PyMODINIT_FUNC PyInit_{}(void)\".format(\n                shared_lib_name(self.group_name).split(\".\")[-1]\n            ),\n            \"{\",\n            (\n                'static PyModuleDef def = {{ PyModuleDef_HEAD_INIT, \"{}\", NULL, -1, NULL, NULL }};'.format(\n                    shared_lib_name(self.group_name)\n                )\n            ),\n            \"int res;\",\n            \"PyObject *capsule;\",\n            \"PyObject *tmp;\",\n            \"static PyObject *module;\",\n            \"if (module) {\",\n            \"Py_INCREF(module);\",\n            \"return module;\",\n            \"}\",\n            \"module = PyModule_Create(&def);\",\n            \"if (!module) {\",\n            \"goto fail;\",\n            \"}\",\n            \"\",\n        )\n\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            emitter.emit_lines(\n                f\"extern PyObject *CPyInit_{name}(void);\",\n                'capsule = PyCapsule_New((void *)CPyInit_{}, \"{}.init_{}\", NULL);'.format(\n                    name, shared_lib_name(self.group_name), name\n                ),\n                \"if (!capsule) {\",\n                \"goto fail;\",\n                \"}\",\n                f'res = PyObject_SetAttrString(module, \"init_{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 module;\", \"fail:\", \"Py_XDECREF(module);\", \"return NULL;\", \"}\")\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        # Emit module methods\n        module_prefix = emitter.names.private_name(module_name)\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            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            emitter.emit_line(\n                (\n                    '{{\"{name}\", (PyCFunction){prefix}{cname}, {flag} | METH_KEYWORDS, '\n                    \"NULL /* docstring */}},\"\n                ).format(name=name, cname=fn.cname(emitter.names), prefix=PREFIX, flag=flag)\n            )\n        emitter.emit_line(\"{NULL, NULL, 0, NULL}\")\n        emitter.emit_line(\"};\")\n        emitter.emit_line()\n\n        # Emit module definition struct\n        emitter.emit_lines(\n            f\"static struct PyModuleDef {module_prefix}module = {{\",\n            \"PyModuleDef_HEAD_INIT,\",\n            f'\"{module_name}\",',\n            \"NULL, /* docstring */\",\n            \"-1,       /* size of per-interpreter state of the module,\",\n            \"             or -1 if the module keeps state in global variables. */\",\n            f\"{module_prefix}module_methods\",\n            \"};\",\n        )\n        emitter.emit_line()\n        # Emit module init function. If we are compiling just one module, this\n        # will be the C API init function. If we are compiling 2+ modules, we\n        # generate a shared library for the modules and shims that call into\n        # the shared library, and in this case we use an internal module\n        # initialized function that will be called by the shim.\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        emitter.emit_line(\"PyObject* modname = NULL;\")\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_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        # 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                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}))\", \"    goto fail;\")\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(f\"return {module_static};\")\n        emitter.emit_lines(\"fail:\", 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 NULL;\")\n        emitter.emit_line(\"}\")\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 use_vectorcall(capi_version)\n        # TODO: Support fastcall for __init__.\n        return fn.name != \"__init__\"\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    use_vectorcall,\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    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__\" and use_vectorcall(emitter.capi_version):\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.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(f\"_Py_IDENTIFIER({rmethod});\")\n    emitter.emit_line(\n        'return CPy_CallReverseOpMethod(obj_left, obj_right, \"{}\", &PyId_{});'.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, Union\nfrom typing_extensions import 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 = Union[\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\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__\"\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\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]\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 use_vectorcall(capi_version: tuple[int, int]) -> bool:\n    # We can use vectorcalls to make calls on Python 3.8+ (PEP 590).\n    return capi_version >= (3, 8)\n\n\ndef use_method_vectorcall(capi_version: tuple[int, int]) -> bool:\n    # We can use a dedicated vectorcall API to call methods on Python 3.9+.\n    return capi_version >= (3, 9)\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/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* 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* ``b.join(x: Iterable)``\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 generate 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 genenerate 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### Debuggging 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.\nInstad 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* ``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\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/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.9 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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   list_operations\n   dict_operations\n   set_operations\n   tuple_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\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://kotlinisland.github.io/basedmypy/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* ``lst * n``, ``n * lst``\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 (except for :ref:`traits\n<trait-types>`). Most non-native classes can't be used as base\nclasses.\n\nThese non-native 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* ``typing.NamedTuple``\n* ``enum.Enum``\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\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*.\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*.\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\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\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    from typing import List, Tuple\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\nOperators\n---------\n\n* Concatenation (``s1 + s2``)\n* Indexing (``s[n]``)\n* Slicing (``s[n:m]``, ``s[n:]``, ``s[:m]``)\n* Comparisons (``==``, ``!=``)\n* Augmented assignment (``s1 += 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* ``s.join(x: Iterable)``\n* ``s.replace(old: str, new: str)``\n* ``s.replace(old: str, new: str, count: int)``\n* ``s.split()``\n* ``s.split(sep: str)``\n* ``s.split(sep: str, maxsplit: int)``\n* ``s1.startswith(s2: 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\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* ``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\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 List, 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/kinds_of_types.html#union-types>`_\nand\n`optional types <https://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/kinds_of_types.html#callable-types-and-lambdas>`_\n\n* `Type variable types <https://kotlinisland.github.io/basedmypy/generics.html>`_\n\n* Type `Any <https://kotlinisland.github.io/basedmypy/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.report(line, None, msg, severity=\"error\", file=path)\n        self.num_errors += 1\n\n    def note(self, msg: str, path: str, line: int) -> None:\n        self._errors.report(line, None, msg, severity=\"note\", file=path)\n\n    def warning(self, msg: str, path: str, line: int) -> None:\n        self._errors.report(line, None, msg, severity=\"warning\", file=path)\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\nfrom mypyc.ir.ops import DeserMaps, Value\nfrom mypyc.ir.rtypes import RInstance, RType, deserialize_type\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        # 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        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 that can't have a dedicated error\n        # 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    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        }\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\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/func_ir.py",
    "content": "\"\"\"Intermediate representation of functions.\"\"\"\n\nfrom __future__ import annotations\n\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    ControlOp,\n    DeserMaps,\n    LoadAddress,\n    Register,\n    Value,\n)\nfrom mypyc.ir.rtypes import RType, bitmap_rprimitive, deserialize_type\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        is_prop_setter: bool = False,\n        is_prop_getter: bool = False,\n        implicit: 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        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        # 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            \"implicit\": self.implicit,\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            data[\"is_prop_setter\"],\n            data[\"is_prop_getter\"],\n            data[\"implicit\"],\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    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"
  },
  {
    "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.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\n    def serialize(self) -> JsonDict:\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        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ModuleIR:\n        return 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\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 (Register)\n- intermediate values of expressions (RegisterOp subclasses)\n- condition flags (true/false)\n- literals (integer literals, True, False, etc.)\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, Union\n\nfrom mypy_extensions import trait\n\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RTuple,\n    RType,\n    RVoid,\n    bit_rprimitive,\n    bool_rprimitive,\n    float_rprimitive,\n    int_rprimitive,\n    is_bit_rprimitive,\n    is_bool_rprimitive,\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\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\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\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\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\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    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    \"\"\"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\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 stolen(self) -> list[Value]:\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_assign(self)\n\n\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 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    \"\"\"Control flow operation.\"\"\"\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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_goto(self)\n\n\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 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\nclass Return(ControlOp):\n    \"\"\"Return a value from a function.\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, value: Value, line: int = -1) -> None:\n        super().__init__(line)\n        self.value = value\n\n    def sources(self) -> list[Value]:\n        return [self.value]\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\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 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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_inc_ref(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_dec_ref(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_call(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_method_call(self)\n\n\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    ) -> 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\n    def __repr__(self) -> str:\n        return f\"<PrimitiveDescription {self.name!r}: {self.arg_types}>\"\n\n\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.args = args\n        self.type = desc.return_type\n        self.error_kind = desc.error_kind\n        self.desc = desc\n\n    def sources(self) -> list[Value]:\n        return self.args\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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_error_value(self)\n\n\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) -> None:\n        self.value = value\n        self.type = rtype\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_literal(self)\n\n\nclass GetAttr(RegisterOp):\n    \"\"\"obj.attr (for a native object)\"\"\"\n\n    error_kind = ERR_MAGIC\n\n    def __init__(self, obj: Value, attr: str, line: int, *, borrow: bool = False) -> None:\n        super().__init__(line)\n        self.obj = obj\n        self.attr = attr\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 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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_get_attr(self)\n\n\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 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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_static(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_init_static(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_tuple_set(self)\n\n\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        self.src = src\n        self.index = index\n        assert isinstance(src.type, RTuple), \"TupleGet only operates on tuples\"\n        assert index >= 0\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_tuple_get(self)\n\n\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__(self, src: Value, typ: RType, line: int, *, borrow: bool = False) -> None:\n        super().__init__(line)\n        self.src = src\n        self.type = typ\n        self.is_borrowed = borrow\n\n    def sources(self) -> list[Value]:\n        return [self.src]\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\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 (\n            is_none_rprimitive(self.src.type)\n            or is_bool_rprimitive(self.src.type)\n            or is_bit_rprimitive(self.src.type)\n        ):\n            self.is_borrowed = True\n\n    def sources(self) -> list[Value]:\n        return [self.src]\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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_unbox(self)\n\n\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\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 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 = Union[bool, list[bool]]\n\n\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    ) -> 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        if is_pure:\n            assert error_kind == ERR_NEVER\n\n    def sources(self) -> list[Value]:\n        return self.args\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\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 stolen(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_truncate(self)\n\n\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 stolen(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_extend(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_global(self)\n\n\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 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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_comparison_op(self)\n\n\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 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\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_float_neg(self)\n\n\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 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\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) -> None:\n        super().__init__(line)\n        self.type = type\n        # TODO: for now we enforce that the src memory address should be Py_ssize_t\n        #       later we should also support same width unsigned int\n        assert is_pointer_rprimitive(src.type)\n        self.src = src\n        self.is_borrowed = True\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_mem(self)\n\n\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 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\nclass GetElementPtr(RegisterOp):\n    \"\"\"Get the address of a struct element.\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        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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_get_element_ptr(self)\n\n\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_address(self)\n\n\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], *, steal: bool = False) -> None:\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 accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_keep_alive(self)\n\n\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      r2 = unborrow r0\n      r3 = unborrow r1\n      # now (r2, r3) represent the tuple as separate items, and the\n      # original tuple can be considered dead and available to be\n      # stolen\n      keep_alive steal t\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 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_ptr(self, op: GetElementPtr) -> 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, Union\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    DecRef,\n    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\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    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive\n\nErrorSource = Union[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        return self.format(\"%r = %scast(%s, %r)\", op, self.borrow_prefix(op), op.type, op.src)\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 = []\n        arg_index = 0\n        type_arg_index = 0\n        for arg_type in zip(op.desc.arg_types):\n            if arg_type:\n                args.append(self.format(\"%r\", op.args[arg_index]))\n                arg_index += 1\n            else:\n                assert op.type_args\n                args.append(self.format(\"%r\", op.type_args[type_arg_index]))\n                type_arg_index += 1\n\n        args_str = \", \".join(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(\"%r = load_mem %r :: %t*\", op, op.src, op.type)\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_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_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                    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\"  ERR: {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                for error in source_to_error[op]:\n                    lines.append(f\"  ERR: {error}\")\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)):\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\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom typing import TYPE_CHECKING, ClassVar, Final, Generic, TypeVar\nfrom typing_extensions import TypeGuard\n\nfrom mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE, JsonDict, short_name\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 (e.g. -113) to signal error, but this is\n    # also a valid non-error value.\n    error_overlap = False\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    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    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_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\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    def serialize(self) -> str:\n        return \"void\"\n\n    def __eq__(self, other: object) -> bool:\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\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    ) -> 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        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 == \"PyObject *\":\n            # Boxed 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 in (\"PyObject **\", \"void *\"):\n            self.c_undefined = \"NULL\"\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    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) -> bool:\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# 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\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).\nlist_rprimitive: Final = RPrimitive(\"builtins.list\", is_unboxed=False, is_refcounted=True)\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 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# 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\n\ndef is_tagged(rtype: RType) -> bool:\n    return rtype is int_rprimitive or rtype is short_int_rprimitive\n\n\ndef is_int_rprimitive(rtype: RType) -> bool:\n    return rtype is int_rprimitive\n\n\ndef is_short_int_rprimitive(rtype: RType) -> bool:\n    return rtype is short_int_rprimitive\n\n\ndef is_int16_rprimitive(rtype: RType) -> rtype is RPrimitive if True else False:\n    return rtype is int16_rprimitive\n\n\ndef is_int32_rprimitive(rtype: RType) -> rtype is RPrimitive if True else False:\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) -> bool:\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) -> bool:\n    return rtype is uint32_rprimitive\n\n\ndef is_uint64_rprimitive(rtype: RType) -> bool:\n    return rtype is uint64_rprimitive\n\n\ndef is_c_py_ssize_t_rprimitive(rtype: RType) -> bool:\n    return rtype is c_pyssize_t_rprimitive\n\n\ndef is_pointer_rprimitive(rtype: RType) -> bool:\n    return rtype is pointer_rprimitive\n\n\ndef is_float_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.float\"\n\n\ndef is_bool_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.bool\"\n\n\ndef is_bit_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"bit\"\n\n\ndef is_object_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.object\"\n\n\ndef is_none_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.None\"\n\n\ndef is_list_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.list\"\n\n\ndef is_dict_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.dict\"\n\n\ndef is_set_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.set\"\n\n\ndef is_str_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.str\"\n\n\ndef is_bytes_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.bytes\"\n\n\ndef is_tuple_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.tuple\"\n\n\ndef is_range_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.range\"\n\n\ndef is_sequence_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and (\n        is_list_rprimitive(rtype) or is_tuple_rprimitive(rtype) or is_str_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_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        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\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    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) -> bool:\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\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        # 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 accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rstruct(self)\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) -> bool:\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\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    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) -> bool:\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\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    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) -> bool:\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) -> bool:\n    \"\"\"Is rtype an optional type with exactly two union items?\"\"\"\n    return optional_value_type(rtype) is not None\n\n\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    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) -> bool:\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"
  },
  {
    "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()\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()\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 Iterator, Sequence\nfrom contextlib import contextmanager\nfrom typing import Any, Callable, Final, Union, 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    UnaryExpr,\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, 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    Assign,\n    BasicBlock,\n    Branch,\n    ComparisonOp,\n    GetAttr,\n    InitStatic,\n    Integer,\n    IntOp,\n    LoadStatic,\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    bitmap_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.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.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\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 = Union[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\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()\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) -> None:\n        self.builder.flush_keep_alives()\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) -> Value:\n        return self.builder.load_str(value)\n\n    def load_bytes_from_str_literal(self, value: str) -> 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))\n\n    def load_int(self, value: int) -> Value:\n        return self.builder.load_int(value)\n\n    def load_float(self, value: float) -> Value:\n        return self.builder.load_float(value)\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) -> Value:\n        return self.builder.none_object()\n\n    def none(self) -> Value:\n        return self.builder.none()\n\n    def true(self) -> Value:\n        return self.builder.true()\n\n    def false(self) -> Value:\n        return self.builder.false()\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) -> Value:\n        return self.builder.builtin_len(val, line)\n\n    def new_tuple(self, items: list[Value], line: int) -> Value:\n        return self.builder.new_tuple(items, 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)\n        self.primitive_op(dict_set_item_op, [non_ext.dict, key_unicode, 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)\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(), \"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)\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))\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 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))\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            retval = self.coerce(self.builder.none(), self.ret_types[-1], -1)\n            self.nonlocal_control[-1].gen_return(self, retval, self.fn_info.fitem.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)\n        assert isinstance(lvalue.node, Var)\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(self, val: int | str | bytes | float | complex | bool) -> 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()\n            else:\n                return self.false()\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:\n                        return self.add_var_to_env_class(\n                            symbol, reg_type, self.fn_info.generator_class, reassign=False\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)\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, target: Value | AssignmentTarget, line: int = -1, can_borrow: 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(GetAttr(target.obj, target.attr, line, borrow=borrow))\n            else:\n                return self.py_get_attr(target.obj, target.attr, line)\n\n        assert False, \"Unsupported lvalue: %r\" % target\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)))\n        elif isinstance(target, AssignmentTargetRegister):\n            rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)\n            self.add(Assign(target.register, rvalue_reg))\n        elif isinstance(target, AssignmentTargetAttr):\n            if isinstance(target.obj_type, RInstance):\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)\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            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 = self.builder.load_int(i)\n            if is_list_rprimitive(rvalue.type):\n                item_value = self.primitive_op(list_get_item_unsafe_op, [rvalue, index], line)\n            else:\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, so -1 for line\n        self.assign(target, value, -1)\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, -1)\n        return reg\n\n    def extract_int(self, e: Expression) -> int | None:\n        if isinstance(e, IntExpr):\n            return e.value\n        elif isinstance(e, UnaryExpr) and e.op == \"-\" and isinstance(e.expr, IntExpr):\n            return -e.expr.value\n        else:\n            return 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            else:\n                return self.type_to_rtype(target_type.args[0])\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            # Tuple might have elements of different types.\n            rtypes = {self.mapper.type_to_rtype(item) for item in target_type.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        target_type = get_proper_type(self.types[expr])\n        if isinstance(target_type, UnionType):\n            types = [get_proper_type(item) for item in target_type.items]\n        else:\n            types = [target_type]\n\n        dict_types = []\n        for t in types:\n            if isinstance(t, TypedDictType):\n                t = t.fallback\n                dict_base = next(base for base in t.type.mro if base.fullname == \"typing.Mapping\")\n            else:\n                assert isinstance(t, Instance), t\n                dict_base = next(base for base in t.type.mro if base.fullname == \"builtins.dict\")\n            dict_types.append(map_instance_to_supertype(t, dict_base))\n        return dict_types\n\n    def get_dict_key_type(self, expr: Expression) -> RType:\n        dict_base_types = self.get_dict_base_type(expr)\n        if len(dict_base_types) == 1:\n            return self.type_to_rtype(dict_base_types[0].args[0])\n        else:\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        if len(dict_base_types) == 1:\n            return self.type_to_rtype(dict_base_types[0].args[1])\n        else:\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)\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        return self.builder.shortcircuit_helper(\n            expr.op,\n            self.node_type(expr),\n            lambda: self.accept(expr.left),\n            lambda: self.accept(expr.right),\n            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 = \"\") -> 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(none_rprimitive)\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_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    ) -> 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)\n        self.function_name_stack.append(name)\n        self.class_ir_stack.append(class_ir)\n        self.ret_types[-1] = ret_type\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)\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)\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)\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, var: SymbolNode, rtype: RType, base: FuncInfo | ImplicitClass, reassign: bool = False\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 = remangle_redefinition_name(var.name)\n        self.fn_info.env_class.attributes[name] = rtype\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)\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\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)\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 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), builder.true()],\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)\n        builder.init_type_var(tv, type_param.name, line)\n        tvs.append(tv)\n    return tvs\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 ENV_ATTR_NAME, 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, Register, Return, SetAttr, Value\nfrom mypyc.ir.rtypes import RInstance, object_rprimitive\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.context import FuncInfo, ImplicitClass\nfrom mypyc.primitives.misc_ops import method_new_op\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)\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\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(), \"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: we use the environment of the original function.\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:\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    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\nimport typing_extensions\nfrom abc import abstractmethod\nfrom typing import Callable, 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.util import dataclass_type, get_func_def, is_constant, is_dataclass_decorator\nfrom mypyc.primitives.dict_ops import dict_new_op, 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    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 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        # 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.primitive_op(\n            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 | None = 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        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)\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    # 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                -1,\n            )\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.primitive_op(\n        dict_set_item_op, [builder.load_globals_dict(), builder.load_str(cdef.name), tp], 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            if builder.options.capi_version < (3, 9):\n                name = \"TypedDict\"\n                if builder.options.capi_version < (3, 8):\n                    # TypedDict was added to typing in Python 3.8.\n                    module = \"typing_extensions\"\n                    # TypedDict is not a real type on typing_extensions 4.7.0+\n                    name = \"_TypedDict\"\n                    if isinstance(typing_extensions.TypedDict, type):\n                        raise RuntimeError(\n                            \"It looks like you may have an old version \"\n                            \"of typing_extensions installed. \"\n                            \"typing_extensions>=4.7.0 is required on Python 3.7.\"\n                        )\n            else:\n                # In Python 3.9 TypedDict is not a real type.\n                name = \"_TypedDict\"\n            base = builder.get_module_attr(module, name, cdef.line)\n        elif is_named_tuple and cls.fullname == \"builtins.tuple\":\n            if builder.options.capi_version < (3, 9):\n                name = \"NamedTuple\"\n            else:\n                # This was changed in Python 3.9.\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 and builder.options.capi_version >= (3, 9):\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 and builder.options.capi_version >= (3, 9):\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            typ = load_type(builder, type_info, 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.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.primitive_op(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)\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, -1)\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(builder.unary_op(eqval, \"not\", line), rettype, line)\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)\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)\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 Final, Union\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.builder import IRBuilder\nfrom mypyc.irbuild.util import bytes_from_str\n\n# All possible result types of constant folding\nConstantValue = Union[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    ) -> 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\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\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        # 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 BITMAP_BITS, ENV_ATTR_NAME, SELF_NAME, bitmap_name\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\", builder.module_name, is_generated=True\n    )\n    env_class.attributes[SELF_NAME] = RInstance(env_class)\n    if builder.fn_info.is_nested:\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) -> None:\n    \"\"\"Generate, instantiate, and set up the environment of an environment class.\"\"\"\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.\n    if builder.fn_info.is_nested:\n        add_args_to_env(builder, local=False, base=builder.fn_info.callable_class)\n    else:\n        add_args_to_env(builder, local=False, base=builder.fn_info)\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:\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        builder.fn_info._curr_env_reg = curr_env_reg\n\n    return curr_env_reg\n\n\ndef load_env_registers(builder: IRBuilder) -> 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)\n\n    fn_info = builder.fn_info\n    fitem = fn_info.fitem\n    if fn_info.is_nested:\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)\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        env.type.class_ir.attributes[symbol.name] = target.type\n        symbol_target = AssignmentTargetAttr(env, symbol.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    if index > 1:\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        # 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) -> 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 is_free_variable(builder, arg.variable) or fn_info.is_generator:\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(arg.variable, rtype, base, reassign=reassign)\n\n\ndef setup_func_for_recursive_call(builder: IRBuilder, fdef: FuncDef, base: ImplicitClass) -> 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    prev_env.attributes[fdef.name] = builder.type_to_rtype(fdef.type)\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, -1))\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, fdef.name, -1))\n    target = builder.add_local_reg(fdef, object_rprimitive)\n    builder.assign(target, val, -1)\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 Sequence\nfrom typing import Callable, Optional, cast\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 Instance, ProperType, TupleType, TypeType, get_proper_type\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    RTuple,\n    bool_rprimitive,\n    int_rprimitive,\n    is_fixed_width_rtype,\n    is_int_rprimitive,\n    is_list_rprimitive,\n    is_none_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)\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 apply_function_specialization, apply_method_specialization\nfrom mypyc.primitives.bytes_ops import bytes_slice_op\nfrom mypyc.primitives.dict_ops import dict_get_item_op, dict_new_op, dict_set_item_op\nfrom mypyc.primitives.generic_ops import iter_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.RUNTIME_ERROR,\n                \"mypyc internal error: should be unreachable\",\n                expr.line,\n            )\n        )\n        return builder.none()\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()\n    if fullname == \"builtins.True\":\n        return builder.true()\n    if fullname == \"builtins.False\":\n        return builder.false()\n    if fullname in (\"typing.TYPE_CHECKING\", \"typing_extensions.TYPE_CHECKING\"):\n        return builder.false()\n\n    math_literal = transform_math_literal(builder, fullname)\n    if math_literal is not None:\n        return math_literal\n\n    if isinstance(expr.node, Var) and expr.node.is_final:\n        value = builder.emit_load_final(\n            expr.node,\n            fullname,\n            expr.name,\n            builder.is_native_ref_expr(expr),\n            builder.types[expr],\n            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()\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        value = builder.emit_load_final(\n            final_var, fullname, final_var.name, native, builder.types[expr], expr.line\n        )\n        if value is not None:\n            return value\n\n    math_literal = transform_math_literal(builder, expr.fullname)\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    # 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 sixth argument (see comment in translate_super_method_call)\n            self_targ = list(builder.symtables[-1].values())[6]\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        callee = 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)\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 (\n            ir.is_ext_class\n            and ir.builtin_base is None\n            and not ir.inherits_python\n            and callee.name == \"__init__\"\n            and len(expr.args) == 0\n        ):\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:\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 6th 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())[6]\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_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(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(expr: OpExpr) -> OpExpr:\n    \"\"\"Replace // with a power of two with a right shift, if possible.\"\"\"\n    if not isinstance(expr.right, IntExpr):\n        return expr\n    divisor = expr.right.value\n    shift = divisor.bit_length() - 1\n    if 0 < shift < 28 and divisor == (1 << shift):\n        return OpExpr(\">>\", expr.left, IntExpr(shift))\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    is_list = is_list_rprimitive(base_type)\n    can_borrow_base = is_list and is_borrow_friendly_expr(builder, index)\n\n    base = builder.accept(expr.base, can_borrow=can_borrow_base)\n\n    if isinstance(base.type, RTuple) and isinstance(index, IntExpr):\n        return builder.add(TupleGet(base, index.value, 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=is_list)\n    return builder.gen_method_call(\n        base, \"__getitem__\", [index_reg], builder.node_type(expr), expr.line\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_int_rprimitive(begin_type) and is_int_rprimitive(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        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))\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))\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 (\n        first_op in [\"in\", \"not in\"]\n        and len(e.operators) == 1\n        and isinstance(e.operands[1], (TupleExpr, ListExpr))\n    ):\n        items = e.operands[1].items\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        # 16 is arbitrarily chosen to limit code size\n        if 1 < n_items < 16:\n            if e.operators[0] == \"in\":\n                bin_op = \"or\"\n                cmp_op = \"==\"\n            else:\n                bin_op = \"and\"\n                cmp_op = \"!=\"\n            lhs = e.operands[0]\n            mypy_file = builder.graph[\"builtins\"].tree\n            assert mypy_file is not None\n            info = mypy_file.names[\"bool\"].node\n            assert isinstance(info, TypeInfo)\n            bool_type = Instance(info, [])\n            exprs = []\n            for item in items:\n                expr = ComparisonExpr([cmp_op], [lhs, item])\n                builder.types[expr] = bool_type\n                exprs.append(expr)\n\n            or_expr: Expression = exprs.pop(0)\n            for expr in exprs:\n                or_expr = OpExpr(bin_op, or_expr, expr)\n                builder.types[or_expr] = bool_type\n            return builder.accept(or_expr)\n        # x in [y]/(y) -> x == y\n        # x not in [y]/(y) -> x != y\n        elif n_items == 1:\n            if e.operators[0] == \"in\":\n                cmp_op = \"==\"\n            else:\n                cmp_op = \"!=\"\n            e.operators = [cmp_op]\n            e.operands[1] = items[0]\n        # x in []/() -> False\n        # x not in []/() -> True\n        elif n_items == 0:\n            if e.operators[0] == \"in\":\n                return builder.false()\n            else:\n                return builder.true()\n\n    # x in {...}\n    # x not in {...}\n    if (\n        first_op in (\"in\", \"not in\")\n        and len(e.operators) == 1\n        and isinstance(e.operands[1], SetExpr)\n    ):\n        set_literal = precompute_set_literal(builder, e.operands[1])\n        if set_literal is not None:\n            lhs = e.operands[0]\n            result = builder.builder.primitive_op(\n                set_in_op, [builder.accept(lhs), set_literal], e.line, bool_rprimitive\n            )\n            if first_op == \"not in\":\n                return builder.unary_op(result, \"not\", e.line)\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 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    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 = cast(Optional[Value], 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\ndef transform_list_comprehension(builder: IRBuilder, o: ListComprehension) -> Value:\n    return translate_list_comprehension(builder, o.generator)\n\n\ndef transform_set_comprehension(builder: IRBuilder, o: SetComprehension) -> Value:\n    return translate_set_comprehension(builder, o.generator)\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    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.primitive_op(dict_set_item_op, [builder.read(d), k, v], o.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, o.line)\n    return builder.read(d)\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    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) -> Value | None:\n    if fullname == \"math.e\":\n        return builder.load_float(math.e)\n    if fullname == \"math.pi\":\n        return builder.load_float(math.pi)\n    if fullname == \"math.inf\":\n        return builder.load_float(math.inf)\n    if fullname == \"math.nan\":\n        return builder.load_float(math.nan)\n    if fullname == \"math.tau\":\n        return builder.load_float(math.tau)\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 typing import Callable, ClassVar\n\nfrom mypy.nodes import (\n    ARG_POS,\n    CallExpr,\n    DictionaryComprehension,\n    Expression,\n    GeneratorExpr,\n    Lvalue,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    SetExpr,\n    TupleExpr,\n    TypeAlias,\n)\nfrom mypyc.ir.ops import (\n    BasicBlock,\n    Branch,\n    Integer,\n    IntOp,\n    LoadAddress,\n    LoadMem,\n    RaiseStandardError,\n    Register,\n    TupleGet,\n    TupleSet,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RTuple,\n    RType,\n    bool_rprimitive,\n    int_rprimitive,\n    is_dict_rprimitive,\n    is_fixed_width_rtype,\n    is_list_rprimitive,\n    is_sequence_rprimitive,\n    is_short_int_rprimitive,\n    is_str_rprimitive,\n    is_tuple_rprimitive,\n    pointer_rprimitive,\n    short_int_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.targets import AssignmentTarget, AssignmentTargetTuple\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\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\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) -> 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)\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)\n\n    builder.push_loop_stack(step_block, exit_block)\n\n    builder.goto_and_activate(condition_block)\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))\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: CFunctionDescription,\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)\n          (2) list(f(x) for x in a_list/a_tuple)\n          (3) [f(x) for x in a_list/a_tuple]\n    RTuple as an original sequence is not supported yet.\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        rtype = builder.node_type(gen.sequences[0])\n        if is_list_rprimitive(rtype) or is_tuple_rprimitive(rtype) or is_str_rprimitive(rtype):\n            sequence = builder.accept(gen.sequences[0])\n            length = builder.builder.builtin_len(sequence, gen.line, use_pyssize_t=True)\n            target_op = empty_op_llbuilder(length, gen.line)\n\n            def set_item(item_index: Value) -> None:\n                e = builder.accept(gen.left_expr)\n                builder.call_c(set_item_op, [target_op, item_index, e], gen.line)\n\n            for_loop_helper_with_index(\n                builder, gen.indices[0], gen.sequences[0], sequence, set_item, gen.line\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    # 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=new_list_set_item_op,\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), e], gen.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n    return builder.read(list_ops)\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), e], gen.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n    return builder.read(set_ops)\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):\n        # Special case \"for x in <list>\".\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    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(self.builder.read(expr, self.line), self.line)\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 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))\n\n        def try_body() -> None:\n            awaitable = builder.call_c(anext_op, [builder.read(self.iter_target)], line)\n            self.next_reg = emit_await(builder, awaitable, line)\n            builder.assign(self.stop_reg, builder.false(), -1)\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    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    def init(self, expr_reg: Value, target_type: RType, reverse: bool) -> None:\n        builder = self.builder\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 not reverse:\n            index_reg: Value = Integer(0)\n        else:\n            index_reg = builder.binary_op(\n                self.load_len(self.expr_target), Integer(1), \"-\", self.line\n            )\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        # TODO: Don't reload the length each time when iterating an immutable sequence?\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        # For compatibility with python semantics we recalculate the length\n        # at every iteration.\n        len_reg = self.load_len(self.expr_target)\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.int_op(\n            short_int_rprimitive,\n            builder.read(self.index_target, line),\n            Integer(step),\n            IntOp.ADD,\n            line,\n        )\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)\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)\n        builder.assign(index_reg, start_reg, -1)\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(self.index_target, self.builder.read(self.index_reg), self.line)\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"
  },
  {
    "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.primitives.bytes_ops import bytes_build_op\nfrom mypyc.primitives.int_ops import 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 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 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        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    SymbolNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.types import CallableType, get_proper_type\nfrom mypyc.common import 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    GetAttr,\n    InitStatic,\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    dict_rprimitive,\n    int_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder, SymbolTarget, 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, ImplicitClass\nfrom mypyc.irbuild.env_class import (\n    finalize_env_class,\n    load_env_registers,\n    load_outer_envs,\n    setup_env_class,\n    setup_func_for_recursive_call,\n)\nfrom mypyc.irbuild.generator import (\n    add_methods_to_generator_class,\n    add_raise_exception_blocks_to_generator_class,\n    create_switch_for_generator_class,\n    gen_generator_func,\n    populate_switch_for_generator_class,\n    setup_env_for_generator_class,\n)\nfrom mypyc.irbuild.targets import AssignmentTarget\nfrom mypyc.irbuild.util import is_constant\nfrom mypyc.primitives.dict_ops import dict_get_method_with_none, dict_new_op, dict_set_item_op\nfrom mypyc.primitives.generic_ops import 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.primitive_op(\n            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)\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) -> 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\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    builder.enter(\n        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    )\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 builder.fn_info.contains_nested or builder.fn_info.is_generator:\n        setup_env_class(builder)\n\n    if builder.fn_info.is_nested or builder.fn_info.in_non_ext:\n        setup_callable_class(builder)\n\n    if builder.fn_info.is_generator:\n        # Do a first-pass and generate a function that just returns a generator object.\n        gen_generator_func(builder)\n        args, _, blocks, ret_type, fn_info = builder.leave()\n        func_ir, func_reg = gen_func_ir(\n            builder, args, blocks, sig, fn_info, cdef, is_singledispatch\n        )\n\n        # Re-enter the FuncItem and visit the body of the function this time.\n        builder.enter(fn_info)\n        setup_env_for_generator_class(builder)\n        load_outer_envs(builder, builder.fn_info.generator_class)\n        top_level = builder.top_level_fn_info()\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(builder, fitem, builder.fn_info.generator_class)\n        create_switch_for_generator_class(builder)\n        add_raise_exception_blocks_to_generator_class(builder, fitem.line)\n    else:\n        load_env_registers(builder)\n        gen_arg_defaults(builder)\n\n    if builder.fn_info.contains_nested and not builder.fn_info.is_generator:\n        finalize_env_class(builder)\n\n    builder.ret_types[-1] = sig.ret_type\n\n    # Add all variables and functions that are declared/defined within this\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 this 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 builder.fn_info.is_nested or builder.fn_info.in_non_ext:\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(var, rtype, env_for_func, reassign=False)\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                builder.add_var_to_env_class(\n                    nested_fn, object_rprimitive, env_for_func, reassign=False\n                )\n\n    builder.accept(fitem.body)\n    builder.maybe_add_implicit_return()\n\n    if builder.fn_info.is_generator:\n        populate_switch_for_generator_class(builder)\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    if fn_info.is_generator:\n        add_methods_to_generator_class(builder, fn_info, sig, args, blocks, fitem.is_coroutine)\n    else:\n        func_ir, func_reg = gen_func_ir(\n            builder, args, blocks, sig, fn_info, cdef, is_singledispatch\n        )\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    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)\n        return gen_dispatch_func_ir(builder, fitem, fn_info.name, name, sig)\n\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        assert isinstance(fn_info.fitem, FuncDef)\n        func_decl = builder.mapper.func_to_decl[fn_info.fitem]\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                func_decl.is_prop_getter,\n                func_decl.is_prop_setter,\n            )\n            func_ir = FuncIR(\n                func_decl, args, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name\n            )\n        else:\n            func_ir = FuncIR(\n                func_decl, args, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name\n            )\n    return (func_ir, func_reg)\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        class_ir.glue_methods[(class_ir, name)] = f\n        builder.functions.append(f)\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\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\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)\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    else:\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        ),\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 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 fdef.original_def:\n        # Get the target associated with the previously defined FuncDef.\n        return builder.lookup(fdef.original_def)\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, line: int) -> Value:\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 typ.module_name in builder.imports:\n        loaded_module = builder.load_module(typ.module_name)\n        class_obj = builder.builder.get_attr(\n            loaded_module, typ.name, object_rprimitive, line, borrow=False\n        )\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.primitive_op(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 = -1\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 = -1\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, line)\n            builder.primitive_op(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    if not is_trait:\n        value = builder.builder.get_attr(self_reg, name, func_decl.sig.ret_type, -1)\n        builder.add(Return(value))\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    if not is_trait:\n        builder.add(SetAttr(self_reg, attr_name, value_reg, -1))\n    builder.add(Return(builder.none()))\n    args, _, blocks, ret_type, fn_info = builder.leave()\n    return FuncIR(func_decl, args, blocks)\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 mypy.nodes import ARG_OPT, Var\nfrom mypyc.common import ENV_ATTR_NAME, NEXT_LABEL_ATTR_NAME, SELF_NAME\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg\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 RInstance, int_rprimitive, object_rprimitive\nfrom mypyc.irbuild.builder import IRBuilder, gen_arg_defaults\nfrom mypyc.irbuild.context import FuncInfo, GeneratorClass\nfrom mypyc.irbuild.env_class import (\n    add_args_to_env,\n    finalize_env_class,\n    load_env_registers,\n    load_outer_env,\n)\nfrom mypyc.irbuild.nonlocalcontrol import ExceptNonlocalControl\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(builder: IRBuilder) -> None:\n    setup_generator_class(builder)\n    load_env_registers(builder)\n    gen_arg_defaults(builder)\n    finalize_env_class(builder)\n    builder.add(Return(instantiate_generator_class(builder)))\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    # 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 class' environment class' NEXT_LABEL_ATTR_NAME attribute to 0.\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    name = f\"{builder.fn_info.namespaced_name()}_gen\"\n\n    generator_class_ir = ClassIR(name, builder.module_name, is_generated=True)\n    generator_class_ir.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_info.env_class)\n    generator_class_ir.mro = [generator_class_ir]\n\n    builder.classes.append(generator_class_ir)\n    builder.fn_info.generator_class = GeneratorClass(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    sig: FuncSignature,\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, sig, fn_info)\n    add_next_to_generator_class(builder, fn_info, helper_fn_decl, sig)\n    add_send_to_generator_class(builder, fn_info, helper_fn_decl, sig)\n    add_iter_to_generator_class(builder, fn_info)\n    add_throw_to_generator_class(builder, fn_info, helper_fn_decl, sig)\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,\n    arg_regs: list[Register],\n    blocks: list[BasicBlock],\n    sig: FuncSignature,\n    fn_info: FuncInfo,\n) -> FuncDecl:\n    \"\"\"Generates a helper method for a generator class, called by '__next__' and 'throw'.\"\"\"\n    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        ),\n        sig.ret_type,\n    )\n    helper_fn_decl = FuncDecl(\n        \"__mypyc_generator_helper__\", fn_info.generator_class.ir.name, builder.module_name, sig\n    )\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[\"__mypyc_generator_helper__\"] = helper_fn_ir\n    builder.functions.append(helper_fn_ir)\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(\n    builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl, sig: FuncSignature\n) -> 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                [builder.self(), none_reg, none_reg, none_reg, none_reg],\n                fn_info.fitem.line,\n            )\n        )\n        builder.add(Return(result))\n\n\ndef add_send_to_generator_class(\n    builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl, sig: FuncSignature\n) -> 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                [builder.self(), none_reg, none_reg, none_reg, builder.read(arg)],\n                fn_info.fitem.line,\n            )\n        )\n        builder.add(Return(result))\n\n\ndef add_throw_to_generator_class(\n    builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl, sig: FuncSignature\n) -> 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, builder.fn_info.fitem.line)\n        builder.assign_if_null(tb, lambda: none_reg, builder.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                [builder.self(), builder.read(typ), builder.read(val), builder.read(tb), none_reg],\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            )\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    cls.exc_regs = (exc_type, exc_val, exc_tb)\n    cls.send_arg_reg = exc_arg\n\n    cls.self_reg = builder.read(self_target, fitem.line)\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), int_rprimitive, cls, reassign=False\n    )\n\n    # Add arguments from the original generator function to the\n    # environment of the generator class.\n    add_args_to_env(builder, local=False, base=cls, reassign=False)\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\nfrom collections.abc import Sequence\nfrom typing import Callable, Final, Optional\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    MAX_LITERAL_SHORT_INT,\n    MAX_SHORT_INT,\n    MIN_LITERAL_SHORT_INT,\n    MIN_SHORT_INT,\n    PLATFORM_SIZE,\n    use_method_vectorcall,\n    use_vectorcall,\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    GetElementPtr,\n    Goto,\n    Integer,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    PrimitiveDescription,\n    PrimitiveOp,\n    RaiseStandardError,\n    Register,\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    RTuple,\n    RType,\n    RUnion,\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    dict_rprimitive,\n    float_rprimitive,\n    int_rprimitive,\n    is_bit_rprimitive,\n    is_bool_rprimitive,\n    is_bytes_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_none_rprimitive,\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    list_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.options import CompilerOptions\nfrom mypyc.primitives.bytes_ops import bytes_compare\nfrom mypyc.primitives.dict_ops import (\n    dict_build_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_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    fast_isinstance_op,\n    none_object_op,\n    not_implemented_op,\n    var_object_size,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    CFunctionDescription,\n    binary_ops,\n    method_call_ops,\n    unary_ops,\n)\nfrom mypyc.primitives.set_ops import new_set_op\nfrom mypyc.primitives.str_ops import str_check_if_true, str_ssize_t_size_op, unicode_compare\nfrom mypyc.primitives.tuple_ops import list_tuple_op, new_tuple_op, new_tuple_with_length_op\nfrom mypyc.rt_subtype import is_runtime_subtype\nfrom mypyc.sametype import is_same_type\nfrom mypyc.subtype import is_subtype\n\nDictEntry = tuple[Optional[Value], 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 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], *, steal: bool = False) -> None:\n        self.add(KeepAlive(values, steal=steal))\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) -> None:\n        if self.keep_alives:\n            self.add(KeepAlive(self.keep_alives.copy()))\n            self.keep_alives = []\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))\n        else:\n            return src\n\n    def unbox_or_cast(\n        self, src: Value, target_type: RType, line: int, *, can_borrow: 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))\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                # Equivalent types\n                return src\n            elif (is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)) and is_tagged(\n                target_type\n            ):\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 (\n                is_bool_rprimitive(src_type) or is_bit_rprimitive(src_type)\n            ) 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))\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)\n\n        res = Register(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            fast2, fast3 = BasicBlock(), BasicBlock()\n            upper_bound = 1 << (size * 8 - 1)\n            if not target_type.is_signed:\n                upper_bound *= 2\n            check2 = self.add(ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT))\n            self.add(Branch(check2, fast2, slow, Branch.BOOL))\n            self.activate_block(fast2)\n            if target_type.is_signed:\n                lower_bound = -upper_bound\n            else:\n                lower_bound = 0\n            check3 = self.add(ComparisonOp(src, Integer(lower_bound, src.type), ComparisonOp.SGE))\n            self.add(Branch(check3, fast3, slow, Branch.BOOL))\n            self.activate_block(fast3)\n            tmp = 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(tmp, target_type))\n        else:\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\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        elif is_int32_rprimitive(target_type):\n            # Slow path just always generates an OverflowError\n            self.call_c(int32_overflow, [], line)\n            self.add(Unreachable())\n        elif is_int16_rprimitive(target_type):\n            # Slow path just always generates an OverflowError\n            self.call_c(int16_overflow, [], line)\n            self.add(Unreachable())\n        elif is_uint8_rprimitive(target_type):\n            # Slow path just always generates an OverflowError\n            self.call_c(uint8_overflow, [], line)\n            self.add(Unreachable())\n        else:\n            assert False, target_type\n\n        self.activate_block(end)\n        return res\n\n    def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:\n        if is_int64_rprimitive(target_type) or (\n            PLATFORM_SIZE == 4 and is_int32_rprimitive(target_type)\n        ):\n            return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)\n        # TODO: i32 on 64-bit platform\n        assert False, (src.type, target_type, PLATFORM_SIZE)\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        assert is_fixed_width_rtype(src.type)\n        assert isinstance(src.type, RPrimitive)\n        src_type = 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))\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))\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_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.add(LoadMem(object_rprimitive, ob_type_address))\n        self.add(KeepAlive([obj]))\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_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                    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            else:\n                star_result = self.primitive_op(list_tuple_op, [star_result], line)\n        if has_star2 and star2_result is None:\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        if use_vectorcall(self.options.capi_version):\n            # More recent Python versions support faster vectorcalls.\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_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 and kw_args_dict\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, 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))\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        if use_method_vectorcall(self.options.capi_version):\n            # More recent Python versions support faster vectorcalls.\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, 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))\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                assert star2_arg\n                output_arg = star2_arg\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, base.line, arg_kinds, arg_names)\n\n        # If the base type is one of ours, do a MethodCall\n        if (\n            isinstance(base.type, RInstance)\n            and base.type.class_ir.is_ext_class\n            and not base.type.class_ir.builtin_base\n        ):\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) -> Value:\n        \"\"\"Load unboxed None value (type: none_rprimitive).\"\"\"\n        return Integer(1, none_rprimitive)\n\n    def true(self) -> Value:\n        \"\"\"Load unboxed True value (type: bool_rprimitive).\"\"\"\n        return Integer(1, bool_rprimitive)\n\n    def false(self) -> Value:\n        \"\"\"Load unboxed False value (type: bool_rprimitive).\"\"\"\n        return Integer(0, bool_rprimitive)\n\n    def none_object(self) -> Value:\n        \"\"\"Load Python None value (type: object_rprimitive).\"\"\"\n        return self.add(LoadAddress(none_object_op.type, none_object_op.src, line=-1))\n\n    def load_int(self, value: int) -> 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))\n        else:\n            return Integer(value)\n\n    def load_float(self, value: float) -> Value:\n        \"\"\"Load a float literal value.\"\"\"\n        return Float(value)\n\n    def load_str(self, value: str) -> 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))\n\n    def load_bytes(self, value: bytes) -> Value:\n        \"\"\"Load a bytes literal value.\"\"\"\n        return self.add(LoadLiteral(value, bytes_rprimitive))\n\n    def load_complex(self, value: complex) -> Value:\n        \"\"\"Load a complex literal value.\"\"\"\n        return self.add(LoadLiteral(value, object_rprimitive))\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        # TODO: modify 'str' to use same interface as 'compare_bytes' as it avoids\n        # call to PyErr_Occurred()\n        if is_str_rprimitive(ltype) and is_str_rprimitive(rtype) and op in (\"==\", \"!=\"):\n            return self.compare_strings(lreg, rreg, op, line)\n        if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype) and op in (\"==\", \"!=\"):\n            return self.compare_bytes(lreg, rreg, op, line)\n        if is_bool_rprimitive(ltype) and is_bool_rprimitive(rtype) and op in BOOL_BINARY_OPS:\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                if op.endswith(\"=\"):\n                    op = op[:-1]\n                if op != \"//\":\n                    op_id = int_op_to_id[op]\n                else:\n                    op_id = IntOp.DIV\n                if is_bool_rprimitive(rtype) or is_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_rprimitive(rtype) or is_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                if op.endswith(\"=\"):\n                    op = op[:-1]\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_rprimitive(ltype) or is_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_rprimitive(ltype) or is_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        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        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        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)\n        equal = True if op == \"==\" else False\n        result = Register(bool_rprimitive)\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_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_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 unary_not(self, value: Value, line: int) -> Value:\n        mask = Integer(1, value.type, line)\n        return self.int_op(value.type, value, mask, IntOp.XOR, line)\n\n    def unary_op(self, value: Value, expr_op: str, line: int) -> Value:\n        typ = value.type\n        if is_bool_rprimitive(typ) or is_bit_rprimitive(typ):\n            if expr_op == \"not\":\n                return self.unary_not(value, line)\n            if expr_op == \"+\":\n                return value\n        if is_fixed_width_rtype(typ):\n            if expr_op == \"-\":\n                # Translate to '0 - x'\n                return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line)\n            elif expr_op == \"~\":\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            elif expr_op == \"+\":\n                return value\n        if is_float_rprimitive(typ):\n            if expr_op == \"-\":\n                return self.add(FloatNeg(value, line))\n            elif expr_op == \"+\":\n                return value\n\n        if isinstance(value, Integer):\n            # TODO: Overflow? Unsigned?\n            num = value.value\n            if is_short_int_rprimitive(typ):\n                num >>= 1\n            return Integer(-num, typ, value.line)\n        if is_tagged(typ) and expr_op == \"+\":\n            return value\n        if isinstance(value, Float):\n            return Float(-value.value, value.line)\n        if isinstance(typ, RInstance):\n            result = self.dunder_op(value, None, expr_op, line)\n            if result is not None:\n                return result\n        primitive_ops_candidates = unary_ops.get(expr_op, [])\n        target = self.matching_primitive_op(primitive_ops_candidates, [value], line)\n        assert target, \"Unsupported unary operation: %s\" % expr_op\n        return target\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]))\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], *, 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)))\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)\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))\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))\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_rprimitive(value.type) or is_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_same_type(value.type, str_rprimitive):\n            result = self.call_c(str_check_if_true, [value], value.line)\n        elif is_same_type(value.type, list_rprimitive) or is_same_type(\n            value.type, dict_rprimitive\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))\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)\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            )\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            )\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        can_borrow: bool = False,\n    ) -> Value | None:\n        matching: PrimitiveDescription | None = None\n        for desc in candidates:\n            if len(desc.arg_types) != len(args):\n                continue\n            if all(\n                # formal is not None and # TODO\n                is_subtype(actual.type, formal)\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        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 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):\n            elem_address = self.add(GetElementPtr(val, PySetObject, \"used\"))\n            size_value = self.add(LoadMem(c_pyssize_t_rprimitive, elem_address))\n            self.add(KeepAlive([val]))\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        # 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        size: Value = Integer(len(items), c_pyssize_t_rprimitive)\n        return self.call_c(new_tuple_op, [size] + items, 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    # 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)\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))\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))\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        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_eq_cmp(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value | None:\n        \"\"\"Add a equality comparison operation.\n\n        Args:\n            expr_op: either '==' or '!='\n        \"\"\"\n        ltype = lreg.type\n        rtype = rreg.type\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 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    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"
  },
  {
    "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 typing import Any, Callable, TypeVar, cast\n\nfrom mypy.build import Graph\nfrom mypy.nodes import ClassDef, Expression, 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 build_type_map, find_singledispatch_register_impls\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    singledispatch_info = find_singledispatch_register_impls(modules, errors)\n\n    result: ModuleIRs = {}\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)\n        module.accept(pbv)\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    IntersectionType,\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    RInstance,\n    RTuple,\n    RType,\n    RUnion,\n    bool_rprimitive,\n    bytes_rprimitive,\n    dict_rprimitive,\n    float_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\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.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.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.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            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, IntersectionType):\n            return object_rprimitive\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, 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)\n\n            ty = node.names.get(\"__match_args__\")\n            assert ty\n\n            match_args_type = get_proper_type(ty.type)\n            assert isinstance(match_args_type, TupleType)\n\n            match_args: list[str] = []\n\n            for item in match_args_type.items:\n                proper_item = get_proper_type(item)\n                assert isinstance(proper_item, Instance) and proper_item.last_known_value\n\n                match_arg = proper_item.last_known_value.value\n                assert isinstance(match_arg, str)\n\n                match_args.append(match_arg)\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"
  },
  {
    "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    Unreachable,\n    Value,\n)\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))\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        builder.call_c(set_stop_iteration_value, [value], NO_TRACEBACK_LINE_NO)\n        builder.add(Unreachable())\n        builder.builder.pop_error_handler()\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))\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)\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    Block,\n    Decorator,\n    Expression,\n    FuncDef,\n    FuncItem,\n    Import,\n    LambdaExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    SymbolNode,\n    Var,\n)\nfrom mypy.traverser import ExtendedTraverserVisitor\nfrom mypyc.errors import Errors\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    ) -> 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 inbetween) 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    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_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_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 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 PROPSET_PREFIX, 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 RInstance, RType, dict_rprimitive, none_rprimitive, tuple_rprimitive\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\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(cdef)\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\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.\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 isinstance(node.node, TypeInfo) and is_from_module(node.node, module):\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_STATICMETHOD\n        if fdef.is_static\n        else (FUNC_CLASSMETHOD if fdef.is_class else FUNC_NORMAL)\n    )\n    sig = mapper.fdef_to_sig(fdef, options.strict_dunders_typing)\n    decl = FuncDecl(fdef.name, class_name, module_name, sig, kind)\n    mapper.func_to_decl[fdef] = decl\n    return decl\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 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 = get_mypyc_attrs(cdef)\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    # 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\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                assert node.node.impl\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 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    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\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            defining_ir is None\n            or not defining_ir.is_ext_class\n            or cdef.info[\"__init__\"].plugin_generated\n        ) and init_node.info.fullname != \"builtins.object\":\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    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\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                    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                        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"
  },
  {
    "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 typing import Callable, Optional\n\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    BytesExpr,\n    CallExpr,\n    DictExpr,\n    Expression,\n    GeneratorExpr,\n    IntExpr,\n    ListExpr,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    StrExpr,\n    TupleExpr,\n)\nfrom mypy.types import AnyType, TypeOfAny\nfrom mypyc.ir.ops import (\n    BasicBlock,\n    Extend,\n    Integer,\n    RaiseStandardError,\n    Register,\n    Truncate,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RPrimitive,\n    RTuple,\n    RType,\n    bool_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_uint8_rprimitive,\n    list_rprimitive,\n    set_rprimitive,\n    str_rprimitive,\n    uint8_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.for_helpers import (\n    comprehension_helper,\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.primitives.dict_ops import (\n    dict_items_op,\n    dict_keys_op,\n    dict_setdefault_spec_init_op,\n    dict_values_op,\n)\nfrom mypyc.primitives.list_ops import new_list_set_item_op\nfrom mypyc.primitives.str_ops import (\n    str_encode_ascii_strict,\n    str_encode_latin1_strict,\n    str_encode_utf8_strict,\n)\nfrom mypyc.primitives.tuple_ops import 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], Optional[Value]]\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\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\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        if isinstance(expr_rtype, RTuple):\n            # len() of fixed-length tuple can be trivially determined\n            # statically, though we still need to evaluate it.\n            builder.accept(arg)\n            return Integer(len(expr_rtype.types))\n        else:\n            if is_list_rprimitive(builder.node_type(arg)):\n                borrow = True\n            else:\n                borrow = False\n            obj = builder.accept(arg, can_borrow=borrow)\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        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=new_list_set_item_op,\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)\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        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=new_tuple_set_item_op,\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    retval = Register(bool_rprimitive)\n    builder.assign(retval, initial_value(), -1)\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        builder.assign(retval, new_value(), -1)\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)\n    builder.assign(retval, builder.coerce(builder.accept(start_expr), target_type, -1), -1)\n\n    def gen_inner_stmts() -> None:\n        call_expr = builder.accept(gen_expr.left_expr)\n        builder.assign(retval, builder.binary_op(retval, call_expr, \"+\", -1), -1)\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\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 (\n        len(expr.args) == 2\n        and expr.arg_kinds == [ARG_POS, ARG_POS]\n        and isinstance(expr.args[1], (RefExpr, TupleExpr))\n    ):\n        builder.types[expr.args[0]] = AnyType(TypeOfAny.from_error)\n\n        irs = builder.flatten_classes(expr.args[1])\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(expr.args[0], can_borrow=can_borrow)\n            return builder.builder.isinstance_helper(obj, irs, expr.line)\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 (\n        isinstance(callee, MemberExpr)\n        and isinstance(callee.expr, StrExpr)\n        and expr.arg_kinds.count(ARG_POS) == len(expr.arg_kinds)\n    ):\n        format_str = callee.expr.value\n        tokens = tokenizer_format_call(format_str)\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        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(\"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.args[0]\n    if isinstance(arg, (StrExpr, BytesExpr)) and len(arg.value) == 1:\n        return Integer(ord(arg.value))\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 Sequence\nfrom typing import Callable\n\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    ListExpr,\n    Lvalue,\n    MatchStmt,\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.ir.ops import (\n    NAMESPACE_MODULE,\n    NO_TRACEBACK_LINE_NO,\n    Assign,\n    BasicBlock,\n    Branch,\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.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    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()\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 transform_assignment_stmt(builder: IRBuilder, stmt: AssignmentStmt) -> None:\n    lvalues = stmt.lvalues\n    assert lvalues\n    builder.disallow_class_assignments(lvalues, stmt.line)\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()\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        for i in range(n):\n            target = builder.get_assignment_target(first_lvalue.items[i])\n            rvalue_item = builder.add(TupleGet(rvalue_reg, i, borrow=True))\n            rvalue_item = builder.add(Unborrow(rvalue_item))\n            builder.assign(target, rvalue_item, line)\n        builder.builder.keep_alive([rvalue_reg], steal=True)\n        builder.flush_keep_alives()\n        return\n\n    for lvalue in lvalues:\n        target = builder.get_assignment_target(lvalue)\n        builder.assign(target, rvalue_reg, line)\n        builder.flush_keep_alives()\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()\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(object_pointer_rprimitive, static_ptrs)\n    import_line_ptr = builder.builder.setup_rarray(c_pyssize_t_rprimitive, mod_lines)\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))\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)\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)\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    else_body = (lambda: builder.accept(t.else_body)) if t.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    old_exc = Register(exc_rtuple)\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])), -1)\n    builder.goto(return_entry)\n\n    builder.activate_block(return_entry)\n    builder.add(Assign(old_exc, builder.add(LoadErrorValue(exc_rtuple))))\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])), -1)\n    builder.add(Assign(old_exc, builder.call_c(error_catch_op, [], -1)))\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    reraise, rest = BasicBlock(), BasicBlock()\n    builder.add(Branch(old_exc, rest, reraise, Branch.IS_ERROR))\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())\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        builder.add(Branch(builder.read(ret_reg), rest, return_block, Branch.IS_ERROR))\n\n        builder.activate_block(return_block)\n        builder.nonlocal_control[-1].gen_return(builder, builder.read(ret_reg), -1)\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, -1)\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\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_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    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        transform_try_finally_stmt(builder, transform_try_body, lambda: builder.accept(body))\n    else:\n        transform_try_except_stmt(builder, t)\n\n\ndef get_sys_exc_info(builder: IRBuilder) -> list[Value]:\n    exc_info = builder.call_c(get_exc_info_op, [], -1)\n    return [builder.add(TupleGet(exc_info, i, -1)) 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)\n            exit_val = builder.gen_method_call(\n                builder.read(mgr),\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(builder.read(exit_), [builder.read(mgr)] + args, line)\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), 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    )\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))\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)\n    to_yield_reg = Register(object_rprimitive)\n    received_reg = Register(object_rprimitive)\n\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    _y_init = builder.call_c(next_raw_op, [builder.read(iter_reg)], line)\n    builder.add(Branch(_y_init, stop_block, main_block, Branch.IS_ERROR))\n\n    # Try extracting a return value from a StopIteration and return it.\n    # If it wasn't, this reraises the exception.\n    builder.activate_block(stop_block)\n    builder.assign(result, builder.call_c(check_stop_op, [], line), 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(received_reg, emit_yield(builder, builder.read(to_yield_reg), line), line)\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(yield_from_except_op, [builder.read(iter_reg), val_address], line)\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(send_op, [builder.read(iter_reg), builder.read(received_reg)], line)\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)\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\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\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\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"
  },
  {
    "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\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\n\nDATACLASS_DECORATORS = {\"dataclasses.dataclass\", \"attr.s\", \"attr.attrs\"}\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    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(stmt: ClassDef | Decorator) -> dict[str, Any]:\n    \"\"\"Collect all the mypyc_attr attributes on a class definition or a function.\"\"\"\n    attrs: dict[str, Any] = {}\n    for dec in stmt.decorators:\n        d = get_mypyc_attr_call(dec)\n        if d:\n            for name, arg in zip(d.arg_names, d.args):\n                if name is None:\n                    if isinstance(arg, StrExpr):\n                        attrs[arg.value] = True\n                else:\n                    attrs[name] = get_mypyc_attr_literal(arg)\n\n    return attrs\n\n\ndef is_extension_class(cdef: ClassDef) -> bool:\n    if any(\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        for d in cdef.decorators\n    ):\n        return False\n    if cdef.info.typeddict_type:\n        return False\n    if cdef.info.is_named_tuple:\n        return False\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 False\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/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    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\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_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_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] + cls.traits:\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\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);\n\nPyObject *CPyTagged_Str(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        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    }\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(PyObject *p) {\n    CPy_XDECREF(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_GetItemUnsafe(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);\nbool CPyList_SetItemUnsafe(PyObject *list, CPyTagged 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_Multiply(PyObject *seq, CPyTagged t_size);\nPyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq);\nPyObject *CPyList_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);\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, CPyTagged size) {\n    if (!PyDict_CheckExact(dict)) {\n        // Dict subclasses will be checked by Python runtime.\n        return 1;\n    }\n    Py_ssize_t py_size = CPyTagged_AsSsize_t(size);\n    Py_ssize_t dict_size = PyDict_Size(dict);\n    if (py_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\nPyObject *CPyStr_Build(Py_ssize_t len, ...);\nPyObject *CPyStr_GetItem(PyObject *str, CPyTagged index);\nPyObject *CPyStr_Split(PyObject *str, PyObject *sep, CPyTagged max_split);\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);\nbool CPyStr_Startswith(PyObject *self, PyObject *subobj);\nbool CPyStr_Endswith(PyObject *self, PyObject *subobj);\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_Encode(PyObject *obj, PyObject *encoding, PyObject *errors);\nCPyTagged CPyStr_Ord(PyObject *obj);\n\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);\n\n\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);\nbool CPySequenceTuple_SetItemUnsafe(PyObject *tuple, CPyTagged 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\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);\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 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                                  _Py_Identifier *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);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // CPY_CPY_H\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    if (PyBytes_Check(a) && PyBytes_Check(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    } else if (PyByteArray_Check(a)) {\n        return PyByteArray_Concat(a, b);\n    } else {\n        PyBytes_Concat(&a, b);\n        return a;\n    }\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 ((PyBytes_Check(obj) || PyByteArray_Check(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        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        _Py_IDENTIFIER(join);\n        return _PyObject_CallMethodIdOneArg(sep, &PyId_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\n\nCPyTagged CPyBytes_Ord(PyObject *obj) {\n    if (PyBytes_Check(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    } else if (PyByteArray_Check(obj)) {\n        Py_ssize_t s = PyByteArray_GET_SIZE(obj);\n        if (s == 1) {\n            return (unsigned char)(PyByteArray_AS_STRING(obj)[0]) << 1;\n        }\n    }\n    PyErr_SetString(PyExc_TypeError, \"ord() expects a character\");\n    return CPY_INT_TAG;\n}\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    _Py_IDENTIFIER(setdefault);\n    PyObject *name = _PyUnicode_FromId(&PyId_setdefault); /* borrowed */\n    if (name == NULL) {\n        return NULL;\n    }\n    return PyObject_CallMethodObjArgs(dict, name, 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    _Py_IDENTIFIER(update);\n    PyObject *name = _PyUnicode_FromId(&PyId_update); /* borrowed */\n    if (name == NULL) {\n        return -1;\n    }\n    PyObject *res = PyObject_CallMethodOneArg(dict, name, 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        _Py_IDENTIFIER(keys);\n        if (PyDict_Check(stuff) || _CPyObject_HasAttrId(stuff, &PyId_keys)) {\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        _Py_IDENTIFIER(keys);\n        if (_CPyObject_HasAttrId(obj, &PyId_keys)) {\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    _Py_IDENTIFIER(keys);\n    return _PyObject_CallMethodIdNoArgs(dict, &PyId_keys);\n}\n\nPyObject *CPyDict_ValuesView(PyObject *dict) {\n    if (PyDict_CheckExact(dict)){\n        return _CPyDictView_New(dict, &PyDictValues_Type);\n    }\n    _Py_IDENTIFIER(values);\n    return _PyObject_CallMethodIdNoArgs(dict, &PyId_values);\n}\n\nPyObject *CPyDict_ItemsView(PyObject *dict) {\n    if (PyDict_CheckExact(dict)){\n        return _CPyDictView_New(dict, &PyDictItems_Type);\n    }\n    _Py_IDENTIFIER(items);\n    return _PyObject_CallMethodIdNoArgs(dict, &PyId_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    _Py_IDENTIFIER(keys);\n    PyObject *view = _PyObject_CallMethodIdNoArgs(dict, &PyId_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    _Py_IDENTIFIER(values);\n    PyObject *view = _PyObject_CallMethodIdNoArgs(dict, &PyId_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    _Py_IDENTIFIER(items);\n    PyObject *view = _PyObject_CallMethodIdNoArgs(dict, &PyId_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        _Py_IDENTIFIER(clear);\n        PyObject *res = _PyObject_CallMethodIdNoArgs(dict, &PyId_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    _Py_IDENTIFIER(copy);\n    return _PyObject_CallMethodIdNoArgs(dict, &PyId_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    _Py_IDENTIFIER(items);\n    PyObject *view = _PyObject_CallMethodIdNoArgs(dict, &PyId_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    _Py_IDENTIFIER(values);\n    PyObject *view = _PyObject_CallMethodIdNoArgs(dict, &PyId_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": "// 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) && value == Py_None) {\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_GetAttrString(type, \"__module__\");\n    if (!module || !PyUnicode_Check(module)) {\n        goto out;\n    }\n    name = PyObject_GetAttrString(type, \"__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\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        return CPy_DomainError();\n    }\n    return v;\n}\n\ndouble CPyFloat_Cos(double x) {\n    double v = cos(x);\n    if (unlikely(isnan(v)) && !isnan(x)) {\n        return CPy_DomainError();\n    }\n    return v;\n}\n\ndouble CPyFloat_Tan(double x) {\n    if (unlikely(isinf(x))) {\n        return CPy_DomainError();\n    }\n    return tan(x);\n}\n\ndouble CPyFloat_Sqrt(double x) {\n    if (x < 0.0) {\n        return CPy_DomainError();\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        return CPy_DomainError();\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/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"
  },
  {
    "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    char c = *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, *msg;\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\nstruct ExcDummyStruct _CPy_ExcDummyStruct = { PyObject_HEAD_INIT(NULL) };\nPyObject *_CPy_ExcDummy = (PyObject *)&_CPy_ExcDummyStruct;\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"
  },
  {
    "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#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\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\nstatic void CPyLong_NormalizeUnsigned(PyLongObject *v) {\n    Py_ssize_t i = CPY_LONG_SIZE_UNSIGNED(v);\n    while (i > 0 && CPY_LONG_DIGIT(v, i - 1) == 0)\n        i--;\n    CPyLong_SetUnsignedSize(v, i);\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    PyLongObject *r;\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    r = _PyLong_New(op == '&' ? asize : bsize);\n    if (unlikely(r == NULL)) {\n        CPyError_OutOfMemory();\n    }\n    Py_ssize_t i;\n    if (op == '&') {\n        for (i = 0; i < asize; i++) {\n            CPY_LONG_DIGIT(r, i) = adigits[i] & bdigits[i];\n        }\n    } else {\n        if (op == '|') {\n            for (i = 0; i < asize; i++) {\n                CPY_LONG_DIGIT(r, i) = adigits[i] | bdigits[i];\n            }\n        } else {\n            for (i = 0; i < asize; i++) {\n                CPY_LONG_DIGIT(r, i) = adigits[i] ^ bdigits[i];\n            }\n        }\n        for (; i < bsize; i++) {\n            CPY_LONG_DIGIT(r, i) = bdigits[i];\n        }\n    }\n    CPyLong_NormalizeUnsigned(r);\n    return CPyTagged_StealFromObject((PyObject *)r);\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_OverflowError, \"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_OverflowError, \"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_OverflowError, \"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_OverflowError, \"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_OverflowError, \"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_OverflowError, \"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_OverflowError, \"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"
  },
  {
    "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\nPyObject *CPyList_GetItemUnsafe(PyObject *list, CPyTagged index) {\n    Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n    PyObject *result = PyList_GET_ITEM(list, n);\n    Py_INCREF(result);\n    return result;\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.\nbool CPyList_SetItemUnsafe(PyObject *list, CPyTagged index, PyObject *value) {\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\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\nPyObject *CPyList_PopLast(PyObject *obj)\n{\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 *)obj, -1);\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        return list_pop_impl((PyListObject *)obj, n);\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_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 *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": "// 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    _Py_IDENTIFIER(send);\n    if (Py_IsNone(val)) {\n        return CPyIter_Next(iter);\n    } else {\n        return _PyObject_CallMethodIdOneArg(iter, &PyId_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    _Py_IDENTIFIER(close);\n    _Py_IDENTIFIER(throw);\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_GetAttrId(iter, &PyId_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_GetAttrId(iter, &PyId_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                }\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_GetAttrString((PyObject *)metaclass, \"__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    // 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_SetAttrString((PyObject *)t, \"__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_GetAttrString((PyObject *)t, \"__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_SetAttrString((PyObject *)t, \"__module__\", modname) < 0)\n        goto error;\n\n    if (init_subclass((PyTypeObject *)t, NULL))\n        goto error;\n\n    Py_XDECREF(dummy_class);\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\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_GetAttrString((PyObject *)Py_TYPE(obj), \"__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\nvoid CPyDebug_Print(const char *msg) {\n    printf(\"%s\\n\", msg);\n    fflush(stdout);\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_GetAttrString(builtins, \"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 (*mod_static == Py_None) {\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                        _Py_Identifier *method) {\n    // Look up reverse method\n    PyObject *m = _PyObject_GetAttrId(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_GetAttrString(singledispatch_func, \"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_GetAttrString(singledispatch_func, \"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_GetAttrString(typing, \"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_GetAttrString(singledispatch_func, \"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#ifdef 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"
  },
  {
    "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/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// 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// 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\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.12 or newer?\n#define CPY_3_12_FEATURES (PY_VERSION_HEX >= 0x030c0000)\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\nstatic inline void CPyLong_SetUnsignedSize(PyLongObject *o, Py_ssize_t n) {\n    if (n == 0)\n        o->long_value.lv_tag = CPY_SIGN_ZERO;\n    else\n        o->long_value.lv_tag = n << CPY_NON_SIZE_BITS;\n}\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\nstatic inline void CPyLong_SetUnsignedSize(PyLongObject *o, Py_ssize_t n) {\n    o->ob_base.ob_size = n;\n}\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#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\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#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\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 (*pobj != NULL);\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_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 %T\", str);\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#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#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 \"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_call.h\"  // _PyObject_CallMethodIdNoArgs, _PyObject_CallMethodIdOneArg\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\n/////////////////////////////////////////\n// Adapted from bltinmodule.c in Python 3.7.0\n_Py_IDENTIFIER(__mro_entries__);\nstatic PyObject*\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_GetOptionalAttrString(base, PyId___mro_entries__.string, &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\n_Py_IDENTIFIER(__init_subclass__);\nstatic int\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_GetAttrId(super, &PyId___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\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 PY_VERSION_HEX >= 0x030A0000  // 3.10\nstatic int\n_CPyObject_HasAttrId(PyObject *v, _Py_Identifier *name) {\n    PyObject *tmp = NULL;\n    int result = PyObject_GetOptionalAttrString(v, name->string, &tmp);\n    if (tmp) {\n        Py_DECREF(tmp);\n    }\n    return result;\n}\n#else\n#define _CPyObject_HasAttrId _PyObject_HasAttrId\n#endif\n\n#if PY_VERSION_HEX < 0x03090000\n// OneArgs and NoArgs functions got added in 3.9\n#define _PyObject_CallMethodIdNoArgs(self, name) \\\n    _PyObject_CallMethodIdObjArgs((self), (name), NULL)\n#define _PyObject_CallMethodIdOneArg(self, name, arg) \\\n    _PyObject_CallMethodIdObjArgs((self), (name), (arg), NULL)\n#define PyObject_CallMethodOneArg(self, name, arg) \\\n    PyObject_CallMethodObjArgs((self), (name), (arg), NULL)\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 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.command.build_ext import build_ext\nfrom distutils.core import Extension, setup\nfrom typing import Any\n\nkwargs: dict[str, Any]\nif sys.platform == \"darwin\":\n    kwargs = {\"language\": \"c++\"}\n    compile_args = []\nelse:\n    kwargs = {}\n    compile_args = [\"--std=c++11\"]\n\n\nclass build_ext_custom(build_ext):  # noqa: N801\n    def get_library_names(self):\n        return [\"gtest\"]\n\n    def run(self):\n        gtest_dir = os.path.abspath(\n            os.path.join(os.path.dirname(__file__), \"..\", \"external\", \"googletest\")\n        )\n\n        os.makedirs(self.build_temp, exist_ok=True)\n\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        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\n        self.library_dirs = [self.build_temp]\n\n        return build_ext.run(self)\n\n\nsetup(\n    name=\"test_capi\",\n    version=\"0.1\",\n    ext_modules=[\n        Extension(\n            \"test_capi\",\n            [\n                \"test_capi.cc\",\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            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\": build_ext_custom},\n)\n"
  },
  {
    "path": "mypyc/lib-rt/str_ops.c",
    "content": "// String primitive operations\n//\n// These are registered in mypyc.primitives.str_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\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            PyObject *unicode = PyUnicode_New(1, ch);\n            if (unicode == NULL)\n                return NULL;\n\n            if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {\n                PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;\n            } else 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\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    assert(_PyUnicode_CheckConsistency(res, 1));\n    return res;\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_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\nbool CPyStr_Startswith(PyObject *self, PyObject *subobj) {\n    Py_ssize_t start = 0;\n    Py_ssize_t end = PyUnicode_GET_LENGTH(self);\n    return PyUnicode_Tailmatch(self, subobj, start, end, -1);\n}\n\nbool CPyStr_Endswith(PyObject *self, PyObject *subobj) {\n    Py_ssize_t start = 0;\n    Py_ssize_t end = PyUnicode_GET_LENGTH(self);\n    return PyUnicode_Tailmatch(self, subobj, start, end, 1);\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_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\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"
  },
  {
    "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/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// PyTuple_SET_ITEM does no error checking,\n// and should only be used to fill in brand new tuples.\nbool CPySequenceTuple_SetItemUnsafe(PyObject *tuple, CPyTagged index, PyObject *value)\n{\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        PyTuple_SET_ITEM(tuple, n, value);\n        return true;\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return false;\n    }\n}\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, IncRef, Integer, IntOp, LoadMem, 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)\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.add(LoadMem(pointer_rprimitive, ob_item_ptr, line))\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    value = builder.add(LoadMem(object_rprimitive, item_ptr, line))\n    builder.add(IncRef(value))\n    return value\n"
  },
  {
    "path": "mypyc/lower/misc_ops.py",
    "content": "from __future__ import annotations\n\nfrom mypyc.ir.ops import GetElementPtr, LoadMem, Value\nfrom mypyc.ir.rtypes import PyVarObject, c_pyssize_t_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))\n"
  },
  {
    "path": "mypyc/lower/registry.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable, Final\n\nfrom mypyc.ir.ops import Value\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\n\nLowerFunc = Callable[[LowLevelIRBuilder, list[Value], int], Value]\n\n\nlowering_registry: Final[dict[str, LowerFunc]] = {}\n\n\ndef lower_primitive_op(name: str) -> Callable[[LowerFunc], LowerFunc]:\n    \"\"\"Register a handler that generates low-level IR for a primitive op.\"\"\"\n\n    def wrapper(f: LowerFunc) -> LowerFunc:\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.\n    \"\"\"\n\n    def __init__(self, groups: Iterable[list[str]]) -> 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        self.module_map: dict[str, str] = {}\n        for names in groups:\n            self.module_map.update(make_module_translation_map(names))\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    ) -> 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"
  },
  {
    "path": "mypyc/primitives/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/primitives/bytes_ops.py",
    "content": "\"\"\"Primitive bytes ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_MAGIC\nfrom mypyc.ir.rtypes import (\n    RUnion,\n    bytes_rprimitive,\n    c_int_rprimitive,\n    c_pyssize_t_rprimitive,\n    dict_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    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# bytearray(obj)\nfunction_op(\n    name=\"builtins.bytearray\",\n    arg_types=[object_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"PyByteArray_FromObject\",\n    error_kind=ERR_MAGIC,\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\n# bytearray + bytearray\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[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# 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"
  },
  {
    "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.\nfunction_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# 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# 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, int_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\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# 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    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"
  },
  {
    "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    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 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"
  },
  {
    "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    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 binary_op, custom_op, function_op, load_address_op, unary_op\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\n# str(int)\nint_to_str_op = function_op(\n    name=\"builtins.str\",\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\n# We need a specialization for str on bools also since the int one is wrong...\nfunction_op(\n    name=\"builtins.str\",\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\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"
  },
  {
    "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)\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# 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\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 short 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, short_int_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, int_rprimitive, object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyList_SetItemUnsafe\",\n    error_kind=ERR_FALSE,\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)\nlist_pop = method_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 * 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[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.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_pointer_rprimitive,\n    c_pyssize_t_rprimitive,\n    dict_rprimitive,\n    int_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    str_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)\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# 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=\"PyObject_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# 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"
  },
  {
    "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 = func_op(name='builtins.len',\n                      arg_types=[list_rprimitive],\n                      result_type=short_int_rprimitive,\n                      error_kind=ERR_NEVER,\n                      emit=emit_len)\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 emit_len is used\nto generate C for this op.  The op can also be manually generated using\n\"list_len_op\". Ops that are only generated automatically don't need to\nbe assigned to a module attribute.\n\nOps defined with custom_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.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\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) -> 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    )\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) -> 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    )\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) -> 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    )\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) -> 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    )\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) -> 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    )\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) -> 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    )\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.bytes_ops\nimport mypyc.primitives.dict_ops\nimport mypyc.primitives.float_ops\nimport mypyc.primitives.int_ops\nimport mypyc.primitives.list_ops\nimport mypyc.primitives.misc_ops\nimport mypyc.primitives.str_ops\nimport mypyc.primitives.tuple_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\nfrom mypyc.ir.rtypes import (\n    bit_rprimitive,\n    bool_rprimitive,\n    c_int_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# frozenset(obj)\nfunction_op(\n    name=\"builtins.frozenset\",\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyFrozenSet_New\",\n    error_kind=ERR_MAGIC,\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# 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.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    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    str_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 '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# 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\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# 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# 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.startswith(str)\nmethod_op(\n    name=\"startswith\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_Startswith\",\n    error_kind=ERR_NEVER,\n)\n\n# str.endswith(str)\nmethod_op(\n    name=\"endswith\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_Endswith\",\n    error_kind=ERR_NEVER,\n)\n\n# str.split(...)\nstr_split_types: list[RType] = [str_rprimitive, str_rprimitive, int_rprimitive]\nstr_split_functions = [\"PyUnicode_Split\", \"PyUnicode_Split\", \"CPyStr_Split\"]\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\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# 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# obj.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# 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"
  },
  {
    "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_FALSE, ERR_MAGIC\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)\nfrom mypyc.primitives.registry import 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# 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\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, int_rprimitive, object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPySequenceTuple_SetItemUnsafe\",\n    error_kind=ERR_FALSE,\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.\nfunction_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# 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/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    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    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_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    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_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    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) -> 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(is_subtype(left_item, right_item) for right_item in right.items):\n                    return False\n            return True\n        else:\n            return any(is_subtype(left, item) for item in right.items)\n    return left.accept(SubtypeVisitor(right))\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) -> None:\n        self.right = right\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_runion(self, left: RUnion) -> bool:\n        return all(is_subtype(item, self.right) 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        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) 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/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)\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)\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_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.ops import PrimitiveDescription\nfrom mypyc.primitives import registry\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        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                if isinstance(ops, PrimitiveDescription):\n                    ops = [ops]\n                for op in 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        env[\"__MYPY_UNDER_TEST__\"] = \"1\"\n\n        out = b\"\"\n        try:\n            # Compile program\n            cmd = subprocess.run(\n                [sys.executable, \"-m\", \"mypyc\", \"--no-strict\", *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.ir.ops import BasicBlock, Register, Value\nfrom mypyc.ir.rtypes import RTuple, bool_rprimitive, int_rprimitive, str_rprimitive\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\"]]))\n\n    def test_label(self) -> None:\n        emitter = Emitter(self.context, {})\n        assert 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        emitter = Emitter(self.context, {})\n        assert emitter.object_annotation(\"hello, world\", \"line;\") == \" /* 'hello, world' */\"\n        assert (\n            emitter.object_annotation(list(range(30)), \"line;\")\n            == \"\"\"\\\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\n    def test_emit_line(self) -> None:\n        emitter = Emitter(self.context, {})\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 (\n            emitter.fragments[1]\n            == \"\"\"\\\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\n    def test_emit_undefined_value_for_simple_type(self) -> None:\n        emitter = Emitter(self.context, {})\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 = Emitter(self.context, {})\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"
  },
  {
    "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 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    DecRef,\n    Extend,\n    GetAttr,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    Integer,\n    IntOp,\n    LoadAddress,\n    LoadMem,\n    Op,\n    Register,\n    Return,\n    SetAttr,\n    SetMem,\n    TupleGet,\n    Unbox,\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    bool_rprimitive,\n    c_int_rprimitive,\n    dict_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    short_int_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        ir = ClassIR(\"A\", \"mod\")\n        ir.attributes = {\n            \"x\": bool_rprimitive,\n            \"y\": int_rprimitive,\n            \"i1\": int64_rprimitive,\n            \"i2\": int32_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\n        self.context = EmitterContext(NameGenerator([[\"mod\"]]))\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_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_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_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 assert_emit(\n        self,\n        op: 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        block.ops.append(op)\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\"]])), 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\"]])), 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\"]]))\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)\n                    insert_exception_handling(fn)\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\n\nbase_dir = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n\n\nclass TestExternal(unittest.TestCase):\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                ],\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 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-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-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]\n\nif sys.version_info >= (3, 10):\n    files.append(\"irbuild-match.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        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            \"    goto L1\",\n            \"  ERR: 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()\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)\n                    insert_exception_handling(fn)\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_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"
  },
  {
    "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)\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())\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())\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)\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\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 mypy.util import safe\nfrom mypyc.build import construct_groups\nfrom mypyc.codegen import emitmodule\nfrom mypyc.errors import Errors\nfrom mypyc.options import CompilerOptions\nfrom mypyc.test.config import test_data_prefix\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    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-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-python37.test\",\n    \"run-python38.test\",\n]\n\nif sys.version_info >= (3, 10):\n    files.append(\"run-match.test\")\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='{}'),\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        # 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        bench = testcase.config.getoption(\"--bench\", False) and \"Benchmark\" in testcase.name\n\n        from mypy import options as mypy_options\n\n        mypy_options._based = False\n        options = Options()\n        options.default_return = False\n        options.infer_function_types = False\n        options.bare_literals = False\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.strict_optional = 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\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)\n\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            )\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            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\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 = int(os.environ.get(\"MYPYC_OPT_LEVEL\", 0))\n        debug_level = int(os.environ.get(\"MYPYC_DEBUG_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        with open(setup_file, \"w\", encoding=\"utf-8\") as f:\n            f.write(\n                setup_format.format(\n                    module_paths, separate, cfiles, self.multi_file, opt_level, debug_level\n                )\n            )\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 \"Debuggging 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(safe(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, dict):\n        assert x.keys() == y.keys(), f\"Keys mismatch at {trail}\"\n        for k in x.keys():\n            assert_blobs_same(x[k], y[k], trail + (k,))\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 Iterator\nfrom typing import Callable\n\nfrom mypy import build\nfrom mypy.errors import CompileError\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 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).functions\n\n\ndef build_ir_for_single_file2(\n    input_lines: list[str], compiler_options: CompilerOptions | None = None\n) -> ModuleIR:\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, 7))\n    import mypy.options\n\n    mypy.options._based = False\n    options = Options()\n    options.show_error_context = False\n    options.default_return = False\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, 6)\n    options.export_types = True\n    options.preserve_asts = True\n    options.allow_empty_bodies = 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    if result.errors:\n        raise CompileError(result.errors)\n\n    errors = Errors(options)\n    modules = build_ir(\n        [result.files[\"__main__\"]],\n        result.graph,\n        result.types,\n        Mapper({\"__main__\": None}),\n        compiler_options,\n        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    return module\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(strip_asserts=\"StripAssert\" in name, capi_version=(3, 7))\n    # A suffix like _python3.8 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    return options\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, List, Set, Optional, cast\nfrom typing_extensions import Final\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_extensions 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"
  },
  {
    "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/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 testErrorOutput]\n# cmd: test.py\n\n[file test.py]\nfrom typing import List, Any, AsyncIterable\nfrom typing_extensions import Final\nfrom mypy_extensions import trait, mypyc_attr\nfrom functools import singledispatch\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 NeverMetaclass(type):  # E: Inheriting from most builtin types is unimplemented\n    pass\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\n@decorator\nclass NonExt(Concrete1):  # E: Non-extension classes may not inherit from extension classes\n    pass\n\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\nclass NopeMultipleInheritanceAndBadOrder3(Trait1, Concrete1, Concrete2):  # E: Non-trait base must appear first in parent list # E: Multiple inheritance is not supported (except for traits)\n    pass\n\nclass NopeBadOrder(Trait1, Concrete2):  # E: Non-trait base must appear first in parent list\n    pass\n\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@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 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"
  },
  {
    "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\n\nfailures = []\n\nfor name in dir(native):\n    if name.startswith('test_'):\n        test_func = getattr(native, name)\n        try:\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"
  },
  {
    "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_extensions 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, r9 :: object\n    r10 :: bit\n    r11 :: 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_CallFunctionObjArgs(r2, 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 = PyObject_CallFunctionObjArgs(r8, r5, 0)\n    dec_ref r8\n    if is_error(r9) 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    r10 = CPy_KeepPropagating()\n    if not r10 goto L9 else goto L7 :: bool\nL7:\n    unreachable\nL8:\n    return 1\nL9:\n    r11 = <error> :: None\n    return r11\nL10:\n    dec_ref r3\n    goto L8\nL11:\n    dec_ref r9\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, r14 :: object\n    r15 :: bit\n    r16 :: 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_CallFunctionObjArgs(r2, 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 = PyObject_CallFunctionObjArgs(r13, r10, 0)\n    dec_ref r13\n    if is_error(r14) 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    r15 = CPy_KeepPropagating()\n    if not r15 goto L18 else goto L16 :: bool\nL16:\n    unreachable\nL17:\n    unreachable\nL18:\n    r16 = <error> :: str\n    return r16\nL19:\n    dec_ref r3\n    goto L3\nL20:\n    xdec_ref r5\n    goto L13\nL21:\n    dec_ref r14\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\n    r10 :: None\nL0:\n    r0 = <error> :: str\n    v = r0\n    r1 = 'a'\n    inc_ref r1\n    u = r1\nL1:\n    if b goto L10 else goto L11 :: bool\nL2:\n    r2 = 'b'\n    inc_ref r2\n    v = r2\n    r3 = v == u\n    r4 = r3 ^ 1\n    if r4 goto L11 else goto L1 :: bool\nL3:\n    r5 = builtins :: module\n    r6 = 'print'\n    r7 = CPyObject_GetAttr(r5, r6)\n    if is_error(r7) goto L12 (error at f:7) else goto L4\nL4:\n    if is_error(v) goto L13 else goto L7\nL5:\n    r8 = raise UnboundLocalError('local variable \"v\" referenced before assignment')\n    if not r8 goto L9 (error at f:7) else goto L6 :: bool\nL6:\n    unreachable\nL7:\n    r9 = PyObject_CallFunctionObjArgs(r7, v, 0)\n    dec_ref r7\n    xdec_ref v\n    if is_error(r9) goto L9 (error at f:7) else goto L14\nL8:\n    return 1\nL9:\n    r10 = <error> :: None\n    return r10\nL10:\n    xdec_ref v\n    goto L2\nL11:\n    dec_ref u\n    goto L3\nL12:\n    xdec_ref v\n    goto L9\nL13:\n    dec_ref r7\n    goto L5\nL14:\n    dec_ref r9\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:-1) 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"
  },
  {
    "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    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    def __init__(self) -> None: pass\n    def __eq__(self, x: object) -> bool: pass\n    def __ne__(self, x: object) -> bool: pass\n\nclass type:\n    def __init__(self, o: object) -> None: ...\n    def __or__(self, o: 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\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 split(self, sep: Optional[str] = None, max: Optional[int] = None) -> List[str]: pass\n    def strip (self, item: str) -> str: pass\n    def join(self, x: Iterable[str]) -> str: pass\n    def format(self, *args: Any, **kwargs: Any) -> str: ...\n    def upper(self) -> str: ...\n    def startswith(self, x: str, start: int=..., end: int=...) -> bool: ...\n    def endswith(self, x: 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\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) -> 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, x: str=..., y: str=...) -> str: ...\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: ...\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 join(self, __iterable_of_bytes: Iterable[bytes]) -> bytearray: ...\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\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 __iter__(self) -> Iterator[_T]: pass\n    def __len__(self) -> int: pass\n    def __contains__(self, item: object) -> int: ...\n    def __add__(self, x: List[_T]) -> List[_T]: ...\n    def append(self, x: _T) -> None: pass\n    def pop(self, i: int = -1) -> _T: pass\n    def count(self, _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\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 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\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\ndef sum(i: Iterable[_T]) -> int: 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(*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 getattr(obj: object, name: str, default: Any = None) -> Any: ...\ndef setattr(obj: object, name: str, value: Any) -> 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 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\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 Exception 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"
  },
  {
    "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): ...\n\ncast = 0\noverload = 0\nAny = object()\nOptional = 0\nTypeVar = 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\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\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\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    a.a = n\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\n    r6 :: str\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\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    r6 = 'a'\n    r7 = box(int, n)\n    r8 = PyObject_SetAttr(a, r6, r7)\n    r9 = r8 >= 0 :: signed\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-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, r4 :: object\n    r5 :: int\nL0:\n    r0 = testmodule :: module\n    r1 = 'factorial'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = box(int, x)\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\n    r5 = unbox(int, r4)\n    return r5\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_CallFunctionObjArgs(r35, 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, r4 :: object\n    r5 :: int\n    r6 :: dict\n    r7 :: str\n    r8, r9 :: object\n    r10, r11 :: int\n    r12 :: dict\n    r13 :: str\n    r14, r15 :: object\n    r16, r17 :: int\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'g'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = box(int, x)\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\n    r5 = unbox(int, r4)\n    r6 = __main__.globals :: static\n    r7 = 'h'\n    r8 = CPyDict_GetItem(r6, r7)\n    r9 = PyObject_CallFunctionObjArgs(r8, 0)\n    r10 = unbox(int, r9)\n    r11 = CPyTagged_Add(r5, r10)\n    r12 = __main__.globals :: static\n    r13 = 'two'\n    r14 = CPyDict_GetItem(r12, r13)\n    r15 = PyObject_CallFunctionObjArgs(r14, 0)\n    r16 = unbox(int, r15)\n    r17 = CPyTagged_Add(r11, r16)\n    return r17\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, r4 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'print'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = object 5\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\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, r4 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'print'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = object 5\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\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]\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\n    r2, y :: int\n    r3 :: str\n    r4 :: object\n    r5 :: int\nL0:\n    r0 = 'pop'\n    r1 = CPyObject_CallMethodObjArgs(x, r0, 0)\n    r2 = unbox(int, r1)\n    y = r2\n    r3 = 'pop'\n    r4 = CPyObject_CallMethodObjArgs(x, r3, 0)\n    r5 = unbox(int, r4)\n    return r5\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, r4 :: object\n    r5 :: int\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'f'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = box(int, x)\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\n    r5 = unbox(int, r4)\n    return r5\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_CallFunctionObjArgs(f, 0)\n    r2 = unbox(float, r1)\n    return r2\n\n[case testCallableTypesWithKeywordArgs]\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 :: object\n    r1 :: str\n    r2 :: tuple\n    r3 :: object\n    r4 :: dict\n    r5 :: object\n    r6 :: int\nL0:\n    r0 = load_address PyLong_Type\n    r1 = 'base'\n    r2 = PyTuple_Pack(1, x)\n    r3 = object 2\n    r4 = CPyDict_Build(1, r1, r3)\n    r5 = PyObject_Call(r0, r2, r4)\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 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: tuple\n    r5 :: object\n    r6 :: dict\n    r7 :: object\n    r8 :: str\n    r9 :: object\n    r10, r11 :: str\n    r12 :: tuple\n    r13, r14 :: object\n    r15 :: dict\n    r16 :: object\nL0:\n    r0 = 'insert'\n    r1 = CPyObject_GetAttr(xs, r0)\n    r2 = 'x'\n    r3 = object 0\n    r4 = PyTuple_Pack(1, r3)\n    r5 = box(int, first)\n    r6 = CPyDict_Build(1, r2, r5)\n    r7 = PyObject_Call(r1, r4, r6)\n    r8 = 'insert'\n    r9 = CPyObject_GetAttr(xs, r8)\n    r10 = 'x'\n    r11 = 'i'\n    r12 = PyTuple_Pack(0)\n    r13 = box(int, second)\n    r14 = object 1\n    r15 = CPyDict_Build(2, r10, r13, r11, r14)\n    r16 = PyObject_Call(r9, r12, r15)\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_CallFunctionObjArgs(r2, 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, r8 :: 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 = PyObject_CallFunctionObjArgs(r6, r7, 0)\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, r18 :: 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 = PyObject_CallFunctionObjArgs(r16, r17, 0)\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, r4 :: object\n    r5 :: str\nL0:\n    r0 = m :: module\n    r1 = 'f'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = object 1\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\n    r5 = cast(str, r4)\n    return r5\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 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: __main__.B\n    r5 :: __main__.A\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 = B()\n    return r4\nL2:\n    r5 = A()\n    return r5\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 :: object\n    r4 :: list\n    r5, r6 :: object\n    r7 :: tuple\n    r8 :: dict\n    r9 :: object\n    r10 :: 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 = PyList_New(0)\n    r5 = box(tuple[int, int, int], r0)\n    r6 = CPyList_Extend(r4, r5)\n    r7 = PyList_AsTuple(r4)\n    r8 = PyDict_New()\n    r9 = PyObject_Call(r3, r7, r8)\n    r10 = unbox(tuple[int, int, int], r9)\n    return r10\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 :: dict\n    r11 :: object\n    r12 :: 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 = PyDict_New()\n    r11 = PyObject_Call(r3, r9, r10)\n    r12 = unbox(tuple[int, int, int], r11)\n    return r12\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 :: dict\n    r11 :: i32\n    r12 :: bit\n    r13 :: tuple\n    r14 :: object\n    r15 :: 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 = PyDict_New()\n    r11 = CPyDict_UpdateInDisplay(r10, r6)\n    r12 = r11 >= 0 :: signed\n    r13 = PyTuple_Pack(0)\n    r14 = PyObject_Call(r9, r13, r10)\n    r15 = unbox(tuple[int, int, int], r14)\n    return r15\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 :: short_int\n    r7 :: native_int\n    r8 :: short_int\n    r9 :: bit\n    r10 :: object\n    r11, x :: int\n    r12, r13 :: bit\n    r14 :: int\n    r15 :: object\n    r16 :: i32\n    r17 :: bit\n    r18 :: short_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 = r7 << 1\n    r9 = int_lt r6, r8\n    if r9 goto L2 else goto L8 :: bool\nL2:\n    r10 = list_get_item_unsafe r1, r6\n    r11 = unbox(int, r10)\n    x = r11\n    r12 = int_ne x, 4\n    if r12 goto L4 else goto L3 :: bool\nL3:\n    goto L7\nL4:\n    r13 = int_ne x, 6\n    if r13 goto L6 else goto L5 :: bool\nL5:\n    goto L7\nL6:\n    r14 = CPyTagged_Multiply(x, x)\n    r15 = box(int, r14)\n    r16 = PyList_Append(r0, r15)\n    r17 = r16 >= 0 :: signed\nL7:\n    r18 = r6 + 2\n    r6 = r18\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 :: short_int\n    r7 :: native_int\n    r8 :: short_int\n    r9 :: bit\n    r10 :: object\n    r11, x :: int\n    r12, r13 :: bit\n    r14 :: int\n    r15, r16 :: object\n    r17 :: i32\n    r18 :: bit\n    r19 :: short_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 = r7 << 1\n    r9 = int_lt r6, r8\n    if r9 goto L2 else goto L8 :: bool\nL2:\n    r10 = list_get_item_unsafe r1, r6\n    r11 = unbox(int, r10)\n    x = r11\n    r12 = int_ne x, 4\n    if r12 goto L4 else goto L3 :: bool\nL3:\n    goto L7\nL4:\n    r13 = int_ne x, 6\n    if r13 goto L6 else goto L5 :: bool\nL5:\n    goto L7\nL6:\n    r14 = CPyTagged_Multiply(x, x)\n    r15 = box(int, x)\n    r16 = box(int, r14)\n    r17 = CPyDict_SetItem(r0, r15, r16)\n    r18 = r17 >= 0 :: signed\nL7:\n    r19 = r6 + 2\n    r6 = r19\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 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: bit\n    r4 :: object\n    r5 :: tuple[int, int, int]\n    r6, x, r7, y, r8, z :: int\n    r9 :: short_int\n    r10 :: native_int\n    r11 :: list\n    r12 :: short_int\n    r13 :: native_int\n    r14 :: short_int\n    r15 :: bit\n    r16 :: object\n    r17 :: tuple[int, int, int]\n    r18, x_2, r19, y_2, r20, z_2, r21, r22 :: int\n    r23 :: object\n    r24 :: bit\n    r25 :: short_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size l\n    r2 = r1 << 1\n    r3 = int_lt r0, r2\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = list_get_item_unsafe l, r0\n    r5 = unbox(tuple[int, int, int], r4)\n    r6 = r5[0]\n    x = r6\n    r7 = r5[1]\n    y = r7\n    r8 = r5[2]\n    z = r8\nL3:\n    r9 = r0 + 2\n    r0 = r9\n    goto L1\nL4:\n    r10 = var_object_size l\n    r11 = PyList_New(r10)\n    r12 = 0\nL5:\n    r13 = var_object_size l\n    r14 = r13 << 1\n    r15 = int_lt r12, r14\n    if r15 goto L6 else goto L8 :: bool\nL6:\n    r16 = list_get_item_unsafe l, r12\n    r17 = unbox(tuple[int, int, int], r16)\n    r18 = r17[0]\n    x_2 = r18\n    r19 = r17[1]\n    y_2 = r19\n    r20 = r17[2]\n    z_2 = r20\n    r21 = CPyTagged_Add(x_2, y_2)\n    r22 = CPyTagged_Add(r21, z_2)\n    r23 = box(int, r22)\n    r24 = CPyList_SetItemUnsafe(r11, r12, r23)\nL7:\n    r25 = r12 + 2\n    r12 = r25\n    goto L5\nL8:\n    return r11\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, r23 :: object\n    r24 :: dict\n    r25 :: str\n    r26 :: i32\n    r27 :: bit\n    r28 :: str\n    r29 :: dict\n    r30 :: str\n    r31, r32, r33 :: object\n    r34 :: tuple\n    r35 :: dict\n    r36 :: str\n    r37 :: i32\n    r38 :: bit\n    r39 :: dict\n    r40 :: str\n    r41, r42, r43 :: object\n    r44 :: dict\n    r45 :: str\n    r46 :: i32\n    r47 :: bit\n    r48 :: str\n    r49 :: dict\n    r50 :: str\n    r51 :: object\n    r52 :: dict\n    r53 :: str\n    r54, r55 :: object\n    r56 :: dict\n    r57 :: str\n    r58 :: i32\n    r59 :: bit\n    r60 :: list\n    r61, r62, r63 :: object\n    r64 :: ptr\n    r65 :: dict\n    r66 :: str\n    r67 :: i32\n    r68 :: 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 = PyObject_CallFunctionObjArgs(r22, r9, r19, 0)\n    r24 = __main__.globals :: static\n    r25 = 'Lol'\n    r26 = CPyDict_SetItem(r24, r25, r23)\n    r27 = r26 >= 0 :: signed\n    r28 = ''\n    r29 = __main__.globals :: static\n    r30 = 'Lol'\n    r31 = CPyDict_GetItem(r29, r30)\n    r32 = object 1\n    r33 = PyObject_CallFunctionObjArgs(r31, r32, r28, 0)\n    r34 = cast(tuple, r33)\n    r35 = __main__.globals :: static\n    r36 = 'x'\n    r37 = CPyDict_SetItem(r35, r36, r34)\n    r38 = r37 >= 0 :: signed\n    r39 = __main__.globals :: static\n    r40 = 'List'\n    r41 = CPyDict_GetItem(r39, r40)\n    r42 = load_address PyLong_Type\n    r43 = PyObject_GetItem(r41, r42)\n    r44 = __main__.globals :: static\n    r45 = 'Foo'\n    r46 = CPyDict_SetItem(r44, r45, r43)\n    r47 = r46 >= 0 :: signed\n    r48 = 'Bar'\n    r49 = __main__.globals :: static\n    r50 = 'Foo'\n    r51 = CPyDict_GetItem(r49, r50)\n    r52 = __main__.globals :: static\n    r53 = 'NewType'\n    r54 = CPyDict_GetItem(r52, r53)\n    r55 = PyObject_CallFunctionObjArgs(r54, r48, r51, 0)\n    r56 = __main__.globals :: static\n    r57 = 'Bar'\n    r58 = CPyDict_SetItem(r56, r57, r55)\n    r59 = r58 >= 0 :: signed\n    r60 = PyList_New(3)\n    r61 = object 1\n    r62 = object 2\n    r63 = object 3\n    r64 = list_items r60\n    buf_init_item r64, 0, r61\n    buf_init_item r64, 1, r62\n    buf_init_item r64, 2, r63\n    keep_alive r60\n    r65 = __main__.globals :: static\n    r66 = 'y'\n    r67 = CPyDict_SetItem(r65, r66, r60)\n    r68 = r67 >= 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 :: i32\n    r4 :: bit\n    r5 :: bool\n    r6 :: object\nL0:\n    r0 = __mypyc_self__.__eq__(rhs)\n    r1 = load_address _Py_NotImplementedStruct\n    r2 = r0 == r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = PyObject_Not(r0)\n    r4 = r3 >= 0 :: signed\n    r5 = truncate r3: i32 to builtins.bool\n    r6 = box(bool, r5)\n    return r6\nL2:\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, r5, r6, r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11, r12 :: 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 = PyObject_CallFunctionObjArgs(r4, r1, 0)\n    r6 = r0.f\n    r7 = PyObject_CallFunctionObjArgs(r6, 0)\n    r8 = 'Exited'\n    r9 = builtins :: module\n    r10 = 'print'\n    r11 = CPyObject_GetAttr(r9, r10)\n    r12 = PyObject_CallFunctionObjArgs(r11, r8, 0)\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, r5, r6, r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11, r12 :: 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 = PyObject_CallFunctionObjArgs(r4, r1, 0)\n    r6 = r0.f\n    r7 = PyObject_CallFunctionObjArgs(r6, 0)\n    r8 = '---'\n    r9 = builtins :: module\n    r10 = 'print'\n    r11 = CPyObject_GetAttr(r9, r10)\n    r12 = PyObject_CallFunctionObjArgs(r11, r8, 0)\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, r5 :: 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 = PyObject_CallFunctionObjArgs(r4, r1, 0)\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, r6 :: object\n    r7 :: dict\n    r8 :: str\n    r9, r10, d :: object\n    r11 :: dict\n    r12 :: str\n    r13 :: i32\n    r14 :: bit\n    r15 :: str\n    r16 :: object\n    r17 :: str\n    r18, r19, r20 :: 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 = PyObject_CallFunctionObjArgs(r5, r1, 0)\n    r7 = __main__.globals :: static\n    r8 = 'a'\n    r9 = CPyDict_GetItem(r7, r8)\n    r10 = PyObject_CallFunctionObjArgs(r9, r6, 0)\n    d = r10\n    r11 = __main__.globals :: static\n    r12 = 'd'\n    r13 = CPyDict_SetItem(r11, r12, r10)\n    r14 = r13 >= 0 :: signed\n    r15 = 'c'\n    r16 = builtins :: module\n    r17 = 'print'\n    r18 = CPyObject_GetAttr(r16, r17)\n    r19 = PyObject_CallFunctionObjArgs(r18, r15, 0)\n    r20 = PyObject_CallFunctionObjArgs(d, 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, r15 :: object\n    r16 :: dict\n    r17 :: str\n    r18, r19 :: object\n    r20 :: dict\n    r21 :: str\n    r22 :: i32\n    r23 :: 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 = PyObject_CallFunctionObjArgs(r14, r11, 0)\n    r16 = __main__.globals :: static\n    r17 = 'a'\n    r18 = CPyDict_GetItem(r16, r17)\n    r19 = PyObject_CallFunctionObjArgs(r18, r15, 0)\n    r20 = __main__.globals :: static\n    r21 = 'c'\n    r22 = CPyDict_SetItem(r20, r21, r19)\n    r23 = r22 >= 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, r5, r6, r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11, r12 :: 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 = PyObject_CallFunctionObjArgs(r4, r1, 0)\n    r6 = r0.f\n    r7 = PyObject_CallFunctionObjArgs(r6, 0)\n    r8 = 'Exited'\n    r9 = builtins :: module\n    r10 = 'print'\n    r11 = CPyObject_GetAttr(r9, r10)\n    r12 = PyObject_CallFunctionObjArgs(r11, r8, 0)\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, r5 :: object\n    r6, r7 :: bool\n    r8, r9 :: int\n    r10 :: 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 = PyObject_CallFunctionObjArgs(comparison, r4, 0)\n    r6 = unbox(bool, r5)\n    r7 = r6 << 1\n    r8 = extend r7: builtins.bool to builtins.int\n    r9 = CPyTagged_Add(r0, r8)\n    r0 = r9\nL3:\n    goto L1\nL4:\n    r10 = 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, r4 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'reveal_type'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = box(int, x)\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\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, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\nL0:\n    r0 = load_address PyBool_Type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    return r3\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, r4 :: object\n    r5, r :: range\n    sum :: int\n    r6, r7 :: object\n    r8, i, r9 :: int\n    r10 :: bit\nL0:\n    r0 = load_address PyRange_Type\n    r1 = object 4\n    r2 = object 12\n    r3 = object 2\n    r4 = PyObject_CallFunctionObjArgs(r0, r1, r2, r3, 0)\n    r5 = cast(range, r4)\n    r = r5\n    sum = 0\n    r6 = PyObject_GetIter(r)\nL1:\n    r7 = PyIter_Next(r6)\n    if is_error(r7) goto L4 else goto L2\nL2:\n    r8 = unbox(int, r7)\n    i = r8\n    r9 = CPyTagged_Add(sum, i)\n    sum = r9\nL3:\n    goto L1\nL4:\n    r10 = 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\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"
  },
  {
    "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"
  },
  {
    "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, r5 :: object\n    r6, b2, r7, b3, r8, b4, r9, b5 :: bytes\nL0:\n    r0 = load_address PyBytes_Type\n    r1 = PyObject_CallFunctionObjArgs(r0, 0)\n    r2 = cast(bytes, r1)\n    b1 = r2\n    r3 = load_address PyBytes_Type\n    r4 = box(int, num)\n    r5 = PyObject_CallFunctionObjArgs(r3, r4, 0)\n    r6 = cast(bytes, r5)\n    b2 = r6\n    r7 = PyBytes_FromObject(l)\n    b3 = r7\n    r8 = PyBytes_FromObject(d)\n    b4 = r8\n    r9 = PyBytes_FromObject(s)\n    b5 = r9\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 :: object\n    r1 :: str\n    r2, r3, a :: object\n    r4 :: bytes\n    b, r5 :: object\n    r6 :: bytes\n    c :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'bytearray'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_CallFunctionObjArgs(r2, 0)\n    a = r3\n    r4 = PyByteArray_FromObject(s)\n    b = r4\n    r5 = box(int, num)\n    r6 = PyByteArray_FromObject(r5)\n    c = r6\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]\ndef f(a: bytes, i: int) -> int:\n    return a[i]\n[out]\ndef f(a, i):\n    a :: bytes\n    i, r0 :: int\nL0:\n    r0 = CPyBytes_GetItem(a, i)\n    return r0\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[typing fixtures/typing-full.pyi]\n[out]\ndef f(var, num):\n    var :: bytes\n    num :: int\n    r0, r1, r2, b1, r3 :: bytes\n    r4 :: tuple[bytes, bytes, int]\n    r5, r6 :: object\n    r7, b2, r8, b3, r9, r10, b4 :: bytes\nL0:\n    r0 = b'aaaa'\n    r1 = b'bbbb'\n    r2 = CPyBytes_Build(4, r0, var, r1, var)\n    b1 = r2\n    r3 = b'aaaa%bbbbb%s%d'\n    r4 = (var, var, num)\n    r5 = box(tuple[bytes, bytes, int], r4)\n    r6 = PyNumber_Remainder(r3, r5)\n    r7 = cast(bytes, r6)\n    b2 = r7\n    r8 = CPyBytes_Build(1, var)\n    b3 = r8\n    r9 = b'sss'\n    r10 = CPyBytes_Build(2, var, r9)\n    b4 = r10\n    return 1\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_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, r17 :: object\n    r18 :: dict\n    r19 :: str\n    r20 :: i32\n    r21 :: bit\n    r22 :: object\n    r23 :: str\n    r24, r25 :: object\n    r26 :: bool\n    r27 :: str\n    r28 :: tuple\n    r29 :: i32\n    r30 :: bit\n    r31 :: dict\n    r32 :: str\n    r33 :: i32\n    r34 :: bit\n    r35 :: object\n    r36 :: str\n    r37, r38 :: object\n    r39 :: str\n    r40 :: tuple\n    r41 :: i32\n    r42 :: bit\n    r43 :: dict\n    r44 :: str\n    r45 :: i32\n    r46 :: bit\n    r47, r48 :: object\n    r49 :: dict\n    r50 :: str\n    r51 :: object\n    r52 :: dict\n    r53 :: str\n    r54, r55 :: object\n    r56 :: tuple\n    r57 :: str\n    r58, r59 :: object\n    r60 :: bool\n    r61, r62 :: str\n    r63 :: tuple\n    r64 :: i32\n    r65 :: bit\n    r66 :: dict\n    r67 :: str\n    r68 :: i32\n    r69 :: 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 = ('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 = PyObject_CallFunctionObjArgs(r16, r13, 0)\n    r18 = __main__.globals :: static\n    r19 = 'T'\n    r20 = CPyDict_SetItem(r18, r19, r17)\n    r21 = r20 >= 0 :: signed\n    r22 = <error> :: object\n    r23 = '__main__'\n    r24 = __main__.C_template :: type\n    r25 = CPyType_FromTemplate(r24, r22, r23)\n    r26 = C_trait_vtable_setup()\n    r27 = '__mypyc_attrs__'\n    r28 = PyTuple_Pack(0)\n    r29 = PyObject_SetAttr(r25, r27, r28)\n    r30 = r29 >= 0 :: signed\n    __main__.C = r25 :: type\n    r31 = __main__.globals :: static\n    r32 = 'C'\n    r33 = CPyDict_SetItem(r31, r32, r25)\n    r34 = r33 >= 0 :: signed\n    r35 = <error> :: object\n    r36 = '__main__'\n    r37 = __main__.S_template :: type\n    r38 = CPyType_FromTemplate(r37, r35, r36)\n    r39 = '__mypyc_attrs__'\n    r40 = PyTuple_Pack(0)\n    r41 = PyObject_SetAttr(r38, r39, r40)\n    r42 = r41 >= 0 :: signed\n    __main__.S = r38 :: type\n    r43 = __main__.globals :: static\n    r44 = 'S'\n    r45 = CPyDict_SetItem(r43, r44, r38)\n    r46 = r45 >= 0 :: signed\n    r47 = __main__.C :: type\n    r48 = __main__.S :: type\n    r49 = __main__.globals :: static\n    r50 = 'Generic'\n    r51 = CPyDict_GetItem(r49, r50)\n    r52 = __main__.globals :: static\n    r53 = 'T'\n    r54 = CPyDict_GetItem(r52, r53)\n    r55 = PyObject_GetItem(r51, r54)\n    r56 = PyTuple_Pack(3, r47, r48, r55)\n    r57 = '__main__'\n    r58 = __main__.D_template :: type\n    r59 = CPyType_FromTemplate(r58, r56, r57)\n    r60 = D_trait_vtable_setup()\n    r61 = '__mypyc_attrs__'\n    r62 = '__dict__'\n    r63 = PyTuple_Pack(1, r62)\n    r64 = PyObject_SetAttr(r59, r61, r63)\n    r65 = r64 >= 0 :: signed\n    __main__.D = r59 :: type\n    r66 = __main__.globals :: static\n    r67 = 'D'\n    r68 = CPyDict_SetItem(r66, r67, r59)\n    r69 = r68 >= 0 :: signed\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 = 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 = 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 = 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 = 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 = 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 = 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 = 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]\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, r2 :: object\n    r3 :: int\nL0:\n    r0 = 'g'\n    r1 = box(int, x)\n    r2 = CPyObject_CallMethodObjArgs(cls, r0, r1, 0)\n    r3 = unbox(int, r2)\n    return r3\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, r4 :: object\n    r5 :: str\n    r6, r7 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.DictSubclass :: type\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, self, 0)\n    r5 = '__init__'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = PyObject_CallFunctionObjArgs(r6, 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 :: i32\n    r4 :: bit\n    r5 :: bool\n    r6 :: object\nL0:\n    r0 = __mypyc_self__.__eq__(rhs)\n    r1 = load_address _Py_NotImplementedStruct\n    r2 = r0 == r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = PyObject_Not(r0)\n    r4 = r3 >= 0 :: signed\n    r5 = truncate r3: i32 to builtins.bool\n    r6 = box(bool, r5)\n    return r6\nL2:\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]\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\n    r2 :: bool\nL0:\n    r0 = '__ne__'\n    r1 = CPyObject_CallMethodObjArgs(a, r0, b, 0)\n    r2 = unbox(bool, r1)\n    return r2\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 :: i32\n    r4 :: bit\n    r5 :: bool\n    r6 :: object\nL0:\n    r0 = __mypyc_self__.__eq__(rhs)\n    r1 = load_address _Py_NotImplementedStruct\n    r2 = r0 == r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = PyObject_Not(r0)\n    r4 = r3 >= 0 :: signed\n    r5 = truncate r3: i32 to builtins.bool\n    r6 = box(bool, r5)\n    return r6\nL2:\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"
  },
  {
    "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 testIntConstantFoldingFinal]\nfrom typing_extensions 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_extensions 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_extensions 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_extensions 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_extensions 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_extensions 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 :: short_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, k :: str\n    r9, r10, r11 :: object\n    r12 :: i32\n    r13, r14, r15 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = r1 << 1\n    r3 = CPyDict_GetKeysIter(d)\nL1:\n    r4 = CPyDict_NextKey(r3, r0)\n    r5 = r4[1]\n    r0 = 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    k = r8\n    r9 = CPyDict_GetItem(d, k)\n    r10 = object 1\n    r11 = PyNumber_InPlaceAdd(r9, r10)\n    r12 = CPyDict_SetItem(d, k, r11)\n    r13 = r12 >= 0 :: signed\nL3:\n    r14 = CPyDict_CheckSize(d, r2)\n    goto L1\nL4:\n    r15 = 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, Union\nfrom typing_extensions import TypedDict\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[out]\ndef print_dict_methods(d1, d2):\n    d1, d2 :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, v :: int\n    r9 :: object\n    r10 :: i32\n    r11 :: bit\n    r12 :: bool\n    r13, r14 :: bit\n    r15 :: short_int\n    r16 :: native_int\n    r17 :: short_int\n    r18 :: object\n    r19 :: tuple[bool, short_int, object, object]\n    r20 :: short_int\n    r21 :: bool\n    r22, r23 :: object\n    r24, r25, k :: int\n    r26, r27, r28, r29, r30 :: object\n    r31 :: i32\n    r32, r33, r34 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d1)\n    r2 = r1 << 1\n    r3 = CPyDict_GetValuesIter(d1)\nL1:\n    r4 = CPyDict_NextValue(r3, r0)\n    r5 = r4[1]\n    r0 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L6 :: bool\nL2:\n    r7 = r4[2]\n    r8 = unbox(int, r7)\n    v = r8\n    r9 = box(int, v)\n    r10 = PyDict_Contains(d2, r9)\n    r11 = r10 >= 0 :: signed\n    r12 = truncate r10: i32 to builtins.bool\n    if r12 goto L3 else goto L4 :: bool\nL3:\n    return 1\nL4:\nL5:\n    r13 = CPyDict_CheckSize(d1, r2)\n    goto L1\nL6:\n    r14 = CPy_NoErrOccurred()\nL7:\n    r15 = 0\n    r16 = PyDict_Size(d2)\n    r17 = r16 << 1\n    r18 = CPyDict_GetItemsIter(d2)\nL8:\n    r19 = CPyDict_NextItem(r18, r15)\n    r20 = r19[1]\n    r15 = r20\n    r21 = r19[0]\n    if r21 goto L9 else goto L11 :: bool\nL9:\n    r22 = r19[2]\n    r23 = r19[3]\n    r24 = unbox(int, r22)\n    r25 = unbox(int, r23)\n    k = r24\n    v = r25\n    r26 = box(int, k)\n    r27 = CPyDict_GetItem(d2, r26)\n    r28 = box(int, v)\n    r29 = PyNumber_InPlaceAdd(r27, r28)\n    r30 = box(int, k)\n    r31 = CPyDict_SetItem(d2, r30, r29)\n    r32 = r31 >= 0 :: signed\nL10:\n    r33 = CPyDict_CheckSize(d2, r17)\n    goto L8\nL11:\n    r34 = 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 :: short_int\n    r4 :: object\n    r5 :: tuple[bool, short_int, object, object]\n    r6 :: short_int\n    r7 :: bool\n    r8, r9 :: object\n    r10 :: str\n    r11 :: union[int, str]\n    k :: str\n    v :: union[int, str]\n    r12, r13 :: object\n    r14 :: int\n    r15 :: object\n    r16 :: i32\n    r17, r18, r19 :: bit\nL0:\n    r0 = PyDict_New()\n    new = r0\n    r1 = 0\n    r2 = PyDict_Size(d)\n    r3 = r2 << 1\n    r4 = CPyDict_GetItemsIter(d)\nL1:\n    r5 = CPyDict_NextItem(r4, r1)\n    r6 = r5[1]\n    r1 = r6\n    r7 = r5[0]\n    if r7 goto L2 else goto L4 :: bool\nL2:\n    r8 = r5[2]\n    r9 = r5[3]\n    r10 = cast(str, r8)\n    r11 = cast(union[int, str], r9)\n    k = r10\n    v = r11\n    r12 = load_address PyLong_Type\n    r13 = PyObject_CallFunctionObjArgs(r12, v, 0)\n    r14 = unbox(int, r13)\n    r15 = box(int, r14)\n    r16 = CPyDict_SetItem(new, k, r15)\n    r17 = r16 >= 0 :: signed\nL3:\n    r18 = CPyDict_CheckSize(d, r3)\n    goto L1\nL4:\n    r19 = CPy_NoErrOccurred()\nL5:\n    return 1\ndef typeddict(d):\n    d :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: short_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, k :: str\n    v :: object\n    r10 :: str\n    r11 :: i32\n    r12 :: bit\n    r13 :: object\n    r14, r15, r16 :: bit\n    name :: object\n    r17, r18 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = r1 << 1\n    r3 = CPyDict_GetItemsIter(d)\nL1:\n    r4 = CPyDict_NextItem(r3, r0)\n    r5 = r4[1]\n    r0 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L9 :: bool\nL2:\n    r7 = r4[2]\n    r8 = r4[3]\n    r9 = cast(str, r7)\n    k = r9\n    v = r8\n    r10 = 'name'\n    r11 = PyUnicode_Compare(k, r10)\n    r12 = r11 == -1\n    if r12 goto L3 else goto L5 :: bool\nL3:\n    r13 = PyErr_Occurred()\n    r14 = r13 != 0\n    if r14 goto L4 else goto L5 :: bool\nL4:\n    r15 = CPy_KeepPropagating()\nL5:\n    r16 = r11 == 0\n    if r16 goto L6 else goto L7 :: bool\nL6:\n    name = v\nL7:\nL8:\n    r17 = CPyDict_CheckSize(d, r2)\n    goto L1\nL9:\n    r18 = CPy_NoErrOccurred()\nL10:\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_extensions 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-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, TypeVar\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 :: dict\n    r0 :: list\n    r1 :: object\n    r2 :: dict\n    r3 :: i32\n    r4 :: bit\n    r5 :: tuple\n    r6 :: object\n    r7 :: int\nL0:\n    r0 = PyList_New(0)\n    r1 = CPyList_Extend(r0, args)\n    r2 = PyDict_New()\n    r3 = CPyDict_UpdateInDisplay(r2, kwargs)\n    r4 = r3 >= 0 :: signed\n    r5 = PyList_AsTuple(r0)\n    r6 = PyObject_Call(func, r5, r2)\n    r7 = unbox(int, r6)\n    return r7\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, r4 :: object\n    r5 :: int\n    r6 :: __main__.DerivedProperty\nL0:\n    r0 = self._incr_func\n    r1 = self.value\n    r2 = self._incr_func\n    r3 = box(int, r1)\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\n    r5 = unbox(int, r4)\n    r6 = DerivedProperty(r0, r5)\n    return r6\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, r4 :: object\n    r5 :: int\n    r6, r7, r8 :: object\n    r9 :: int\n    r10 :: __main__.AgainProperty\nL0:\n    r0 = self._incr_func\n    r1 = self.value\n    r2 = self._incr_func\n    r3 = box(int, r1)\n    r4 = PyObject_CallFunctionObjArgs(r2, r3, 0)\n    r5 = unbox(int, r4)\n    r6 = self._incr_func\n    r7 = box(int, r5)\n    r8 = PyObject_CallFunctionObjArgs(r6, r7, 0)\n    r9 = unbox(int, r8)\n    r10 = AgainProperty(r0, r9)\n    return r10\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"
  },
  {
    "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\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\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_extensions 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 :: 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\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_extensions 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"
  },
  {
    "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, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\nL0:\n    r0 = load_address PyLong_Type\n    r1 = PyObject_IsInstance(value, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    return r3\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, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3, r4 :: bool\nL0:\n    r0 = load_address PyBool_Type\n    r1 = PyObject_IsInstance(value, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    r4 = r3 ^ 1\n    return r4\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, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3, r4 :: bool\n    r5 :: object\n    r6 :: i32\n    r7 :: bit\n    r8, r9 :: bool\nL0:\n    r0 = load_address PyLong_Type\n    r1 = PyObject_IsInstance(value, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L2 else goto L1 :: bool\nL1:\n    r4 = r3\n    goto L3\nL2:\n    r5 = load_address PyBool_Type\n    r6 = PyObject_IsInstance(value, r5)\n    r7 = r6 >= 0 :: signed\n    r8 = truncate r6: i32 to builtins.bool\n    r9 = r8 ^ 1\n    r4 = r9\nL3:\n    return r4\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 = 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"
  },
  {
    "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 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 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 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 :: short_int\n    r3 :: native_int\n    r4 :: short_int\n    r5 :: bit\n    r6 :: object\n    r7, x, r8 :: int\n    r9 :: object\n    r10 :: bit\n    r11 :: short_int\n    a :: list\n    r12 :: native_int\n    r13 :: list\n    r14 :: short_int\n    r15 :: native_int\n    r16 :: short_int\n    r17 :: bit\n    r18 :: object\n    r19, x_2, r20 :: int\n    r21 :: object\n    r22 :: bit\n    r23 :: short_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 = r3 << 1\n    r5 = int_lt r2, r4\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = list_get_item_unsafe source, r2\n    r7 = unbox(int, r6)\n    x = r7\n    r8 = CPyTagged_Add(x, 2)\n    r9 = box(int, r8)\n    r10 = CPyList_SetItemUnsafe(r1, r2, r9)\nL3:\n    r11 = r2 + 2\n    r2 = r11\n    goto L1\nL4:\n    a = r1\n    r12 = var_object_size source\n    r13 = PyList_New(r12)\n    r14 = 0\nL5:\n    r15 = var_object_size source\n    r16 = r15 << 1\n    r17 = int_lt r14, r16\n    if r17 goto L6 else goto L8 :: bool\nL6:\n    r18 = list_get_item_unsafe source, r14\n    r19 = unbox(int, r18)\n    x_2 = r19\n    r20 = CPyTagged_Add(x_2, 2)\n    r21 = box(int, r20)\n    r22 = CPyList_SetItemUnsafe(r13, r14, r21)\nL7:\n    r23 = r14 + 2\n    r14 = r23\n    goto L5\nL8:\n    b = r13\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 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: bit\n    r4 :: object\n    r5, i :: int\n    r6 :: object\n    r7 :: union[int, None]\n    r8 :: short_int\n    r9 :: object\n    res :: union[int, None]\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size x\n    r2 = r1 << 1\n    r3 = int_lt r0, r2\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = list_get_item_unsafe x, r0\n    r5 = unbox(int, r4)\n    i = r5\n    r6 = box(int, i)\n    r7 = r6\n    goto L5\nL3:\n    r8 = r0 + 2\n    r0 = r8\n    goto L1\nL4:\n    r9 = box(None, 1)\n    r7 = r9\nL5:\n    res = r7\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 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: list\n    r5 :: native_int\n    r6 :: short_int\n    r7 :: int\nL0:\n    r0 = load_address PyList_Type\n    r1 = PyObject_IsInstance(a, 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 = borrow cast(list, a)\n    r5 = var_object_size r4\n    r6 = r5 << 1\n    keep_alive a\n    return r6\nL2:\n    r7 = unbox(int, a)\n    return r7\ndef loop(a):\n    a :: list\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: bit\n    r4 :: object\n    r5, x :: union[str, bytes]\n    r6 :: short_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size a\n    r2 = r1 << 1\n    r3 = int_lt r0, r2\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = list_get_item_unsafe a, r0\n    r5 = cast(union[str, bytes], r4)\n    x = r5\nL3:\n    r6 = r0 + 2\n    r0 = r6\n    goto L1\nL4:\n    return 1\ndef nested_union(a):\n    a :: list\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: bit\n    r4 :: object\n    r5, x :: union[str, None]\n    r6 :: short_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size a\n    r2 = r1 << 1\n    r3 = int_lt r0, r2\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = list_get_item_unsafe a, r0\n    r5 = cast(union[str, None], r4)\n    x = r5\nL3:\n    r6 = r0 + 2\n    r0 = r6\n    goto L1\nL4:\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    i :: int\n    r3 :: object\n    r4 :: str\n    r5, 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    i = 246\nL2:\n    r3 = builtins :: module\n    r4 = 'print'\n    r5 = CPyObject_GetAttr(r3, r4)\n    r6 = box(int, i)\n    r7 = [r6]\n    r8 = load_address r7\n    r9 = _PyObject_Vectorcall(r5, r8, 1, 0)\n    keep_alive r6\n    goto L4\nL3:\nL4:\n    r10 = box(None, 1)\n    return r10\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):\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, 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 = '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    r32 = box(None, 1)\n    return r32\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):\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, r26 :: 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    r26 = box(None, 1)\n    return r26\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 :: object\n    r6, num :: int\n    r7 :: str\n    r8 :: object\n    r9 :: str\n    r10 :: object\n    r11 :: object[1]\n    r12 :: object_ptr\n    r13, r14 :: 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    r6 = unbox(int, r5)\n    num = r6\nL2:\n    r7 = 'matched'\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 L4\nL3:\nL4:\n    r14 = box(None, 1)\n    return r14\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    r2, y :: int\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 = CPy_TypeCheck(x, r0)\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = unbox(int, x)\n    y = 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 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"
  },
  {
    "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\n    r5, a, r6 :: str\n    r7 :: object\n    r8, 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 = PyObject_CallFunctionObjArgs(inner, r3, 0)\n    r5 = cast(str, r4)\n    a = r5\n    r6 = 'two'\n    r7 = PyObject_CallFunctionObjArgs(inner, r6, 0)\n    r8 = cast(str, r7)\n    b = r8\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_CallFunctionObjArgs(inner, 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_CallFunctionObjArgs(inner, 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_CallFunctionObjArgs(inner, 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_CallFunctionObjArgs(c, 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_CallFunctionObjArgs(b, 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_CallFunctionObjArgs(inner, 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_CallFunctionObjArgs(r1, 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, r5 :: object\n    r6, r7 :: 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 = PyObject_CallFunctionObjArgs(r3, r4, 0)\n    r6 = unbox(int, r5)\n    r7 = CPyTagged_Add(n, r6)\n    return r7\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, r17 :: object\n    r18, r19 :: 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_CallFunctionObjArgs(r11, 0)\n    r13 = unbox(int, r12)\n    r14 = r0.a\n    r15 = r0.baz\n    r16 = box(int, r14)\n    r17 = PyObject_CallFunctionObjArgs(r15, r16, 0)\n    r18 = unbox(int, r17)\n    r19 = CPyTagged_Add(r13, r18)\n    return r19\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, r2 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.s\n    r2 = PyObject_CallFunctionObjArgs(r1, a, b, 0)\n    return r2\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, r8 :: object\n    r9 :: 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 = PyObject_CallFunctionObjArgs(t, r6, r7, 0)\n    r9 = unbox(None, r8)\n    return r9\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 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4, r5 :: int\n    r6 :: __main__.A\n    r7 :: int\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(int, x)\n    r5 = CPyTagged_Add(r4, 2)\n    return r5\nL2:\n    r6 = borrow cast(__main__.A, x)\n    r7 = r6.a\n    keep_alive x\n    return r7\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 = 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 = 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 = 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 = 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 = 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-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 :: short_int\n    r7 :: native_int\n    r8 :: short_int\n    r9 :: bit\n    r10 :: object\n    r11, x, r12 :: int\n    r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: short_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 = r7 << 1\n    r9 = int_lt r6, r8\n    if r9 goto L2 else goto L4 :: bool\nL2:\n    r10 = list_get_item_unsafe tmp_list, r6\n    r11 = unbox(int, r10)\n    x = r11\n    r12 = f(x)\n    r13 = box(int, r12)\n    r14 = PySet_Add(r5, r13)\n    r15 = r14 >= 0 :: signed\nL3:\n    r16 = r6 + 2\n    r6 = r16\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 :: short_int\n    r11 :: object\n    r12 :: tuple[bool, short_int, object]\n    r13 :: short_int\n    r14 :: bool\n    r15 :: object\n    r16, x, r17 :: int\n    r18 :: object\n    r19 :: i32\n    r20, r21, r22 :: 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 = r9 << 1\n    r11 = CPyDict_GetKeysIter(tmp_dict)\nL1:\n    r12 = CPyDict_NextKey(r11, r8)\n    r13 = r12[1]\n    r8 = r13\n    r14 = r12[0]\n    if r14 goto L2 else goto L4 :: bool\nL2:\n    r15 = r12[2]\n    r16 = unbox(int, r15)\n    x = r16\n    r17 = f(x)\n    r18 = box(int, r17)\n    r19 = PySet_Add(r7, r18)\n    r20 = r19 >= 0 :: signed\nL3:\n    r21 = CPyDict_CheckSize(tmp_dict, r10)\n    goto L1\nL4:\n    r22 = 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 :: short_int\n    r11 :: native_int\n    r12 :: short_int\n    r13 :: bit\n    r14 :: object\n    r15, z :: int\n    r16 :: bit\n    r17 :: int\n    r18 :: object\n    r19 :: i32\n    r20 :: bit\n    r21 :: short_int\n    r22, r23, r24 :: object\n    r25, y, r26 :: int\n    r27 :: object\n    r28 :: i32\n    r29, r30 :: bit\n    r31, r32, r33 :: object\n    r34, x, r35 :: int\n    r36 :: object\n    r37 :: i32\n    r38, r39 :: 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 = r11 << 1\n    r13 = int_lt r10, r12\n    if r13 goto L2 else goto L6 :: bool\nL2:\n    r14 = list_get_item_unsafe tmp_list, r10\n    r15 = unbox(int, r14)\n    z = r15\n    r16 = int_lt z, 8\n    if r16 goto L4 else goto L3 :: bool\nL3:\n    goto L5\nL4:\n    r17 = f1(z)\n    r18 = box(int, r17)\n    r19 = PyList_Append(r9, r18)\n    r20 = r19 >= 0 :: signed\nL5:\n    r21 = r10 + 2\n    r10 = r21\n    goto L1\nL6:\n    r22 = PyObject_GetIter(r9)\n    r23 = PyObject_GetIter(r22)\nL7:\n    r24 = PyIter_Next(r23)\n    if is_error(r24) goto L10 else goto L8\nL8:\n    r25 = unbox(int, r24)\n    y = r25\n    r26 = f2(y)\n    r27 = box(int, r26)\n    r28 = PyList_Append(r8, r27)\n    r29 = r28 >= 0 :: signed\nL9:\n    goto L7\nL10:\n    r30 = CPy_NoErrOccurred()\nL11:\n    r31 = PyObject_GetIter(r8)\n    r32 = PyObject_GetIter(r31)\nL12:\n    r33 = PyIter_Next(r32)\n    if is_error(r33) goto L15 else goto L13\nL13:\n    r34 = unbox(int, r33)\n    x = r34\n    r35 = f3(x)\n    r36 = box(int, r35)\n    r37 = PySet_Add(r7, r36)\n    r38 = r37 >= 0 :: signed\nL14:\n    goto L12\nL15:\n    r39 = 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_extensions 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 :: object\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_extensions 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\n    r12 :: i32\n    r13 :: bit\n    r14 :: object\n    r15 :: ptr\n    r16 :: object\n    r17 :: bit\n    r18 :: int\n    r19 :: bit\n    r20 :: int\n    r21 :: bool\n    r22 :: object\n    r23 :: bool\nL0:\n    r0 = get_element_ptr arg ob_type :: PyObject\n    r1 = 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 = PyObject_CallFunctionObjArgs(r9, r1, r10, 0)\n    r12 = CPyDict_SetItem(r2, r1, r11)\n    r13 = r12 >= 0 :: signed\n    r6 = r11\nL3:\n    r14 = load_address PyLong_Type\n    r15 = get_element_ptr r6 ob_type :: PyObject\n    r16 = load_mem r15 :: builtins.object*\n    keep_alive r6\n    r17 = r16 == r14\n    if r17 goto L4 else goto L7 :: bool\nL4:\n    r18 = unbox(int, r6)\n    r19 = int_eq r18, 0\n    if r19 goto L5 else goto L6 :: bool\nL5:\n    r20 = unbox(int, arg)\n    r21 = g(r20)\n    return r21\nL6:\n    unreachable\nL7:\n    r22 = PyObject_CallFunctionObjArgs(r6, arg, 0)\n    r23 = unbox(bool, r22)\n    return r23\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\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\n    r12 :: i32\n    r13 :: bit\n    r14 :: object\n    r15 :: ptr\n    r16 :: object\n    r17 :: bit\n    r18 :: int\n    r19 :: object\n    r20 :: None\nL0:\n    r0 = get_element_ptr x ob_type :: PyObject\n    r1 = 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 = PyObject_CallFunctionObjArgs(r9, r1, r10, 0)\n    r12 = CPyDict_SetItem(r2, r1, r11)\n    r13 = r12 >= 0 :: signed\n    r6 = r11\nL3:\n    r14 = load_address PyLong_Type\n    r15 = get_element_ptr r6 ob_type :: PyObject\n    r16 = load_mem r15 :: builtins.object*\n    keep_alive r6\n    r17 = r16 == r14\n    if r17 goto L4 else goto L5 :: bool\nL4:\n    r18 = unbox(int, r6)\n    unreachable\nL5:\n    r19 = PyObject_CallFunctionObjArgs(r6, x, 0)\n    r20 = unbox(None, r19)\n    return r20\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"
  },
  {
    "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 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: bit\n    r4 :: object\n    r5, x, r6 :: int\n    r7 :: short_int\nL0:\n    y = 0\n    r0 = 0\nL1:\n    r1 = var_object_size ls\n    r2 = r1 << 1\n    r3 = int_lt r0, r2\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = list_get_item_unsafe ls, r0\n    r5 = unbox(int, r4)\n    x = r5\n    r6 = CPyTagged_Add(y, x)\n    y = r6\nL3:\n    r7 = r0 + 2\n    r0 = r7\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 :: short_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, key :: int\n    r9, r10 :: object\n    r11 :: int\n    r12, r13 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = r1 << 1\n    r3 = CPyDict_GetKeysIter(d)\nL1:\n    r4 = CPyDict_NextKey(r3, r0)\n    r5 = r4[1]\n    r0 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L4 :: bool\nL2:\n    r7 = r4[2]\n    r8 = unbox(int, r7)\n    key = r8\n    r9 = box(int, key)\n    r10 = CPyDict_GetItem(d, r9)\n    r11 = unbox(int, r10)\nL3:\n    r12 = CPyDict_CheckSize(d, r2)\n    goto L1\nL4:\n    r13 = 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 :: short_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, key :: int\n    r9, r10 :: object\n    r11, r12 :: int\n    r13 :: bit\n    r14, r15 :: object\n    r16, r17 :: int\n    r18, r19 :: bit\nL0:\n    s = 0\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = r1 << 1\n    r3 = CPyDict_GetKeysIter(d)\nL1:\n    r4 = CPyDict_NextKey(r3, r0)\n    r5 = r4[1]\n    r0 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L6 :: bool\nL2:\n    r7 = r4[2]\n    r8 = unbox(int, r7)\n    key = r8\n    r9 = box(int, key)\n    r10 = CPyDict_GetItem(d, r9)\n    r11 = unbox(int, r10)\n    r12 = CPyTagged_Remainder(r11, 4)\n    r13 = r12 != 0\n    if r13 goto L3 else goto L4 :: bool\nL3:\n    goto L5\nL4:\n    r14 = box(int, key)\n    r15 = CPyDict_GetItem(d, r14)\n    r16 = unbox(int, r15)\n    r17 = CPyTagged_Add(s, r16)\n    s = r17\nL5:\n    r18 = CPyDict_CheckSize(d, r2)\n    goto L1\nL6:\n    r19 = 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, r1 :: int\n    r2, x, r3, r4 :: object\n    r5, y :: int\nL0:\n    r0 = borrow t[0]\n    r1 = unborrow r0\n    r2 = box(int, r1)\n    x = r2\n    r3 = borrow t[1]\n    r4 = unborrow r3\n    r5 = unbox(int, r4)\n    y = r5\n    keep_alive steal t\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, 2\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_GetItem(t, 0)\n    r8 = CPySequenceTuple_GetItem(t, 2)\n    r9 = unbox(int, r8)\n    x = r7\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, r7 :: 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 = PyObject_CallFunctionObjArgs(r6, s, 0)\n    CPy_Raise(r7)\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, r1 :: short_int\n    r2 :: native_int\n    r3 :: short_int\n    r4 :: bit\n    i :: int\n    r5 :: object\n    r6, x, r7 :: int\n    r8, r9 :: short_int\nL0:\n    r0 = 0\n    r1 = 0\nL1:\n    r2 = var_object_size a\n    r3 = r2 << 1\n    r4 = int_lt r1, r3\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    i = r0\n    r5 = list_get_item_unsafe a, r1\n    r6 = unbox(int, r5)\n    x = r6\n    r7 = CPyTagged_Add(i, x)\nL3:\n    r8 = r0 + 2\n    r0 = r8\n    r9 = r1 + 2\n    r1 = r9\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 :: short_int\n    r1 :: object\n    r2 :: native_int\n    r3 :: short_int\n    r4 :: bit\n    r5, r6 :: object\n    r7, x :: int\n    r8, y :: bool\n    r9 :: i32\n    r10 :: bit\n    r11 :: bool\n    r12 :: short_int\n    r13 :: bit\nL0:\n    r0 = 0\n    r1 = PyObject_GetIter(b)\nL1:\n    r2 = var_object_size a\n    r3 = r2 << 1\n    r4 = int_lt r0, r3\n    if r4 goto L2 else goto L7 :: bool\nL2:\n    r5 = PyIter_Next(r1)\n    if is_error(r5) goto L7 else goto L3\nL3:\n    r6 = list_get_item_unsafe a, r0\n    r7 = unbox(int, r6)\n    x = r7\n    r8 = unbox(bool, r5)\n    y = r8\n    r9 = PyObject_IsTrue(b)\n    r10 = r9 >= 0 :: signed\n    r11 = truncate r9: i32 to builtins.bool\n    if r11 goto L4 else goto L5 :: bool\nL4:\n    x = 2\nL5:\nL6:\n    r12 = r0 + 2\n    r0 = r12\n    goto L1\nL7:\n    r13 = CPy_NoErrOccurred()\nL8:\n    return 1\ndef g(a, b):\n    a :: object\n    b :: list\n    r0 :: object\n    r1, r2 :: short_int\n    z :: int\n    r3 :: object\n    r4 :: native_int\n    r5 :: short_int\n    r6, r7 :: bit\n    r8, x :: bool\n    r9 :: object\n    r10, y :: int\n    r11, r12 :: short_int\n    r13 :: 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 = r4 << 1\n    r6 = int_lt r1, r5\n    if r6 goto L3 else goto L6 :: bool\nL3:\n    r7 = int_lt r2, 10\n    if r7 goto L4 else goto L6 :: bool\nL4:\n    r8 = unbox(bool, r3)\n    x = r8\n    r9 = list_get_item_unsafe b, r1\n    r10 = unbox(int, r9)\n    y = r10\n    x = 0\nL5:\n    r11 = r1 + 2\n    r1 = r11\n    r12 = r2 + 2\n    r2 = r12\n    z = r12\n    goto L1\nL6:\n    r13 = 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 Optional, List\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[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]\ndef eq(x: str, y: str) -> bool:\n    return x == y\n\ndef neq(x: str, y: str) -> bool:\n    return x != y\n\n[out]\ndef eq(x, y):\n    x, y :: str\n    r0 :: i32\n    r1 :: bit\n    r2 :: object\n    r3, r4, r5 :: bit\nL0:\n    r0 = PyUnicode_Compare(x, y)\n    r1 = r0 == -1\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = PyErr_Occurred()\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPy_KeepPropagating()\nL3:\n    r5 = r0 == 0\n    return r5\ndef neq(x, y):\n    x, y :: str\n    r0 :: i32\n    r1 :: bit\n    r2 :: object\n    r3, r4, r5 :: bit\nL0:\n    r0 = PyUnicode_Compare(x, y)\n    r1 = r0 == -1\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = PyErr_Occurred()\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPy_KeepPropagating()\nL3:\n    r5 = r0 != 0\n    return r5\n\n[case testStrReplace]\nfrom typing import Optional\n\ndef do_replace(s: str, 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[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 testStrToBool]\ndef is_true(x: str) -> bool:\n    if x:\n        return True\n    else:\n        return False\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]\ndef f(s: str, 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[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]\ndef f(var: str, 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[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\n    r13 :: str\n    r14 :: list\n    r15 :: ptr\n    r16, s2, r17, s3, r18, 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 = CPyObject_CallMethodObjArgs(r7, r11, var, r10, 0)\n    r13 = cast(str, r12)\n    r14 = PyList_New(2)\n    r15 = list_items r14\n    buf_init_item r15, 0, r6\n    buf_init_item r15, 1, r13\n    keep_alive r14\n    r16 = PyUnicode_Join(r5, r14)\n    s2 = r16\n    r17 = ''\n    s3 = r17\n    r18 = 'abc'\n    s4 = r18\n    return 1\n\n[case testStringFormattingCStyle]\ndef f(var: str, 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', 'backslashreplace')\n[out]\ndef f(b):\n    b :: bytes\n    r0, r1, r2, r3, r4, r5 :: str\nL0:\n    r0 = CPy_Decode(b, 0, 0)\n    r1 = 'utf-8'\n    r2 = CPy_Decode(b, r1, 0)\n    r3 = 'utf-8'\n    r4 = 'backslashreplace'\n    r5 = CPy_Decode(b, r3, r4)\n    return 1\n\n[case testEncode]\ndef f(s: str) -> 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[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\n    r20 :: str\n    r21 :: tuple\n    r22 :: dict\n    r23 :: object\n    r24 :: str\n    r25 :: object\n    r26 :: str\n    r27 :: tuple\n    r28 :: dict\n    r29 :: object\n    r30 :: str\n    r31 :: object\n    r32, r33 :: str\n    r34 :: tuple\n    r35 :: dict\n    r36 :: object\n    r37 :: str\n    r38 :: 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 = CPyObject_GetAttr(s, r18)\n    r20 = 'errors'\n    r21 = PyTuple_Pack(1, r17)\n    r22 = CPyDict_Build(1, r20, errors)\n    r23 = PyObject_Call(r19, r21, r22)\n    r24 = 'encode'\n    r25 = CPyObject_GetAttr(s, r24)\n    r26 = 'errors'\n    r27 = PyTuple_Pack(0)\n    r28 = CPyDict_Build(1, r26, errors)\n    r29 = PyObject_Call(r25, r27, r28)\n    r30 = 'encode'\n    r31 = CPyObject_GetAttr(s, r30)\n    r32 = 'encoding'\n    r33 = 'errors'\n    r34 = PyTuple_Pack(0)\n    r35 = CPyDict_Build(2, r32, encoding, r33, errors)\n    r36 = PyObject_Call(r31, r34, r35)\n    r37 = 'latin2'\n    r38 = CPy_Encode(s, r37, 0)\n    return 1\n\n[case testOrd]\ndef str_ord(x: str) -> 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[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, r3 :: object\n    r4 :: int\nL0:\n    r0 = builtins :: module\n    r1 = 'ord'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_CallFunctionObjArgs(r2, x, 0)\n    r4 = unbox(int, r3)\n    return r4\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-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, r9 :: object\n    r10 :: bit\nL0:\nL1:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_CallFunctionObjArgs(r2, 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 = PyObject_CallFunctionObjArgs(r8, r5, 0)\nL3:\n    CPy_RestoreExcInfo(r4)\n    goto L5\nL4: (handler for L2)\n    CPy_RestoreExcInfo(r4)\n    r10 = 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, r11 :: object\n    r12 :: 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_CallFunctionObjArgs(r2, 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 = PyObject_CallFunctionObjArgs(r10, r7, 0)\nL6:\n    CPy_RestoreExcInfo(r6)\n    goto L8\nL7: (handler for L5)\n    CPy_RestoreExcInfo(r6)\n    r12 = 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, r4, r5 :: object\n    r6 :: str\n    r7, r8 :: object\n    r9 :: tuple[object, object, object]\n    r10 :: object\n    r11 :: str\n    r12 :: object\n    r13 :: bit\n    r14, e :: object\n    r15 :: str\n    r16 :: object\n    r17 :: str\n    r18, r19 :: object\n    r20 :: bit\n    r21 :: tuple[object, object, object]\n    r22 :: str\n    r23 :: object\n    r24 :: str\n    r25, r26 :: object\n    r27 :: bit\nL0:\nL1:\n    r0 = 'a'\n    r1 = builtins :: module\n    r2 = 'print'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = PyObject_CallFunctionObjArgs(r3, r0, 0)\nL2:\n    r5 = builtins :: module\n    r6 = 'object'\n    r7 = CPyObject_GetAttr(r5, r6)\n    r8 = PyObject_CallFunctionObjArgs(r7, 0)\n    goto L8\nL3: (handler for L2)\n    r9 = CPy_CatchError()\n    r10 = builtins :: module\n    r11 = 'AttributeError'\n    r12 = CPyObject_GetAttr(r10, r11)\n    r13 = CPy_ExceptionMatches(r12)\n    if r13 goto L4 else goto L5 :: bool\nL4:\n    r14 = CPy_GetExcValue()\n    e = r14\n    r15 = 'b'\n    r16 = builtins :: module\n    r17 = 'print'\n    r18 = CPyObject_GetAttr(r16, r17)\n    r19 = PyObject_CallFunctionObjArgs(r18, r15, e, 0)\n    goto L6\nL5:\n    CPy_Reraise()\n    unreachable\nL6:\n    CPy_RestoreExcInfo(r9)\n    goto L8\nL7: (handler for L3, L4, L5)\n    CPy_RestoreExcInfo(r9)\n    r20 = CPy_KeepPropagating()\n    unreachable\nL8:\n    goto L12\nL9: (handler for L1, L6, L7, L8)\n    r21 = CPy_CatchError()\n    r22 = 'weeee'\n    r23 = builtins :: module\n    r24 = 'print'\n    r25 = CPyObject_GetAttr(r23, r24)\n    r26 = PyObject_CallFunctionObjArgs(r25, r22, 0)\nL10:\n    CPy_RestoreExcInfo(r21)\n    goto L12\nL11: (handler for L9)\n    CPy_RestoreExcInfo(r21)\n    r27 = 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, r9, r10 :: object\n    r11 :: str\n    r12 :: object\n    r13 :: bit\n    r14 :: str\n    r15 :: object\n    r16 :: str\n    r17, r18 :: object\n    r19 :: 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 = PyObject_CallFunctionObjArgs(r8, r5, 0)\n    goto L7\nL4:\n    r10 = builtins :: module\n    r11 = 'IndexError'\n    r12 = CPyObject_GetAttr(r10, r11)\n    r13 = CPy_ExceptionMatches(r12)\n    if r13 goto L5 else goto L6 :: bool\nL5:\n    r14 = 'yo'\n    r15 = builtins :: module\n    r16 = 'print'\n    r17 = CPyObject_GetAttr(r15, r16)\n    r18 = PyObject_CallFunctionObjArgs(r17, r14, 0)\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    r19 = 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, r4 :: object\n    r5, r6, r7 :: tuple[object, object, object]\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11, r12 :: object\n    r13 :: 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 = PyObject_CallFunctionObjArgs(r3, r0, 0)\n    CPy_Raise(r4)\n    unreachable\nL3:\nL4:\nL5:\n    r5 = <error> :: tuple[object, object, object]\n    r6 = r5\n    goto L7\nL6: (handler for L1, L2, L3)\n    r7 = CPy_CatchError()\n    r6 = r7\nL7:\n    r8 = 'finally'\n    r9 = builtins :: module\n    r10 = 'print'\n    r11 = CPyObject_GetAttr(r9, r10)\n    r12 = PyObject_CallFunctionObjArgs(r11, r8, 0)\n    if is_error(r6) goto L9 else goto L8\nL8:\n    CPy_Reraise()\n    unreachable\nL9:\n    goto L13\nL10: (handler for L7, L8)\n    if is_error(r6) goto L12 else goto L11\nL11:\n    CPy_RestoreExcInfo(r6)\nL12:\n    r13 = 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, r6 :: object\n    r7 :: bool\n    y :: object\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11, r12 :: object\n    r13, r14 :: tuple[object, object, object]\n    r15, r16, r17, r18 :: object\n    r19 :: i32\n    r20 :: bit\n    r21 :: bool\n    r22 :: bit\n    r23, r24, r25 :: tuple[object, object, object]\n    r26, r27 :: object\n    r28 :: bit\nL0:\n    r0 = PyObject_CallFunctionObjArgs(x, 0)\n    r1 = PyObject_Type(r0)\n    r2 = '__exit__'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = '__enter__'\n    r5 = CPyObject_GetAttr(r1, r4)\n    r6 = PyObject_CallFunctionObjArgs(r5, r0, 0)\n    r7 = 1\nL1:\nL2:\n    y = r6\n    r8 = 'hello'\n    r9 = builtins :: module\n    r10 = 'print'\n    r11 = CPyObject_GetAttr(r9, r10)\n    r12 = PyObject_CallFunctionObjArgs(r11, r8, 0)\n    goto L8\nL3: (handler for L2)\n    r13 = CPy_CatchError()\n    r7 = 0\n    r14 = CPy_GetExcInfo()\n    r15 = r14[0]\n    r16 = r14[1]\n    r17 = r14[2]\n    r18 = PyObject_CallFunctionObjArgs(r3, r0, r15, r16, r17, 0)\n    r19 = PyObject_IsTrue(r18)\n    r20 = r19 >= 0 :: signed\n    r21 = truncate r19: i32 to builtins.bool\n    if r21 goto L5 else goto L4 :: bool\nL4:\n    CPy_Reraise()\n    unreachable\nL5:\nL6:\n    CPy_RestoreExcInfo(r13)\n    goto L8\nL7: (handler for L3, L4, L5)\n    CPy_RestoreExcInfo(r13)\n    r22 = CPy_KeepPropagating()\n    unreachable\nL8:\nL9:\nL10:\n    r23 = <error> :: tuple[object, object, object]\n    r24 = r23\n    goto L12\nL11: (handler for L1, L6, L7, L8)\n    r25 = CPy_CatchError()\n    r24 = r25\nL12:\n    if r7 goto L13 else goto L14 :: bool\nL13:\n    r26 = load_address _Py_NoneStruct\n    r27 = PyObject_CallFunctionObjArgs(r3, r0, r26, r26, r26, 0)\nL14:\n    if is_error(r24) 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(r24) goto L19 else goto L18\nL18:\n    CPy_RestoreExcInfo(r24)\nL19:\n    r28 = 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, r6 :: object\n    r7, r8 :: tuple[object, object, object]\n    r9, r10, r11 :: object\n    r12 :: None\n    r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: bool\n    r17 :: bit\n    r18, r19, r20 :: tuple[object, object, object]\n    r21 :: object\n    r22 :: None\n    r23 :: 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 = PyObject_CallFunctionObjArgs(r5, r2, 0)\n    goto L8\nL3: (handler for L2)\n    r7 = CPy_CatchError()\n    r1 = 0\n    r8 = CPy_GetExcInfo()\n    r9 = r8[0]\n    r10 = r8[1]\n    r11 = r8[2]\n    r12 = x.__exit__(r9, r10, r11)\n    r13 = box(None, r12)\n    r14 = PyObject_IsTrue(r13)\n    r15 = r14 >= 0 :: signed\n    r16 = truncate r14: i32 to builtins.bool\n    if r16 goto L5 else goto L4 :: bool\nL4:\n    CPy_Reraise()\n    unreachable\nL5:\nL6:\n    CPy_RestoreExcInfo(r7)\n    goto L8\nL7: (handler for L3, L4, L5)\n    CPy_RestoreExcInfo(r7)\n    r17 = CPy_KeepPropagating()\n    unreachable\nL8:\nL9:\nL10:\n    r18 = <error> :: tuple[object, object, object]\n    r19 = r18\n    goto L12\nL11: (handler for L1, L6, L7, L8)\n    r20 = CPy_CatchError()\n    r19 = r20\nL12:\n    if r1 goto L13 else goto L14 :: bool\nL13:\n    r21 = load_address _Py_NoneStruct\n    r22 = x.__exit__(r21, r21, r21)\nL14:\n    if is_error(r19) 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(r19) goto L19 else goto L18\nL18:\n    CPy_RestoreExcInfo(r19)\nL19:\n    r23 = 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, cast\ndef f(t: Tuple[int, ...]) -> int:\n    return t[1]\n[out]\ndef f(t):\n    t :: tuple\n    r0 :: object\n    r1 :: int\nL0:\n    r0 = CPySequenceTuple_GetItem(t, 2)\n    r1 = unbox(int, r0)\n    return r1\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 :: short_int\n    r1 :: native_int\n    r2 :: short_int\n    r3 :: bit\n    r4 :: object\n    r5, x :: str\n    r6 :: short_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size xs\n    r2 = r1 << 1\n    r3 = int_lt r0, r2\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPySequenceTuple_GetItem(xs, r0)\n    r5 = cast(str, r4)\n    x = r5\nL3:\n    r6 = r0 + 2\n    r0 = r6\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 :: bit\n    r1 :: bool\n    r2 :: bit\n    r3 :: bool\n    r4 :: bit\nL0:\n    r0 = int_eq i, 2\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = r0\n    goto L3\nL2:\n    r2 = int_eq i, 4\n    r1 = r2\nL3:\n    if r1 goto L4 else goto L5 :: bool\nL4:\n    r3 = r1\n    goto L6\nL5:\n    r4 = int_eq i, 6\n    r3 = r4\nL6:\n    return r3\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 :: short_int\n    r8 :: native_int\n    r9 :: short_int\n    r10 :: bit\n    r11 :: object\n    r12, x :: int\n    r13 :: bool\n    r14 :: object\n    r15 :: bit\n    r16 :: short_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 = r8 << 1\n    r10 = int_lt r7, r9\n    if r10 goto L2 else goto L4 :: bool\nL2:\n    r11 = list_get_item_unsafe source, r7\n    r12 = unbox(int, r11)\n    x = r12\n    r13 = f(x)\n    r14 = box(bool, r13)\n    r15 = CPySequenceTuple_SetItemUnsafe(r6, r7, r14)\nL3:\n    r16 = r7 + 2\n    r7 = r16\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 :: short_int\n    r5 :: native_int\n    r6 :: bit\n    r7 :: short_int\n    r8 :: bit\n    r9, x, r10 :: str\n    r11 :: bit\n    r12 :: short_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 = CPyStr_Size_size_t(source)\n    r6 = r5 >= 0 :: signed\n    r7 = r5 << 1\n    r8 = int_lt r4, r7\n    if r8 goto L2 else goto L4 :: bool\nL2:\n    r9 = CPyStr_GetItem(source, r4)\n    x = r9\n    r10 = f2(x)\n    r11 = CPySequenceTuple_SetItemUnsafe(r3, r4, r10)\nL3:\n    r12 = r4 + 2\n    r4 = r12\n    goto L1\nL4:\n    a = r3\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 :: short_int\n    r3 :: native_int\n    r4 :: short_int\n    r5 :: bit\n    r6 :: object\n    r7, x, r8 :: bool\n    r9 :: object\n    r10 :: bit\n    r11 :: short_int\n    a :: tuple\nL0:\n    r0 = var_object_size source\n    r1 = PyTuple_New(r0)\n    r2 = 0\nL1:\n    r3 = var_object_size source\n    r4 = r3 << 1\n    r5 = int_lt r2, r4\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = CPySequenceTuple_GetItem(source, r2)\n    r7 = unbox(bool, r6)\n    x = r7\n    r8 = f(x)\n    r9 = box(bool, r8)\n    r10 = CPySequenceTuple_SetItemUnsafe(r1, r2, r9)\nL3:\n    r11 = r2 + 2\n    r2 = r11\n    goto L1\nL4:\n    a = r1\n    return 1\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 :: i32\n    r6 :: bit\n    r7 :: object\n    r8, r9, r10 :: bit\n    r11, r12 :: bool\n    r13 :: object\n    r14 :: str\n    r15 :: object\n    r16 :: tuple[int, int]\n    r17, r18 :: object\n    r19, 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 = PyUnicode_Compare(r3, r4)\n    r6 = r5 == -1\n    if r6 goto L1 else goto L3 :: bool\nL1:\n    r7 = PyErr_Occurred()\n    r8 = r7 != 0\n    if r8 goto L2 else goto L3 :: bool\nL2:\n    r9 = CPy_KeepPropagating()\nL3:\n    r10 = r5 == 0\n    if r10 goto L5 else goto L4 :: bool\nL4:\n    r11 = r10\n    goto L6\nL5:\n    r12 = raise RuntimeError('mypyc internal error: should be unreachable')\n    r13 = box(None, 1)\n    r14 = 'version_info'\n    r15 = CPyObject_GetAttr(r13, r14)\n    r16 = (6, 10)\n    r17 = box(tuple[int, int], r16)\n    r18 = PyObject_RichCompare(r15, r17, 4)\n    r19 = unbox(bool, r18)\n    r11 = r19\nL6:\n    y = r11\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 :: i32\n    r6 :: bit\n    r7 :: object\n    r8, r9, r10 :: bit\n    r11, r12 :: bool\n    r13 :: object\n    r14, 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 = PyUnicode_Compare(r3, r4)\n    r6 = r5 == -1\n    if r6 goto L1 else goto L3 :: bool\nL1:\n    r7 = PyErr_Occurred()\n    r8 = r7 != 0\n    if r8 goto L2 else goto L3 :: bool\nL2:\n    r9 = CPy_KeepPropagating()\nL3:\n    r10 = r5 == 0\n    if r10 goto L5 else goto L4 :: bool\nL4:\n    r11 = r10\n    goto L6\nL5:\n    r12 = raise RuntimeError('mypyc internal error: should be unreachable')\n    r13 = box(None, 1)\n    r14 = unbox(bool, r13)\n    r11 = r14\nL6:\n    y = r11\n    return 1\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_CallFunctionObjArgs(r2, 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, r5 :: 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 = PyObject_CallFunctionObjArgs(r4, r1, 0)\nL4:\n    return 4\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_python3_8]\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_python3_8]\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_python3_8]\nfrom typing import Any\n\ndef f(o: Any) -> None:\n    # On Python 3.8 vectorcalls are only faster with keyword args\n    o.m('x')\n    o.m('x', a='y')\n[out]\ndef f(o):\n    o :: object\n    r0, r1 :: str\n    r2 :: object\n    r3, r4, r5 :: str\n    r6 :: object\n    r7 :: object[2]\n    r8 :: object_ptr\n    r9, r10 :: object\nL0:\n    r0 = 'x'\n    r1 = 'm'\n    r2 = CPyObject_CallMethodObjArgs(o, r1, r0, 0)\n    r3 = 'x'\n    r4 = 'y'\n    r5 = 'm'\n    r6 = CPyObject_GetAttr(o, r5)\n    r7 = [r3, r4]\n    r8 = load_address r7\n    r9 = ('a',)\n    r10 = _PyObject_Vectorcall(r6, r8, 1, r9)\n    keep_alive r3, r4\n    return 1\n\n[case testVectorcallMethod_python3_9_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_python3_9_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/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 :: short_int\n    r1 :: ptr\n    r2 :: native_int\n    r3 :: short_int\n    r4 :: bit\n    r5 :: native_int\n    r6, r7 :: ptr\n    r8 :: native_int\n    r9 :: ptr\n    r10 :: object\n    r11, x :: int\n    r12 :: short_int\n    r13 :: None\nL0:\n    r0 = 0\nL1:\n    r1 = get_element_ptr l ob_size :: PyVarObject\n    r2 = load_mem r1 :: native_int*\n    r3 = r2 << 1\n    r4 = r0 < r3 :: signed\n    if r4 goto L2 else goto L5 :: bool\nL2:\n    r5 = r0 >> 1\n    r6 = get_element_ptr l ob_item :: PyListObject\n    r7 = load_mem r6 :: ptr*\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: builtins.object*\n    inc_ref r10\n    r11 = unbox(int, r10)\n    dec_ref r10\n    if is_error(r11) goto L6 (error at f:4) else goto L3\nL3:\n    x = r11\n    dec_ref x :: int\nL4:\n    r12 = r0 + 2\n    r0 = r12\n    goto L1\nL5:\n    return 1\nL6:\n    r13 = <error> :: None\n    return r13\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, x, r3, r4, y :: __main__.C\n    r5, r6, r7 :: int\nL0:\n    r0 = g()\n    r1 = borrow r0[0]\n    r2 = unborrow r1\n    x = r2\n    r3 = borrow r0[1]\n    r4 = unborrow r3\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 :: object\n    r1 :: str\n    r2 :: tuple\n    r3 :: object\n    r4 :: dict\n    r5 :: object\n    r6 :: int\nL0:\n    r0 = load_address PyLong_Type\n    r1 = 'base'\n    r2 = PyTuple_Pack(1, x)\n    r3 = object 2\n    r4 = CPyDict_Build(1, r1, r3)\n    r5 = PyObject_Call(r0, r2, r4)\n    dec_ref r2\n    dec_ref 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 :: short_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, key :: int\n    r9, r10 :: object\n    r11 :: int\n    r12, r13 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = r1 << 1\n    r3 = CPyDict_GetKeysIter(d)\nL1:\n    r4 = CPyDict_NextKey(r3, r0)\n    r5 = r4[1]\n    r0 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L6 :: bool\nL2:\n    r7 = r4[2]\n    dec_ref r4\n    r8 = unbox(int, r7)\n    dec_ref r7\n    key = r8\n    r9 = box(int, key)\n    r10 = CPyDict_GetItem(d, r9)\n    dec_ref r9\n    r11 = unbox(int, r10)\n    dec_ref r10\n    dec_ref r11 :: int\nL3:\n    r12 = CPyDict_CheckSize(d, r2)\n    goto L1\nL4:\n    r13 = CPy_NoErrOccurred()\nL5:\n    return 1\nL6:\n    dec_ref r3\n    dec_ref r4\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 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_python3_8]\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_python3_9_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 = 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_extensions 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"
  },
  {
    "path": "mypyc/test-data/run-async.test",
    "content": "# async test cases (compile and run)\n\n[case testAsync]\nimport asyncio\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()\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[typing fixtures/typing-full.pyi]\n\n[file driver.py]\nfrom native import f\nimport asyncio\n\nresult = asyncio.run(f())\nassert result == 1\n\n[case testAsyncWith]\nfrom testutil import async_val\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\n\n[file driver.py]\nfrom native import async_with\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\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\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 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[typing fixtures/typing-full.pyi]\n[file driver.py]\nimport asyncio\nimport native\nasyncio.run(native.x())\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\nfrom types import FunctionType\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]) -> \"FunctionType[[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\nfrom types import FunctionType\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]) -> \"FunctionType[[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-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, x: Leaf) -> bool:\n        return isinstance(self.left, Leaf)\n    def visit_node(self, x: Node) -> bool:\n        if isinstance(self.left, Node):\n            # our boolean stuff is crap\n            if (self.left.value == x.value and equal(self.left.left, x.left)\n                    and equal(self.left.right, x.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 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 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\n[case testBoolMixInt]\ny = False\nprint((y or 0) and True)\n[out]\n0\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: bytes = bytearray(3)\n    brr2: bytes = 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: bytes = brr2 + b2\n    assert b5 == bytearray(b'\\x00\\x01\\x02\\x03\\x04456')\n    assert type(b5) == bytearray\n    b5 = b2 + brr2\n    assert b5 == b'456\\x00\\x01\\x02\\x03\\x04'\n    assert type(b5) == 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\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\ndef test_basics() -> None:\n    brr1: bytes = 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: bytes = bytearray(l)\n    assert brr2 == bytearray(b'\\n\\x14\\x1e(')\n    assert brr2 == b'\\n\\x14\\x1e('\n    brr3: bytes = bytearray(range(5))\n    assert brr3 == bytearray(b'\\x00\\x01\\x02\\x03\\x04')\n    assert brr3 == b'\\x00\\x01\\x02\\x03\\x04'\n    brr4: bytes = 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 f(b: bytes) -> bool:\n    return True\n\ndef test_bytearray_passed_into_bytes() -> None:\n    assert f(bytearray(3))\n    brr1: Any = bytearray()\n    assert f(brr1)\n\n[case testBytearraySlicing]\ndef test_bytearray_slicing() -> None:\n    b: bytes = 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: bytes = 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    x: bytes = bytearray(b' ')\n    assert x.join([b'a', b'b']) == b'a b'\n    assert type(x.join([b'a', b'b'])) == bytearray\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]\n[typing fixtures/typing-full.pyi]\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\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\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"
  },
  {
    "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\nfrom typing_extensions import TypedDict\nclass C(TypedDict):\n    x: collections.deque\n[file driver.py]\nfrom native import C\nfrom collections import deque\n\nprint(C.__annotations__[\"x\"] is deque)\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 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\nfrom typing_extensions import 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):\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 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 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_extensions 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\nz: Foo = Bar()\nz.f(1, z=50)\nz.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\n# Make an \"interpreted\" subtype of Foo\ntype2: Any = type\nBar = type2('Bar', (Foo,), {})\nBaz = type2('Baz', (Foo,), {'f': baz_f})\n\ny: Foo = Bar()\ny.f(1, z=2)\ny.f()\n\nz: Foo = Baz()\nz.f(1, z=2)\nz.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\nz: Foo = Bar()\nz.f(1)\nz.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\nz: Foo = Bar()\nz.f(1, z=2)\nz.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\nz: Foo = Bar()\nz.f(1, z=2)\nz.f(1, 2, 3)\nz.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\n# Make an \"interpreted\" subtype of Foo\ntype2: Any = type\nBaz = type2('Baz', (Foo,), {'f': baz_f})\n\nz: Foo = Baz()\nz.f()\nz.f(y=1)\nz.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):\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 DerivedInterpreted1(b):\n        def __init__(self):\n            super().__init__('y')\n    d2 = DerivedInterpreted1()\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\nassert Derived()() == 1\n\n[case testClassWithFinalAttribute]\nfrom typing_extensions 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 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"
  },
  {
    "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, Union\nfrom typing_extensions import TypedDict\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[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"
  },
  {
    "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\nassert UsesNotImplemented() != object()\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):\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]\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\ndef test_unannotated_add_and_radd_1() -> None:\n    o = F(4)\n    assert o + 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\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# TODO: Inheritance\n\n[case testDifferentReverseDunders]\nclass C:\n    # __radd__ and __rsub__ are tested elsewhere\n\n    def __rmul__(self, x):\n        return 1\n\n    def __rtruediv__(self, x):\n        return 2\n\n    def __rmod__(self, x):\n        return 3\n\n    def __rfloordiv__(self, x):\n        return 4\n\n    def __rlshift__(self, x):\n        return 5\n\n    def __rrshift__(self, x):\n        return 6\n\n    def __rand__(self, x):\n        return 7\n\n    def __ror__(self, x):\n        return 8\n\n    def __rxor__(self, x):\n        return 9\n\n    def __rmatmul__(self, x):\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):\n        self.x = 0\n\n    def __iadd__(self, x):\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"
  },
  {
    "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 Any, cast\nfrom typing_extensions import Final\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        # https://github.com/mypyc/mypyc/issues/1029\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    # https://github.com/mypyc/mypyc/issues/1029\n    # assert t2 == tuple([5.0, 1.5, -7.0, -113.0])\n\n[case testFloatGlueMethodsAndInheritance]\nfrom typing import Any\nfrom typing_extensions import Final\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"
  },
  {
    "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 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, for_loop, while_loop,\n    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 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, ...]:  # type: ignore[override]\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 g() -> None:\n    a = ['']\n    with f():\n        a.pop()\n\ng()\n\n[case testUnpackKwargsCompiled]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(**kwargs: Unpack[Person]) -> None:\n    print(kwargs[\"name\"])\n\n# This is not really supported yet, just test that we behave reasonably.\nfoo(name='Jennifer', age=38)\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\nif 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\nbar()\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"
  },
  {
    "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\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\n[file driver.py]\nfrom native import normal, generator, triple, another_triple, outer\nfrom testutil import run_generator\n\nassert run_generator(normal(1, 2.0)(3, '4.00')) == ((1, 2.0, 3, '4.00'), None)\nassert run_generator(generator(1)) == ((1, 2, 3), None)\nassert run_generator(triple()()) == ((1, 2, 3), None)\nassert run_generator(another_triple()()) == ((1,), None)\nassert run_generator(outer()) == ((0, 1, 2, 3, 4), None)\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: bool\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\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\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"
  },
  {
    "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(OverflowError, \"int too large to convert to i16\"):\n        o = 2**15\n        x2: i16 = o\n    with assertRaises(OverflowError, \"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(OverflowError):\n        assert i16_3 < int_too_big\n    with assertRaises(OverflowError):\n        assert int_too_big < i16_3\n    with assertRaises(OverflowError):\n        assert i16_3 > int_too_small\n    with assertRaises(OverflowError):\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(OverflowError):\n        assert i16_3 & int_too_big\n    with assertRaises(OverflowError):\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(OverflowError):\n        x = i16(too_big)\n\n    too_small = int() - 2**15 - 1\n    with assertRaises(OverflowError):\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(OverflowError, \"int too large to convert to i16\"):\n        assert from_float(float(2**15))\n    with assertRaises(OverflowError, \"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(OverflowError, \"int too large to convert to i32\"):\n        o = 2**31\n        x2: i32 = o\n    with assertRaises(OverflowError, \"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(OverflowError):\n        assert i32_3 < int_too_big\n    with assertRaises(OverflowError):\n        assert int_too_big < i32_3\n    with assertRaises(OverflowError):\n        assert i32_3 > int_too_small\n    with assertRaises(OverflowError):\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(OverflowError):\n        assert i32_3 & int_too_big\n    with assertRaises(OverflowError):\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(OverflowError):\n        x = i32(too_big)\n\n    too_small = int() - 2**31 - 1\n    with assertRaises(OverflowError):\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(OverflowError, \"int too large to convert to i32\"):\n        assert from_float(float(2**31))\n    with assertRaises(OverflowError, \"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(OverflowError):\n        x = i64(too_big)\n\n    too_small = int() - 2**63 - 1\n    with assertRaises(OverflowError):\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(OverflowError, \"int too large to convert to i64\"):\n        assert from_float(float(2**63))\n    with assertRaises(OverflowError, \"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(OverflowError):\n        assert i64_3 < int_too_big\n    with assertRaises(OverflowError):\n        assert int_too_big < i64_3\n    with assertRaises(OverflowError):\n        assert i64_3 > int_too_small\n    with assertRaises(OverflowError):\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(OverflowError):\n        assert i64_3 & int_too_big\n    with assertRaises(OverflowError):\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, Tuple\nimport sys\n\nfrom mypy_extensions import mypyc_attr, i64\nfrom typing_extensions import Final\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(OverflowError, \"int too large to convert to i64\"):\n        y: i64 = o2\n    o3: Any = -(1 << 63 + 1)\n    with assertRaises(OverflowError, \"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, Iterator, Tuple\nfrom typing_extensions import Final\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_extensions 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 Any\nfrom typing_extensions import Final\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\nassert shared.counter == 0\ndo_import()\nassert shared.counter == 1\n\n[file a.py]\nimport shared\nshared.counter += 1\n\n[file shared.py]\ncounter = 0\n\n[case testDelayedImport]\nimport a\nprint(\"inbetween\")\nimport 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]\ntry:\n    import enum\n    import dataclasses, missing  # type: ignore[import]\nexcept ImportError as e:\n    line = e.__traceback__.tb_lineno # type: ignore[attr-defined]\n    assert line == 3, f\"traceback's line number is {line}, expected 3\"\n\n[case testImportGroupIsolation]\ndef func() -> None:\n    import second\n\nimport first\nfunc()\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"
  },
  {
    "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 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 testListBuild]\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\n[case testListPrims]\nfrom typing import List\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    l.pop(2)\n    assert l == [1, 2, 3]\n    l.pop(-2)\n    assert l == [1, 3]\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]\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\n[case testOperatorInExpression]\n\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\n[file driver.py]\n\nfrom native import *\n\nassert not tuple_in_int0(0)\nassert not tuple_in_int1(0)\nassert tuple_in_int1(1)\nassert not tuple_in_int3(0)\nassert tuple_in_int3(1)\nassert tuple_in_int3(2)\nassert tuple_in_int3(3)\nassert not tuple_in_int3(4)\n\nassert tuple_not_in_int0(0)\nassert tuple_not_in_int1(0)\nassert not tuple_not_in_int1(1)\nassert tuple_not_in_int3(0)\nassert not tuple_not_in_int3(1)\nassert not tuple_not_in_int3(2)\nassert not tuple_not_in_int3(3)\nassert tuple_not_in_int3(4)\n\nassert tuple_in_str(\"foo\")\nassert tuple_in_str(\"bar\")\nassert tuple_in_str(\"baz\")\nassert not tuple_in_str(\"apple\")\nassert not tuple_in_str(\"pie\")\nassert not tuple_in_str(\"\\0\")\nassert not tuple_in_str(\"\")\n\nassert not list_in_int0(0)\nassert not list_in_int1(0)\nassert list_in_int1(1)\nassert not list_in_int3(0)\nassert list_in_int3(1)\nassert list_in_int3(2)\nassert list_in_int3(3)\nassert not list_in_int3(4)\n\nassert list_not_in_int0(0)\nassert list_not_in_int1(0)\nassert not list_not_in_int1(1)\nassert list_not_in_int3(0)\nassert not list_not_in_int3(1)\nassert not list_not_in_int3(2)\nassert not list_not_in_int3(3)\nassert list_not_in_int3(4)\n\nassert list_in_str(\"foo\")\nassert list_in_str(\"bar\")\nassert list_in_str(\"baz\")\nassert not list_in_str(\"apple\")\nassert not list_in_str(\"pie\")\nassert not list_in_str(\"\\0\")\nassert not list_in_str(\"\")\n\nassert list_in_mixed(0)\nassert list_in_mixed([])\nassert list_in_mixed({})\nassert list_in_mixed(())\nassert list_in_mixed(False)\nassert list_in_mixed(0.0)\nassert not list_in_mixed([1])\nassert not list_in_mixed(object)\nassert list_in_mixed(type)\n\n[case testListBuiltFromGenerator]\ndef test() -> 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\"]\n\n[case testNextBug]\nfrom typing import List, Optional\n\ndef test(x: List[int]) -> None:\n    res = next((i for i in x), None)\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"
  },
  {
    "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 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 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, 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))\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\nfrom typing_extensions import 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\nassert f(False) == ((1, None), (None, 1))\nassert f(True) == ((None, 1), (1, None))\nassert next(gen(False)) is None\nassert 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, NamedTuple\nfrom typing_extensions import Literal, TypedDict, NewType\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[out]\nLol(a=1, b=[])\n10\n1\n20\nTypeError\n1\nTypeError\n10\n\n[case testClassBasedTypedDict]\nfrom typing_extensions 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\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]\n[typing fixtures/typing-full.pyi]\nfrom typing import Any, List\n\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]) == 6.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 []) == 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 []) == 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 []), 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\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, 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\nelif sys.version_info[:2] == (3, 8):\n    def version() -> int:\n        return 8\nelif sys.version_info[:2] == (3, 7):\n    def version() -> int:\n        return 7\nelif sys.version_info[:2] == (3, 6):\n    def version() -> int:\n        return 6\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\nA = sys.platform == 'x' and foobar\nB = sys.platform == 'x' and sys.foobar\nC = sys.platform == 'x' and f(a, -b, 'y') > [c + e, g(y=2)]\nC = sys.platform == 'x' and cast(a, b[c])\nC = sys.platform == 'x' and (lambda x: y + x)\nC = sys.platform == 'x' and (x for y in z)\nC = sys.platform == 'x' and [x for y in z]\nC = sys.platform == 'x' and {x: x for y in z}\nC = sys.platform == 'x' and {x for y in z}\n\nassert not A\nassert not B\nassert 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\n[case testGlobalRedefinition_toplevel]\n# mypy: allow-redefinition\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"
  },
  {
    "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_extensions 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_extensions 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_extensions 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_extensions import Final\nX: Final = 10\n\n[file other.py.2]\nfrom typing_extensions 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 native, 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"
  },
  {
    "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, o: nodes.Block) -> str:\n        # we really need comprehensions!\n        # TODO: PartialType unsupported\n        things = []  # type: List[str]\n        for s in o.stmts:\n            things.append(s.accept(self))\n        return \"{\" + \"; \".join(things) + \"}\"\n\n    def visit_func_def(self, o: nodes.FuncDef) -> str:\n        return \"def \" + o.name() + \"(): \" + o.body.accept(self)\n\n    def visit_expr_stmt(self, o: nodes.ExprStmt) -> str:\n        return o.expr.accept(self)\n\n    def visit_lambda_expr(self, o: nodes.LambdaExpr) -> str:\n        return \"(fn: \" + o.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    return o\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 typing import Any, 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[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\nfrom types import FunctionType\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]) -> \"FunctionType[[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\nz: Foo = Bar()\nz.f(1, z=50)\nz.f()\nz.f(1)\nz.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 testPrecomputedFrozenSets]\nfrom typing import Any\nfrom typing_extensions import Final\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"
  },
  {
    "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\n\n@singledispatch\ndef fun(arg) -> 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\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef fun(arg) -> 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\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef fun(arg) -> 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\n\n@singledispatch\ndef fun(arg) -> 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): 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\nclass A: pass\n\n@singledispatch\ndef fun(arg) -> 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\n\n@singledispatch\ndef fun(arg) -> bool:\n    return False\n\n@fun.register(int)\ndef fun_specialized(arg) -> 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\n\n@singledispatch\ndef fun(arg) -> bool:\n    return False\n\ndef fun_specialized_impl(arg) -> 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\n\n@singledispatch\ndef fun(arg) -> bool:\n    return False\n\n@fun.register(int)\ndef fun_specialized(arg) -> 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\n\n@singledispatch\ndef fun(arg) -> bool:\n    return False\n\ntry:\n    @fun.register\n    def fun_specialized(arg: None) -> bool:\n        return True\nexcept TypeError:\n    pass\n\n[case testRegisteringTheSameFunctionSeveralTimes]\nfrom functools import singledispatch\n\n@singledispatch\ndef fun(arg) -> bool:\n    return False\n\n@fun.register(int)\n@fun.register(str)\ndef fun_specialized(arg) -> 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]\nfrom functools import singledispatch\nfrom collections.abc import Mapping\n\n@singledispatch\ndef fun(arg) -> bool:\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\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():\n    tree = build(5)\n    tree2 = build(5)\n    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, a, b) -> 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\n\n@singledispatch\ndef f(a) -> bool:\n    return False\n\n@f.register\ndef g(b: int) -> bool:\n    return True\n\ndef test_singledispatch():\n    assert f(5)\n    assert not f('a')\n\n[case testKeywordArguments]\nfrom functools import singledispatch\n\n@singledispatch\ndef f(arg, *, 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():\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():\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\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) -> int:\n    return 0\n\n@f.register\n@decorator\ndef h(arg: str) -> int:\n    return 2\n\ndef test_singledispatch():\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) -> int:\n        return f(x) * 7\n    return wrapper\n\n@singledispatch\ndef f(arg) -> int:\n    return 10\n\n@f.register\n@decorator\ndef h(arg: str) -> int:\n    return 5\n\n\ndef test_singledispatch():\n    assert f('a') == 35\n    assert f(A()) == 10\n\n[case testMoreSpecificTypeBeforeLessSpecificType]\nfrom functools import singledispatch\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef f(arg) -> 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():\n    assert f(B()) == 'b'\n    assert f(A()) == 'a'\n    assert f(5) == 'default'\n\n[case testMultipleRelatedClassesBeingRegistered]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n@singledispatch\ndef f(arg) -> 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():\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():\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) -> 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\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) -> str:\n    return \"default\"\n    pass\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():\n    assert f(AB()) == \"a\"\n    assert f(BA()) == \"b\"\n\n[case testCallingFunctionBeforeAllImplementationsRegistered]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef f(arg) -> 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\nassert f(A()) == 'a'\nassert f(B()) == 'b'\nassert f(1) == 'default'\n\n\n[case testDynamicallyRegisteringFunctionFromInterpretedCode]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nclass D(C): pass\n\n@singledispatch\ndef f(arg) -> 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\n\n@singledispatch\ndef f(arg) -> 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) -> 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\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 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))\n\n[file driver.py]\nfrom native import f, g, tostr, booltostr, concat, eq, match\nimport sys\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 eq('foo') == 0\nassert eq('zar') == 1\nassert eq('bar') == 2\n\nassert int(tostr(0)) == 0\nassert int(tostr(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)\n\n[case testStringOps]\nfrom typing import List, Optional\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\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 getitem(s: str, index: int) -> str:\n    return s[index]\n\nfrom testutil import assertRaises\n\ns = \"abc\"\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 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\n[case testStringFormattingCStyle]\n[typing fixtures/typing-full.pyi]\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\n[case testFStrings]\nimport decimal\nfrom datetime import datetime\n\nvar = 'mypyc'\nnum = 20\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# 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\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\n[case testDecode]\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'abc'.decode() == 'abc'\n    assert b'abc'.decode('utf-8') == '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('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    try:\n        b'Z\\xc3\\xbcrich'.decode('ascii')\n        assert False\n    except UnicodeDecodeError:\n        pass\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\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"
  },
  {
    "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 = None  # type: 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\nfrom typing_extensions import 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]\nfrom typing import ForwardRef, Optional\nfrom native import ClassIR, FuncIR, Record\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': ForwardRef('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, List, Any, Optional\nfrom typing_extensions import Final\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\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\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\nTUPLE: Final[Tuple[str, ...]] = ('x', 'y')\n\ndef test_final_boxed_tuple() -> None:\n    t = TUPLE\n    assert t == ('x', 'y')\n"
  },
  {
    "path": "mypyc/test-data/run-u8.test",
    "content": "[case testU8BasicOps]\nfrom typing import Any, Tuple\n\nfrom mypy_extensions import u8, i16, i32, i64\nfrom typing_extensions import Final\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(OverflowError, \"int too large or small to convert to u8\"):\n        o = 256\n        x2: u8 = o\n    with assertRaises(OverflowError, \"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(OverflowError):\n        assert u8_3 < int_too_big\n    with assertRaises(OverflowError):\n        assert int_too_big < u8_3\n    with assertRaises(OverflowError):\n        assert u8_3 > int_too_small\n    with assertRaises(OverflowError):\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(OverflowError):\n        assert u8_3 & int_too_big\n    with assertRaises(OverflowError):\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(OverflowError):\n        x = u8(too_big)\n\n    too_small = int() - 1\n    with assertRaises(OverflowError):\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(OverflowError, \"int too large or small to convert to u8\"):\n        assert from_float(float(256))\n    with assertRaises(OverflowError, \"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/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 typing import Optional, cast\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) -> 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 = cast(Optional[BasicBlock], 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(ir.blocks, error_label, ir.traceback_name)\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], default_error_handler: BasicBlock, func_name: str | None\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                    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    )\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        old_branch = self.branch_map.get(op.dest)\n        if old_branch:\n            # Replace assignment with a copy of the old branch, which is in a\n            # separate basic block. The old branch will be deletecd 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, Optional\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    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    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[Optional[Value]]):\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        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_ptr(self, op: GetElementPtr) -> 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_ptr(self, op: GetElementPtr) -> 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)\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/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 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:\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    ControlOp,\n    DecRef,\n    Goto,\n    IncRef,\n    Integer,\n    KeepAlive,\n    LoadAddress,\n    Op,\n    Register,\n    RegisterOp,\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\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):\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)\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/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) -> 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)\n\n\ndef split_blocks_at_uninits(\n    blocks: list[BasicBlock], pre_must_defined: AnalysisDict[Value]\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                    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 src not in init_registers_set:\n                        init_registers.append(src)\n                        init_registers_set.add(src)\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                    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": "pw",
    "content": "#!/usr/bin/env python3\n\n##################################################################################\n# Pyprojectx wrapper script                                                      #\n# https://github.com/pyprojectx/pyprojectx                                       #\n#                                                                                #\n# Copyright (c) 2021 Ivo Houbrechts                                              #\n#                                                                                #\n# Licensed under the MIT license                                                 #\n##################################################################################\nimport argparse\nimport os\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom venv import EnvBuilder\n\nVERSION = \"3.1.5\"\n\nPYPROJECTX_INSTALL_DIR_ENV_VAR = \"PYPROJECTX_INSTALL_DIR\"\nPYPROJECTX_PACKAGE_ENV_VAR = \"PYPROJECTX_PACKAGE\"\nPYPROJECT_TOML = \"pyproject.toml\"\nDEFAULT_INSTALL_DIR = \".pyprojectx\"\n\nCYAN = \"\\033[96m\"\nBLUE = \"\\033[94m\"\nRED = \"\\033[91m\"\nRESET = \"\\033[0m\"\nif sys.platform.startswith(\"win\"):\n    os.system(\"color\")\n\n\ndef run(args):\n    try:\n        options = get_options(args)\n        pyprojectx_script = ensure_pyprojectx(options)\n        explicit_options = []\n        if not options.toml:\n            explicit_options += [\"--toml\", str(options.toml_path)]\n        if not options.install_dir:\n            explicit_options += [\"--install-dir\", str(options.install_path)]\n\n        subprocess.run([str(pyprojectx_script), *explicit_options, *args], check=True)\n    except subprocess.CalledProcessError as e:\n        raise SystemExit(e.returncode) from e\n\n\ndef get_options(args):\n    options = arg_parser().parse_args(args)\n    options.install_path = Path(\n        options.install_dir\n        or os.environ.get(PYPROJECTX_INSTALL_DIR_ENV_VAR, Path(__file__).with_name(DEFAULT_INSTALL_DIR))\n    )\n    options.toml_path = Path(options.toml) if options.toml else Path(__file__).with_name(PYPROJECT_TOML)\n    if os.environ.get(PYPROJECTX_PACKAGE_ENV_VAR):\n        options.version = \"development\"\n        options.pyprojectx_package = os.environ.get(PYPROJECTX_PACKAGE_ENV_VAR)\n    else:\n        options.version = VERSION\n        options.pyprojectx_package = f\"pyprojectx[locked]=={VERSION}\"\n    options.verbosity = 0 if options.quiet or not options.verbosity else options.verbosity\n    return options\n\n\ndef arg_parser():\n    parser = argparse.ArgumentParser(\n        description=\"Execute commands or aliases defined in the [tool.pyprojectx] section of pyproject.toml. \"\n        \"Use the -i or --info option to see available tools and aliases.\",\n        allow_abbrev=False,\n    )\n    parser.add_argument(\"--version\", action=\"version\", version=VERSION)\n    parser.add_argument(\n        \"--toml\",\n        \"-t\",\n        action=\"store\",\n        help=\"The toml config file. Defaults to 'pyproject.toml' in the same directory as the pw script.\",\n    )\n    parser.add_argument(\n        \"--install-dir\",\n        action=\"store\",\n        help=f\"The directory where all tools (including pyprojectx) are installed; defaults to the \"\n        f\"{PYPROJECTX_INSTALL_DIR_ENV_VAR} environment value if set, else '.pyprojectx' \"\n        f\"in the same directory as the invoked pw script.\",\n    )\n    parser.add_argument(\n        \"--force-install\",\n        \"-f\",\n        action=\"store_true\",\n        help=\"Force clean installation of the virtual environment used to run cmd, if any.\",\n    )\n    parser.add_argument(\n        \"--clean\",\n        \"-c\",\n        action=\"store_true\",\n        help=\"Clean .pyprojectx directory by removing all but the current versions \"\n        \"of pyprojectx and context virtual environments.\",\n    )\n    parser.add_argument(\n        \"--install-context\",\n        action=\"store\",\n        metavar=\"tool-context\",\n        help=\"Install a tool context without actually running any command.\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"count\",\n        dest=\"verbosity\",\n        help=\"Give more output. This option is additive and can be used up to 2 times.\",\n    )\n    parser.add_argument(\n        \"--quiet\",\n        \"-q\",\n        action=\"store_true\",\n        help=\"Suppress output.\",\n    )\n    parser.add_argument(\n        \"--info\",\n        \"-i\",\n        action=\"store_true\",\n        help=\"Show the configuration details of a command instead of running it. \"\n        \"If no command is specified, a list with all available tools and aliases is shown.\",\n    )\n    parser.add_argument(\n        \"--add\",\n        action=\"store\",\n        metavar=\"[context:]<package>,<package>...\",\n        help=\"Add one or more packages to a tool context. \"\n        \"If no context is specified, the packages are added to the main context. \"\n        \"Packages can be specified as in 'pip install', except that a ',' can't be used in the version specification.\",\n    )\n    parser.add_argument(\n        \"--lock\",\n        action=\"store_true\",\n        help=\"Write all dependencies of all tool contexts to 'pw.lock' to guarantee reproducible outcomes.\",\n    )\n    parser.add_argument(\n        \"--install-px\", action=\"store_true\", help=\"Install the px and pxg scripts in your home directory.\"\n    )\n    parser.add_argument(\n        \"--upgrade\",\n        action=\"store_true\",\n        help=\"Print instructions to download the latest pyprojectx wrapper scripts.\",\n    )\n    parser.add_argument(\n        \"command\", nargs=argparse.REMAINDER, help=\"The command/alias with optional arguments to execute.\"\n    )\n    return parser\n\n\ndef ensure_pyprojectx(options):\n    env_builder = EnvBuilder(with_pip=True)\n    venv_dir = (\n        options.install_path / \"pyprojectx\" / f\"{options.version}-py{sys.version_info.major}.{sys.version_info.minor}\"\n    )\n    env_context = env_builder.ensure_directories(venv_dir)\n    pyprojectx_script = Path(env_context.bin_path, \"pyprojectx\")\n    pyprojectx_exe = Path(env_context.bin_path, \"pyprojectx.exe\")\n    pip_cmd = [env_context.env_exe, \"-m\", \"pip\", \"install\", \"--pre\"]\n\n    if options.quiet:\n        out = subprocess.DEVNULL\n        pip_cmd.append(\"--quiet\")\n    else:\n        out = sys.stderr\n\n    if not pyprojectx_script.is_file() and not pyprojectx_exe.is_file():\n        if not options.quiet:\n            print(f\"{CYAN}creating pyprojectx venv in {BLUE}{venv_dir}{RESET}\", file=sys.stderr)\n        env_builder.create(venv_dir)\n        subprocess.run(\n            [*pip_cmd, \"--upgrade\", \"pip\"],\n            stdout=out,\n            check=True,\n        )\n\n        if not options.quiet:\n            print(\n                f\"{CYAN}installing pyprojectx {BLUE}{options.version}: {options.pyprojectx_package} {RESET}\",\n                file=sys.stderr,\n            )\n        if options.version == \"development\":\n            if not options.quiet:\n                print(\n                    f\"{RED}WARNING: {options.pyprojectx_package} is installed in editable mode{RESET}\",\n                    file=sys.stderr,\n                )\n            pip_cmd.append(\"-e\")\n        subprocess.run([*pip_cmd, options.pyprojectx_package], stdout=out, check=True)\n    return pyprojectx_script\n\n\nif __name__ == \"__main__\":\n    run(sys.argv[1:])\n"
  },
  {
    "path": "pw.bat",
    "content": "@echo off\npython \"%~dp0pw\" %*\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 >= 75.1.0\",\n    # the following is from mypy-requirements.txt/setup.py\n    \"basedtyping>=0.1.4\",\n    \"typing_extensions>=4.6.0\",\n    \"mypy_extensions>=1.0.0\",\n    \"tomli>=1.1.0; python_version<'3.11'\",\n    # the following is from build-requirements.txt\n    \"types-psutil\",\n    \"types-setuptools==68.2.0.0\",\n]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"basedmypy\"\ndescription = \"based static typing for Python\"\nreadme = {text = \"\"\"\nBasedmypy -- Based Static typing for Python\n===========================================\n\nBasedmypy is a type checker that is built on top of the work done by the\n`mypy project <https://github.com/python/mypy>`_.\n\"\"\", content-type = \"text/x-rst\"}\nauthors = [{name = \"Jukka Lehtosalo\", email = \"jukka.lehtosalo@iki.fi\"}]\nlicense = {text = \"MIT\"}\nclassifiers = [\n  \"Development Status :: 7 - Inactive\",\n  \"Environment :: Console\",\n  \"Intended Audience :: Developers\",\n  \"License :: OSI Approved :: MIT License\",\n  \"Programming Language :: Python :: 3\",\n  \"Programming Language :: Python :: 3.9\",\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  \"Topic :: Software Development\",\n  \"Typing :: Typed\",\n]\nrequires-python = \">=3.9\"\ndependencies = [\n  # When changing this, also update build-system.requires and mypy-requirements.txt\n  \"basedtyping>=0.1.4\",\n  \"typing_extensions>=4.6.0\",\n  \"mypy_extensions>=1.0.0\",\n  \"tomli>=1.1.0; python_version<'3.11'\",\n]\ndynamic = [\"version\"]\n\n[project.optional-dependencies]\ndmypy = [\"psutil>=4.0\"]\nmypyc = [\"setuptools>=50\"]\nreports = [\"lxml\"]\ninstall-types = [\"pip\"]\nfaster-cache = [\"orjson\"]\n\n[project.urls]\nNews = \"https://github.com/KotlinIsland/basedmypy/releases\"\nDocumentation = \"https://KotlinIsland.github.io/basedmypy\"\nRepository = \"https://github.com/KotlinIsland/basedmypy\"\nChangelog = \"https://github.com/KotlinIsland/basedmypy/blob/master/CHANGELOG.md\"\nDiscord = \"https://discord.gg/7y9upqPrk2\"\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\n[tool.pyprojectx]\nscripts_dir = \"misc\"\n\n[tool.pyprojectx.main]\ndir = \".venv\"\nrequirements = [\"uv\", \"-r test-requirements.txt\", \"-e .\"]\n\n[tool.pyprojectx.aliases]\n_typecheck = \"mypy --config-file mypy_self_check.ini -p mypy -p mypyc\"\ntypecheck = \"@_typecheck --baseline-file=\"\ntypecheck-strict = \"@_typecheck --config-file mypy_self_check_strict.ini\"\nwrite-baseline = \"@typecheck-strict --platform linux --write-baseline\"\ntest = \"pytest -n0 -k\"\n\n\n[tool.black]\nline-length = 99\ntarget-version = [\"py39\", \"py310\", \"py311\", \"py312\", \"py313\"]\nskip-magic-trailing-comma = true\nforce-exclude = '''\n^/mypy/typeshed|\n^/mypyc/test-data|\n^/test-data|\n^/pw$\n'''\n\n[tool.ruff]\nline-length = 99\ntarget-version = \"py39\"\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  \"SIM201\", \"SIM202\", \"SIM222\", \"SIM223\",  # flake8-simplify\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  \"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  \"F821\",  # Clashes with based type-guard\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[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": "from __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\"\n\nprint(executable)\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]\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    # We do a no-strict compatible check, this is needed because generating a baseline from the head of upstream\n    #  sound very laborious, strict check is in tox.ini\n    \"self\": [\n        executable,\n        \"-m\",\n        \"mypy\",\n        \"--config-file\",\n        \"mypy_self_check.ini\",\n        \"--baseline-file=\",\n        \"-p\",\n        \"mypy\",\n        \"-p\",\n        \"mypyc\",\n    ],\n    # Lint\n    \"lint\": [\"mypy\", \"-V\"],\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]),\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    cmd = cmds[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(\"usage:\", prog, \" \".join(f\"[{k}]\" for k in cmds))\n        print()\n        print(\n            \"Run the given tests. If given no arguments, run everything except\"\n            + \" pytest-extra and mypyc-extra.\"\n        )\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, 9, 0):  # noqa: UP036, RUF100\n    sys.stderr.write(\"ERROR: You need Python 3.9 or later to use basedmypy.\\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 __based_version__, __version__, based_version_info\n\nif TYPE_CHECKING:\n    from typing_extensions 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, globs, root=\"mypy\"):\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):\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(\"from mypy.versionutil import VersionInfo\\n\")\n            stream.write(f'__version__ = \"{__version__}\"\\n')\n            stream.write(f\"based_version_info = {based_version_info!r}\\n\")\n            stream.write(f'__based_version__ = \"{__based_version__}\"\\n')\n\n    def run(self):\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            # 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        # Uses __file__ at top level https://github.com/mypyc/mypyc/issues/700\n        os.path.join(\"mypyc\", \"__main__.py\"),\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    ext_modules = mypycify(\n        mypyc_targets + [\"--config-file=mypy_bootstrap.ini\", \"--no-strict\"],\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    )\n    assert is_list_of_setuptools_extension(ext_modules), \"Expected mypycify to use setuptools\"\n\nelse:\n    ext_modules = []\n\n\nsetup(version=__based_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/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_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/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/__init__.pyi",
    "content": "import os\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: int) -> int: ...\n    @overload\n    @staticmethod\n    def overloaded_static_method(value: float) -> float: ...\n    @staticmethod\n    def some_static_method(a: int, b: int) -> 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() -> os.PathLike: ...\ndef func_returning_vector() -> list[float]: ...\n"
  },
  {
    "path": "test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/demo.pyi",
    "content": "from 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: int) -> 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: int) -> 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: float, y: float) -> None: ...\n    def as_list(self) -> list[float]: ...\n    @overload\n    def distance_to(self, x: float, y: float) -> 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: float, right: float) -> float: ...\ndef sum(arg0: int, arg1: int) -> int: ...\ndef weighted_midpoint(left: float, right: float, alpha: float = ...) -> float: ...\n"
  },
  {
    "path": "test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/__init__.pyi",
    "content": "import os\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: int) -> int:\n        \"\"\"overloaded_static_method(*args, **kwargs)\n        Overloaded function.\n\n        1. overloaded_static_method(value: int) -> int\n\n        2. overloaded_static_method(value: float) -> float\n        \"\"\"\n    @overload\n    @staticmethod\n    def overloaded_static_method(value: float) -> float:\n        \"\"\"overloaded_static_method(*args, **kwargs)\n        Overloaded function.\n\n        1. overloaded_static_method(value: int) -> int\n\n        2. overloaded_static_method(value: float) -> float\n        \"\"\"\n    @staticmethod\n    def some_static_method(a: int, b: int) -> int:\n        \"\"\"some_static_method(a: int, b: int) -> 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\ndef func_incomplete_signature(*args, **kwargs):\n    \"\"\"func_incomplete_signature() -> dummy_sub_namespace::HasNoBinding\"\"\"\ndef func_returning_optional() -> int | None:\n    \"\"\"func_returning_optional() -> Optional[int]\"\"\"\ndef func_returning_pair() -> tuple[int, float]:\n    \"\"\"func_returning_pair() -> Tuple[int, float]\"\"\"\ndef func_returning_path() -> os.PathLike:\n    \"\"\"func_returning_path() -> os.PathLike\"\"\"\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": "from 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: int) -> None:\n            \"\"\"__init__(self: pybind11_fixtures.demo.Point.AngleUnit, value: int) -> 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        @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: int) -> None:\n            \"\"\"__init__(self: pybind11_fixtures.demo.Point.LengthUnit, value: int) -> 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        @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        \"\"\"__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: float, y: float) -> None\n        \"\"\"\n    @overload\n    def __init__(self, x: float, y: float) -> 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: float, y: float) -> 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: float, y: float) -> float:\n        \"\"\"distance_to(*args, **kwargs)\n        Overloaded function.\n\n        1. distance_to(self: pybind11_fixtures.demo.Point, x: float, y: float) -> 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: float, y: float) -> 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\ndef answer() -> int:\n    '''answer() -> int\n\n    answer docstring, with end quote\"\n    '''\ndef midpoint(left: float, right: float) -> float:\n    \"\"\"midpoint(left: float, right: float) -> float\"\"\"\ndef sum(arg0: int, arg1: int) -> int:\n    '''sum(arg0: int, arg1: int) -> int\n\n    multiline docstring test, edge case quotes \"\"\"\\'\\'\\'\n    '''\ndef weighted_midpoint(left: float, right: float, alpha: float = ...) -> float:\n    \"\"\"weighted_midpoint(left: float, right: float, alpha: float = 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==2.9.2\",\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 = C # 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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): pass \\\n      # E: Cannot determine consistent method resolution order (MRO) for \"B\"\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: 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: 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[out]\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[out]\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: Definition of \"foo\" in base class \"A\" is incompatible with definition in base class \"Mixin\"\n    pass\n[builtins fixtures/property.pyi]\n[out]\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 \"Union[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]\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 \"Union[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 \"Union[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 testSliceAnnotated39]\n# flags: --python-version 3.9\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\n[case testSliceAnnotated38]\n# flags: --python-version 3.8\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 \"Callable[[Arg(int, 'arg')], None]\", not \"Callable[[int], None]\"\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]\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 \"Union[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]\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 \"Union[__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://kotlinisland.github.io/basedmypy/more_types.html#asynchronous-iterators\n        raise BaseException\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-bare-literals.test",
    "content": "[case testBareLiteralLiterals]\nfrom __future__ import annotations\n\na: 1\nreveal_type(a)  # N: Revealed type is \"1\"\na2: 1 | str\nreveal_type(a2)  # N: Revealed type is \"1 | str\"\na3: \"1 | str\"\nreveal_type(a3)  # N: Revealed type is \"1 | str\"\n\nb: True\nreveal_type(b)  # N: Revealed type is \"True\"\nb2: True | str\nreveal_type(b2)  # N: Revealed type is \"True | str\"\n\nc: False\nreveal_type(c)  # N: Revealed type is \"False\"\nc2: False | str\nreveal_type(c2)  # N: Revealed type is \"False | str\"\n\nd: 1.1  # E: Invalid type: float literals cannot be used as a type  [valid-type]\nd2: 1.1 | str  # E: Invalid type: float literals cannot be used as a type  [valid-type]\n\ne: 1j  # E: Invalid type: complex literals cannot be used as a type  [valid-type]\ne2: 1j | str  # E: Invalid type: complex literals cannot be used as a type  [valid-type]\n[builtins fixtures/tuple.pyi]\n\n\n[case testNoBareLiteralLiterals]\n# flags: --python-version 3.10\n\na1: 1\na2: 1 | str  # E: \"1\" is a bare literal and shouldn't be used in a type operation without \"__future__.annotations\"  [valid-type]\n\nb1: True\nb2: True | str  # E: \"True\" is a bare literal and shouldn't be used in a type operation without \"__future__.annotations\"  [valid-type]\n\nc1: False\nc2: False | str  # E: \"False\" is a bare literal and shouldn't be used in a type operation without \"__future__.annotations\"  [valid-type]\n\nd1: 1.1  # E: Invalid type: float literals cannot be used as a type  [valid-type]\nd2: 1.1 | str  # E: Invalid type: float literals cannot be used as a type  [valid-type]\n\ne1: 1j  # E: Invalid type: complex literals cannot be used as a type  [valid-type]\ne2: 1j | str  # E: Invalid type: complex literals cannot be used as a type  [valid-type]\n\n\n[case testBareLiteralEnum]\n# flags: --python-version 3.10\nfrom __future__ import annotations\nfrom enum import Enum\n\nclass E(Enum):\n    A = 1\n\na: E.A\na2: E.A | str\nreveal_type(a)  # N: Revealed type is \"__main__.E.A\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testNoBareLiteralEnum]\n# flags: --python-version 3.10\nfrom enum import Enum\n\nclass E(Enum):\n    A = 1\n\na: E.A\nb: E.A | str  # E: \"__main__.E.A\" is a bare literal and shouldn't be used in a type operation without \"__future__.annotations\"  [valid-type]\n[builtins fixtures/tuple.pyi]\n\n\n[case testNoBareLiteralTypeAlias]\nfrom __future__ import annotations\nfrom typing_extensions import TypeAlias\nfrom enum import Enum\n\nclass E(Enum):\n    A = 1\n\nA: TypeAlias = 1  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?  [valid-type]\nB: TypeAlias = True  # E: \"True\" is a bare literal and cannot be used here, try Literal[True] instead?  [valid-type]\nC: TypeAlias = False  # E: \"False\" is a bare literal and cannot be used here, try Literal[False] instead?  [valid-type]\nD: TypeAlias = E.A  # E: \"E.A\" is a bare literal and cannot be used here, try Literal[E.A] instead?  [valid-type]\nA2 = str | 2  # E: Unsupported left operand type for | (\"type[str]\")  [operator]\na2: A2  # E: Variable \"__main__.A2\" is not valid as a type  [valid-type] \\\n       # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/tuple.pyi]\n\n\n[case testBareLiteralTypeVarBound]\n# flags: --python-version 3.10\n\nfrom typing import TypeVar\nT1 = TypeVar(\"T1\", bound=list[1])  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?  [valid-type]\nT2 = TypeVar(\"T2\", str, list[1])  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?  [valid-type]\n\n\n[case testBareLiteralGeneric]\n# flags: --python-version 3.10\nl1: list[1]  # E: \"1\" is a bare literal and shouldn't be used in a type operation without \"__future__.annotations\"  [valid-type]\nl1 = list[1]()  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?  [valid-type]\n\n\n[case testBareLiteralsInStubs]\nimport a\n[file a.pyi]\nfrom typing import TypeVar\nT = TypeVar(\"T\", 1, 2)\na: 1 | 2\n"
  },
  {
    "path": "test-data/unit/check-based-callable.test",
    "content": "[case testCallableSyntax]\nc: \"(str) -> int\"\nreveal_type(c)  # N: Revealed type is \"(str) -> int\"\nf: \"def (str) -> int\"\nreveal_type(f)  # N: Revealed type is \"def (str) -> int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testCallableSyntaxBreak]\n# ensure things that look a lot like Callable syntax are handled as not that\nfrom typing import Literal\nt: \"(Literal['->'])\"\nreveal_type(t)  # N: Revealed type is \"'->'\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n\n[case testCallableIsntFunction]\nc: \"(str) -> int\"\nc.__name__  # E: \"(str) -> int\" has no attribute \"__name__\"  [attr-defined]\nf: \"def (str) -> int\"\nreveal_type(f.__name__)  # N: Revealed type is \"str\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n\n[case testFunctionTypeSubtypesCallable]\nc: \"(str) -> int\"\nf: \"def (str) -> int\" = c  # E: Incompatible types in assignment (expression has type \"(str) -> int\", variable has type \"def (str) -> int\")  [assignment]\nc2: \"(str) -> int\" = f\n[builtins fixtures/tuple.pyi]\n\n\n[case testFunctiontypeInferred]\ndef f(): ...\nreveal_type(f)  # N: Revealed type is \"def () -> None\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testRuntimeFunctionType]\nfrom types import FunctionType\nimport future\n\na: FunctionType[[int], str]  # E: Type parameters for \"FunctionType\" requires `from __future__ import annotations` or quoted types  [valid-type] \\\n                             # N: Or you can use \"basedtyping.FunctionType\" instead\nFoo = FunctionType[[int], str]  # E: Type parameters for \"FunctionType\" requires `from __future__ import annotations` or quoted types  [valid-type] \\\n                                # N: Or you can use \"basedtyping.FunctionType\" instead\n[file future.py]\nfrom __future__ import annotations\nfrom types import FunctionType\na: FunctionType[[int], str]\nFoo = FunctionType[[int], str]  # E: Type parameters for \"FunctionType\" requires `from __future__ import annotations` or quoted types  [valid-type] \\\n                                # N: Or you can use \"basedtyping.FunctionType\" instead\n[builtins fixtures/tuple.pyi]\n\n\n[case testFunctionTypeNoArguments]\nfrom types import FunctionType\n\na: FunctionType\n\nfrom basedtyping import FunctionType as BasedFunctionType\n\nb: BasedFunctionType   # E: Missing type parameters for generic type \"BasedFunctionType\"  [type-arg]\n[builtins fixtures/tuple.pyi]\n\n\n[case testFunctionTypeOnInstance]\nfrom typing import ClassVar\nclass A:\n    a: ClassVar[\"def (A) -> int\"]\na = A()\nA.a(a)\na.a()\n[builtins fixtures/tuple.pyi]\n\n\n[case testMethodType]\nimport types\nclass A:\n    def f(self): ...\nreveal_type(A().f)  # N: Revealed type is \"_NamedCallable & () -> None\"\nb: int = A().f  # E: Incompatible types in assignment (expression has type \"_NamedCallable & () -> None\", variable has type \"int\")  [assignment]\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypeType]\nclass A: ...\nreveal_type(A)  # N: Revealed type is \"() -> __main__.A\"\nb: int = A  # E: Incompatible types in assignment (expression has type \"type[A]\", variable has type \"int\")  [assignment]\n[builtins fixtures/tuple.pyi]\n\n\n[case testClassAssignments]\nfrom __future__ import annotations\nfrom typing import Callable, ClassVar\nfrom types import FunctionType\n\nsome_callable: Callable[['C'], int]\nsome_function: FunctionType[['C'], int]\n\nclass C:\n    c1: Callable[['C'], int]  # callable attribute\n    c2: FunctionType[['C'], int]  # callable attribute\n    c3: Callable[['C'], int] = some_function  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                              # N: Consider setting it on the instance, or using \"ClassVar\"\n    c4: FunctionType[['C'], int] = some_function  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                                  # N: Consider setting it on the instance, or using \"ClassVar\"\n\n    m1 = some_function  # method, because of assignment\n    def m2(self) -> int: return 1\n    m3 = some_callable  # method, because of assignment\n\n    a1: ClassVar[Callable[['C'], int]]\n    a2: ClassVar[FunctionType[['C'], int]]\n\n    def __init__(self):\n        self.c5: Callable[[], int]  # callable attribute\n        self.c6 = some_function  # callable attribute\n        self.m1 = some_function  # E: Cannot assign to a method  [method-assign] \\\n                                 # E: Incompatible types in assignment (expression has type \"def (C) -> int\", variable has type \"_NamedCallable & () -> int\")  [assignment]\n\nC.c1 = lambda x: 1  # error, too sus  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                      # N: Consider setting it on the instance, or using \"ClassVar\"\nC.c2 = lambda x: 1  # error, too sus  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                      # N: Consider setting it on the instance, or using \"ClassVar\"\nC.c3 = lambda x: 1  # error, too sus  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                      # N: Consider setting it on the instance, or using \"ClassVar\"\nC.c4 = lambda x: 1  # error, too sus  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                      # N: Consider setting it on the instance, or using \"ClassVar\"\nC.c5 = lambda x: 1  # error, too sus  # E: Cannot infer type of lambda  [misc] \\\n                                      # E: Incompatible types in assignment (expression has type \"def (x: Untyped) -> int\", variable has type \"() -> int\")  [assignment] \\\n                                      # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                      # N: Consider setting it on the instance, or using \"ClassVar\"\nC.c6 = lambda x: 1  # error, too sus  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                      # N: Consider setting it on the instance, or using \"ClassVar\"\n\nC.m1 = lambda x: 1  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                    # N: Consider setting it on the instance, or using \"ClassVar\"\nC.m2 = lambda x: 1  # error, can't assign to a method  # E: Cannot assign to a method  [method-assign] \\\n                                                       # E: Incompatible types in assignment (expression has type \"def (x: C) -> int\", variable has type \"def (self: C) -> int\")  [assignment] \\\n                                                       # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype] \\\n                                                       # N: Consider setting it on the instance, or using \"ClassVar\"\n\nC.a1 = lambda x: 1  # E: Assigning a \"FunctionType\" on the class will become a \"MethodType\"  [callable-functiontype]\nC.a1 = some_callable  # E: This \"CallableType\" could be a \"FunctionType\", which when assigned via the class, would produce a \"MethodType\"  [possible-function] \\\n                      # N: Consider changing the type to \"FunctionType\"\nC.a2 = lambda x: 1\n\nc: C\nreveal_type(c.c1)  # N: Revealed type is \"(__main__.C) -> int\"\nreveal_type(c.c2)  # N: Revealed type is \"def (__main__.C) -> int\"\nreveal_type(c.c3)  # N: Revealed type is \"(__main__.C) -> int\"\nreveal_type(c.c4)  # N: Revealed type is \"def (__main__.C) -> int\"\nreveal_type(c.c5)  # N: Revealed type is \"() -> int\"\nreveal_type(c.c6)  # N: Revealed type is \"def (__main__.C) -> int\"\n\nreveal_type(c.m1)  # N: Revealed type is \"_NamedCallable & () -> int\"\nreveal_type(c.m2)  # N: Revealed type is \"_NamedCallable & () -> int\"\n\nreveal_type(c.a1)  # N: Revealed type is \"(__main__.C) -> int\"\nreveal_type(c.a2)  # N: Revealed type is \"_NamedCallable & () -> int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testCallableDecorator]\nfrom typing import Callable, TypeVar\nfrom types import FunctionType\n\nT = TypeVar(\"T\")\ndef as_functiontype(fn: Callable[[T], None]) -> \"FunctionType[[T], None]\": ...\n\ndef dec(fn: Callable[[T], None]) -> Callable[[T], None]: ...\n\nclass A:\n    def m1(self): ...\n    @dec  # E: This decorator returns a \"Callable\", not a \"FunctionType\". Decorate this decorator with \"basedtyping.as_functiontype\", or add a 'type: ignore' if it's intentional  [callable-functiontype]\n    def m2(self): ...\n    @as_functiontype\n    @dec\n    def m3(self): ...\n    @dec\n    @classmethod\n    def m4(cls): ...\n    @dec\n    @staticmethod\n    def m5(arg: int): ...\n@dec\ndef f(a: A): ...\na: A\na.m1()\na.m2(a)\na.m3()\na.m4()\na.m5(1)\n[builtins fixtures/classmethod.pyi]\n\n\n[case testClassVarCallable]\nfrom typing import ClassVar\nclass A:\n    a: ClassVar[\"(A) -> None\"]\n    m: ClassVar[\"def (A) -> None\"]\n\na: A\na.a(a)\na.m()\n\n\n[case testCallableNew]\n# mypy: no-infer-function-types, allow-untyped-defs, allow-incomplete-defs, allow-any-expr, no-default-return\n\nclass A:\n    def __new__(cls, a: int): ...\nclass B:\n    def __new__(cls, a): ...\n\nreveal_type(A.__new__)  # N: Revealed type is \"def (cls: type[__main__.A], a: int) -> Untyped\"\nreveal_type(B.__new__)  # N: Revealed type is \"def (cls: type[__main__.B], a: Untyped) -> Untyped\"\na: A\nb: B\nreveal_type(a.__new__)  # N: Revealed type is \"def (cls: type[__main__.A], a: int) -> Untyped\"\nreveal_type(b.__new__)  # N: Revealed type is \"def (cls: type[__main__.B], a: Untyped) -> Untyped\"\n\nimport strict\n\n[file strict.py]\nclass A:\n    def __new__(cls, a: int): ...\n\nreveal_type(A.__new__)  # N: Revealed type is \"def (cls: type[strict.A], a: int) -> strict.A\"\nreveal_type(A(1).__new__)  # N: Revealed type is \"def (cls: type[strict.A], a: int) -> strict.A\"\n\n\n[case testOverloadNotFunctionType]\nfrom typing import Callable, overload\n\nclass A:\n    def __init__(self, _: object): ...\n    def __call__(self, a: int=1): ...\n\n@overload\ndef f(): ...\n\n@overload\ndef f(a: int): ...\n\n@A\ndef f(): ...\n\n\n[case testNamedCallable]\n# flags: --disallow-redefinition\nclass A:\n    def f(self): ...\n\nclass C1:\n    __name__: str\n    __qualname__: str\n    def __call__(self): ...\nclass C2:\n    def __call__(self): ...\n\nf = A().f\nreveal_type(f)  # N: Revealed type is \"_NamedCallable & () -> None\"\nf = C1()\nf = C2()  # E: Incompatible types in assignment (expression has type \"C2\", variable has type \"_NamedCallable & () -> None\")  [assignment] \\\n          # N: \"C2.__call__\" has type \"() -> None\"\n\n\n[case testVariousMethods]\nclass A:\n    def f(self): ...\n\n    @classmethod\n    def c(cls): ...\n\n    @staticmethod\n    def s(): ...\n\nreveal_type(A.f)  # N: Revealed type is \"def (self: __main__.A) -> None\"\nreveal_type(A.c)  # N: Revealed type is \"_NamedCallable & () -> None\"\nreveal_type(A.s)  # N: Revealed type is \"_NamedCallable & () -> None\"\nreveal_type(A().f)  # N: Revealed type is \"_NamedCallable & () -> None\"\nreveal_type(A().c)  # N: Revealed type is \"_NamedCallable & () -> None\"\nreveal_type(A().s)  # N: Revealed type is \"_NamedCallable & () -> None\"\n[builtins fixtures/callable.pyi]\n\n\n[case testNonInstanceThing]\n# test a crash when the subject isn't an instance\nfrom collections import namedtuple\n\nf = namedtuple(\"f\", \"\")\nf.__repr__ = lambda _: \"\"  # E: \"type[f]\" has no attribute \"__repr__\"  [attr-defined] \\\n                           # E: Expression type contains \"Any\" (has type \"def (_: Untyped) -> str\")  [any]\nreveal_type(f)  # N: Revealed type is \"() -> tuple[(), fallback=__main__.f]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testBasedtypingFunctionType]\nfrom basedtyping import FunctionType\n\na: FunctionType[[], None]  # testing that it doesn't get an error here\nreveal_type(a)  # N: Revealed type is \"def () -> None\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-cast.test",
    "content": "[case testNonOverlappingCast]\nfrom typing import cast, List\n\na: int\ncast(str, a)  # E: Conversion of type \"int\" to type \"str\" may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to \"object\" first.  [bad-cast]\ncast(str, cast(object, a))\nb: List[int]\ncast(List[str], b)  # E: Conversion of type \"list[int]\" to type \"list[str]\" may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to \"object\" first.  [bad-cast]\ncast(List[object], b)\n"
  },
  {
    "path": "test-data/unit/check-based-conditional-types.test",
    "content": "\n[case testConditionalType]\nfrom __future__ import annotations\n\ndef f(x: object) -> x is int if True else False: ...\n\nreveal_type(f)  # N: Revealed type is \"def (x: object) -> x is int if True else False\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testConditionalTypePast]\ndef f1(x: object) -> \"x is int\" if True else False: ...  # E: You need to put quotes around the entire type-guard, or enable `__future__.annotations`  [misc]\ndef f2(x: object) -> \"x is int if True else False\": ...\n\n\n[case testConditionalTypeUnsupported]\nfrom __future__ import annotations\n\ndef f1(x: object) -> x is int if int else False: ...  # E: Invalid type comment or annotation  [valid-type] \\\n                                                      # N: The condition can only be \"True\"\ndef f2(x: object) -> int if True else False: ...  # E: Invalid type comment or annotation  [valid-type] \\\n                                                  # N: The true branch can only be a type-guard\ndef f3(x: object) -> x is int if True else x is str: ...  # E: Invalid type comment or annotation  [valid-type] \\\n                                                          # N: The false branch can only be \"False\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-default-return.test",
    "content": "-- Type checker test cases for default return type.\n\n\n[case testSimple]\ndef f(): ...\nreveal_type(f)  # N: Revealed type is \"def () -> None\"\nreveal_type(f())  # N: Revealed type is \"None\"\n\ndef g(i: int): ...\nreveal_type(g)  # N: Revealed type is \"def (i: int) -> None\"\n\nclass A:\n    def f(self): ...\n    def g(self, i: int): ...\n\nreveal_type(A.f)  # N: Revealed type is \"def (self: __main__.A) -> None\"\nreveal_type(A.g)  # N: Revealed type is \"def (self: __main__.A, i: int) -> None\"\n\n\n[case testUntypedDefs]\n# flags: --allow-untyped-defs --allow-any-expr\n\ndef f(): ...\nreveal_type(f)  # N: Revealed type is \"def () -> Untyped\"\n\ndef g(i: int): ...\nreveal_type(g)  # N: Revealed type is \"def (i: int) -> None\"\n\ndef h(i: int, j): ...  # E: Function is missing a type annotation for one or more arguments  [no-untyped-def]\n\nclass A:\n    def f(self): ...\n    def g(self, i): ...\n    def h(self, i: int): ...\n    def i(self, i: int, j): ... # E: Function is missing a type annotation for one or more arguments  [no-untyped-def]\n\nreveal_type(A.f)  # N: Revealed type is \"def (self: __main__.A) -> Untyped\"\nreveal_type(A.g)  # N: Revealed type is \"def (self: __main__.A, i: Untyped) -> Untyped\"\nreveal_type(A.h)  # N: Revealed type is \"def (self: __main__.A, i: int) -> None\"\nreveal_type(A.i)  # N: Revealed type is \"def (self: __main__.A, i: int, j: Untyped) -> None\"\n\n\n[case testIncompleteDefs]\n# flags: --allow-incomplete-defs --allow-untyped-defs --allow-any-expr\n\ndef f(i): ...\nreveal_type(f)  # N: Revealed type is \"def (i: Untyped) -> Untyped\"\n\ndef g(i: int, j): ...\nreveal_type(g)  # N: Revealed type is \"def (i: int, j: Untyped) -> None\"\n\nclass A:\n    def f(self): ...\n    def g(self, i): ...\n    def h(self, i: int): ...\n    def i(self, i: int, j): ...\n\nreveal_type(A.f)  # N: Revealed type is \"def (self: __main__.A) -> Untyped\"\nreveal_type(A.g)  # N: Revealed type is \"def (self: __main__.A, i: Untyped) -> Untyped\"\nreveal_type(A.h)  # N: Revealed type is \"def (self: __main__.A, i: int) -> None\"\nreveal_type(A.i)  # N: Revealed type is \"def (self: __main__.A, i: int, j: Untyped) -> None\"\n\n\n[case testGenerator]\ndef f():  # E: The return type of a generator function should be \"Generator\" or one of its supertypes  [misc]\n    yield\n\ndef g(i: int):  # E: The return type of a generator function should be \"Generator\" or one of its supertypes  [misc]\n    yield\n\nclass A:\n    def f(self): # E: The return type of a generator function should be \"Generator\" or one of its supertypes  [misc]\n        yield\n    def g(self, i: int): # E: The return type of a generator function should be \"Generator\" or one of its supertypes  [misc]\n        yield\n\n\n[case testAsync]\nasync def f1():\n    ...\nasync def f2():  # E: The return type of an async generator function should be \"AsyncGenerator\" or one of its supertypes  [misc]\n    yield\n\nasync def g1(i: int):\n    ...\nasync def g2(i: int):  # E: The return type of an async generator function should be \"AsyncGenerator\" or one of its supertypes  [misc]\n    yield\n\nclass A:\n    async def f1(self):\n        ...\n    async def f2(self): # E: The return type of an async generator function should be \"AsyncGenerator\" or one of its supertypes  [misc]\n        yield\n    async def g1(self, i: int):\n        ...\n    async def g2(self, i: int): # E: The return type of an async generator function should be \"AsyncGenerator\" or one of its supertypes  [misc]\n        yield\n\n[case testLambda]\n# flags: --allow-any-expr\n\nf = lambda x: x\ng = lambda: ...\nreveal_type(f)  # N: Revealed type is \"def (x: Untyped) -> Any\"\nreveal_type(g)  # N: Revealed type is \"def () -> ellipsis\"\n\n\n[case testExplicitAny]\n# flags: --allow-any-expr  --allow-any-explicit\nfrom typing import Any\n\ndef f() -> Any: ...\ndef g(i: int) -> Any: ...\nreveal_type(f)  # N: Revealed type is \"def () -> Any\"\nreveal_type(g)  # N: Revealed type is \"def (i: int) -> Any\"\n\nclass A:\n    def f(self) -> Any: ...\n    def g(self, i: int) -> Any: ...\nreveal_type(A.f)  # N: Revealed type is \"def (self: __main__.A) -> Any\"\nreveal_type(A.g)  # N: Revealed type is \"def (self: __main__.A, i: int) -> Any\"\n\n\n[case testNoDefaultReturn]\n# flags: --no-default-return --allow-any-expr\n\ndef f(i): ...  # E: Function is missing a type annotation  [no-untyped-def]\ndef g(i: int, j): ...  # E: Function is missing a return type annotation  [no-untyped-def] \\\n                       # E: Function is missing a type annotation for one or more arguments  [no-untyped-def]\n\nclass A:\n    def f(self, i): ...  # E: Function is missing a type annotation  [no-untyped-def]\n    def g(self, i: int, j): ...  # E: Function is missing a return type annotation  [no-untyped-def] \\\n                                 # E: Function is missing a type annotation for one or more arguments  [no-untyped-def]\n\n\n[case testOverload]\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self): ...\n    @overload\n    def f(self, i: int): ...\n    def f(self, i: int = 0): ...\n\nreveal_type(A.f)  # N: Revealed type is \"Overload(def (self: __main__.A) -> None, def (self: __main__.A, i: int) -> None)\"\n\n@overload\ndef f(): ...\n@overload\ndef f(i: int): ...\ndef f(i: int = 0): ...\n\nreveal_type(f)  # N: Revealed type is \"Overload(def () -> None, def (i: int) -> None)\"\n\n\n[case testOverloadIncomplete]\n# flags: --allow-incomplete-defs --allow-untyped-defs --allow-any-expr --allow-any-decorated\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self): ...\n    @overload\n    def f(self, i): ...\n    @overload\n    def f(self, i, j: int): ...\n    def f(self, i: int = 0, j: int = 0): ...\n\nreveal_type(A.f)  # N: Revealed type is \"Overload(def (self: __main__.A) -> None, def (self: __main__.A, i: Untyped) -> None, def (self: __main__.A, i: Untyped, j: int) -> None)\"\n\n@overload\ndef f(): ...\n@overload\ndef f(i): ...\n@overload\ndef f(i, j: int): ...\ndef f(i: int = 0, j: int = 0): ...\n\nreveal_type(f)  # N: Revealed type is \"Overload(def () -> None, def (i: Untyped) -> None, def (i: Untyped, j: int) -> None)\"\n\n\n[case testOverloadUntyped]\n# flags: --allow-untyped-defs --allow-any-expr --allow-any-decorated\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self): ...\n    @overload\n    def f(self, i): ...\n    @overload\n    def f(self, *, j: int): ...\n    def f(self, i: int = 0, j: int = 0): ...\n\nreveal_type(A.f)  # N: Revealed type is \"Overload(def (self: __main__.A) -> None, def (self: __main__.A, i: Untyped) -> None, def (self: __main__.A, *, j: int) -> None)\"\n\n@overload\ndef f(): ...\n@overload\ndef f(i): ...\n@overload\ndef f(*, j: int): ...\ndef f(i: int = 0, j: int = 0): ...\n\nreveal_type(f)  # N: Revealed type is \"Overload(def () -> None, def (i: Untyped) -> None, def (*, j: int) -> None)\"\n\n[case testOverloadOther]\n# flags: --allow-untyped-defs --allow-incomplete-defs --allow-any-expr --allow-any-decorated\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self) -> int: ...\n    @overload\n    def f(self, i): ...\n    @overload\n    def f(self, i, j: int): ...\n    def f(self, i: int = 0, j: int = 0) -> object: ...\n\nreveal_type(A.f)  # N: Revealed type is \"Overload(def (self: __main__.A) -> int, def (self: __main__.A, i: Untyped) -> None, def (self: __main__.A, i: Untyped, j: int) -> None)\"\n\nclass B:\n    @overload\n    def f(self) -> str: ...\n    @overload\n    def f(self, i): ...\n    @overload\n    def f(self, i, j: int) -> int: ...\n    def f(self, i: int = 0, j: int = 0) -> object: ...\n\nreveal_type(B.f)  # N: Revealed type is \"Overload(def (self: __main__.B) -> str, def (self: __main__.B, i: Untyped) -> None, def (self: __main__.B, i: Untyped, j: int) -> int)\"\n\n\n[case testNewHasError]\n# flags: --no-infer-function-types\nclass A:\n    def __new__(cls): ...  # E: \"__new__\" must return a class instance (got \"None\")  [misc]\n\nreveal_type(A.__new__)  # N: Revealed type is \"def (cls: type[__main__.A]) -> None\"\n"
  },
  {
    "path": "test-data/unit/check-based-format.test",
    "content": "[case testFormatObject]\nx: object\nf\"{x:1}\"  # E: The string for \"object\" isn't helpful in a user-facing or semantic string  [helpful-string] \\\n          # E: The type \"object\" doesn't support format-specifiers  [str-format] \\\n          # N: Maybe you want to add '!s' to the conversion\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatNone]\nx: None\nf\"{x:1}\"  # E: The string for \"None\" isn't helpful in a user-facing or semantic string  [helpful-string] \\\n          # E: The type \"None\" doesn't support format-specifiers  [str-format] \\\n          # N: Maybe you want to add '!s' to the conversion\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatInt]\nx: int\nf\"{x:1}\"\nf\"{x:.1f}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatStr]\nx: str\nf\"{x:1}\"\nf\"{x:.1f}\"  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | complex\")  [str-format]\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatFloat]\nx: float\nf\"{x:1}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatConplex]\nx: complex\nf\"{x:1}\"\nf\"{x:.1f}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatWithStringCoversion]\nx: object\nf\"{x!s:1}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testTypeWithFormat]\nclass X:\n    def __format__(self, format_spec: str) -> str: ...\n\nx: X\nf\"{x:1}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testDatetimeFormat]\nfrom datetime import date\nimport sys\n\nf\"{date(1,1,1):%%%m%%:}\"\n\nf\"{date(1,1,1):%t%i%:Y}\"  # E: Invalid format sequence '%t', escape with '%%'  [str-format] \\\n                         # E: Invalid format sequence '%i', escape with '%%'  [str-format] \\\n                         # E: Invalid format sequence '%:Y', escape with '%%'  [str-format]\nf\"{date(1,1,1):%}\"  # E: Invalid trailing '%', escape with '%%'  [str-format]\nf\"{date(1,1,1):%:}\"  # E: Invalid trailing '%:', escape with '%%'  [str-format]\nif sys.version_info[1] < 12:  # type: ignore[operator]\n    f\"{date(1,1,1):%:z}\"  # E: Format sequence '%:z' is new in version 3.12  [str-format]\nelse:\n    f\"{date(1,1,1):%t}\"\n\nclass D(date):\n    def __format__(self, s: str) -> str: ...\nf\"{D(1,1,1):% %:z}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testHelpfulExplicitStr]\ndef s(o: object) -> str: ...\nn: None\nf\"{s(n)}\"\no: object\nf\"{s(o)}\"\nclass A: ...\na: A\nf\"{s(a)}\"\n[builtins fixtures/f_string.pyi]\n\n\n[case testFormatHelpful]\nfrom typing_extensions import override\nfrom datetime import datetime\nfrom dataclasses import dataclass\n\no: object\nf\"{o}\"  # E: The string for \"object\" isn't helpful in a user-facing or semantic string  [helpful-string]\nn: None\nf\"{n}\"  # E: The string for \"None\" isn't helpful in a user-facing or semantic string  [helpful-string]\n\ndef f(o: object): ...\nf\"{f}\"  # E: The type \"def (o: object) -> None\" doesn't define a __format__, __str__ or __repr__ method  [helpful-string]\nclass A: ...\nf\"{A}\"  # E: The type \"() -> __main__.A\" doesn't define a __format__, __str__ or __repr__ method  [helpful-string]\nf\"{A()}\"  # E: The type \"__main__.A\" doesn't define a __format__, __str__ or __repr__ method  [helpful-string]\nclass F:\n    def __format__(self, format_spec: str) -> str: ...\nf\"{F}\"  # E: The type \"() -> __main__.F\" doesn't define a __format__, __str__ or __repr__ method  [helpful-string]\nf\"{F()}\"\nclass S:\n    @override\n    def __str__(self) -> str: ...\n\nclass R:\n    def __repr__(self) -> str: ...\nf\"{R}\"  # E: The type \"() -> __main__.R\" doesn't define a __format__, __str__ or __repr__ method  [helpful-string]\nf\"{R()}\"\nf\"{1}\"\ni: int\nf\"{i}\"\nd: datetime\nf\"{d}\"\n\n@dataclass\nclass D:\n    a: int\ndata: D\nf\"{data}\"\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-generic-typevar-bound.test",
    "content": "[case testGenericTypeVarBound]\nfrom typing import TypeVar, List\n\nT = TypeVar(\"T\", bound=int)\nL = TypeVar(\"L\", bound=List[T])\n\ndef foo(l: L) -> T:\n    return l[0]\n\nreveal_type(foo([True]))  # N: Revealed type is \"bool\"\nfoo([\"\"])  # E: Value of type variable \"T\" of \"foo\" cannot be \"str\"  [type-var]\n\n\n[case testParamSpecEllipsis]\nfrom typing import TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nT = TypeVar(\"T\")\n\nclass C(Generic[P]): ...\nCT = TypeVar(\"CT\", bound=C[...])  # type: ignore[explicit-any]\n\ndef f(ct: CT): ...  # E: Explicit \"Any\" is not allowed  [explicit-any]\n[builtins fixtures/tuple.pyi]\n\n\n[case testParamSpecWithGenericTypeVar-xfail]\nfrom typing import TypeVar, Generic, Callable\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nT = TypeVar(\"T\")\n\nclass C(Generic[P]):\n    c: Callable[P, int]\nCT = TypeVar(\"CT\", bound=C[T])\n\ndef f(t: T, ct: CT) -> int:\n    ct(1)  # E: what the?\n    return ct(t)\n\nf(1, C[str]())  # E: What the?\nf(1, C[int]())\n[builtins fixtures/tuple.pyi]\n\n\n[case testGenericTypeVarConstraint-xfail]\nfrom typing import TypeVar, Iterable\n\nE = TypeVar(\"E\", int, str)\nI = TypeVar(\"I\", bound=Iterable[E])\n\ndef foo(i: I, e: E) -> I:\n    assert i[0] == e\n    return i\n\nreveal_type(foo([True], True))  # N: Revealed type is \"list[int]\"\nreveal_type(foo([\"my\"], \"py\"))  # N: Revealed type is \"list[str]\"\nreveal_type(foo([\"my\"], 10))  # E: argument 2 is bad\nreveal_type(foo([None], None))  # E: \"I of foo\" cannot be \"list[None]\"\n\n\n[case testGenericTypeVarConstraint2-xfail]\nfrom typing import TypeVar, Iterable, Set\n\nT = TypeVar(\"T\", bound=int)\nC = TypeVar(\"L\", Sequence[T], Mapping[T, T])\n\ndef foo(c: C, t: T) -> C:\n    assert c[0] == t\n    return c\n\nreveal_type(foo([True], True))  # N: Revealed type is \"Sequence[bool]\"\nreveal_type(foo([\"my\"], \"py\"))  # E: \"T of foo\" can't be \"str\"\nreveal_type(foo({1: 1}, \"10\"))  # E: bad arg 2\nreveal_type(foo({True: True}, True))  # N: Mapping[bool]\n"
  },
  {
    "path": "test-data/unit/check-based-ignore-any-from-error.test",
    "content": "[case testIgnoreAnyFromError]\nfrom typing import Any\na = AMONGUS  # E: Name \"AMONGUS\" is not defined  [name-defined]\nb = a + 1\nc = b()\nd = [c]\ne = d[0].d\ne + 1\nf: Any  # E: Explicit \"Any\" is not allowed  [explicit-any]\ng = f + 1  # E: Expression has type \"Any\"  [any]\n\n[case testIncludeAnyFromError]\n# flags: --show-any-from-error\nfrom typing import Any\na = AMONGUS  # E: Name \"AMONGUS\" is not defined  [name-defined] \\\n             # E: Expression has type \"Any (from error)\"  [any]\nb = a + 1  # E: Expression has type \"Any (from error)\"  [any]\nc = b()  # E: Expression has type \"Any (from error)\"  [any]\nd = [c]  # E: Expression type contains \"Any\" (has type \"list[Any (from error)]\")  [any] \\\n         # E: Expression has type \"Any (from error)\"  [any]\ne = d[0].d  # E: Expression type contains \"Any\" (has type \"list[Any (from error)]\")  [any] \\\n            # E: Expression has type \"Any (from error)\"  [any]\ne + 1  # E: Expression has type \"Any (from error)\"  [any]\nf: Any  # E: Explicit \"Any\" is not allowed  [explicit-any]\ng = f + 1  # E: Expression has type \"Any\"  [any]\n\n\n[case testErrorInAssignment]\nclass A: b: int\n\nA.b = b  # E: Name \"b\" is not defined  [name-defined]\n"
  },
  {
    "path": "test-data/unit/check-based-incomplete-defs.test",
    "content": "[case testCallingIncomplete]\n# flags: --config-file tmp/mypy.ini\nfrom b import foo\nfoo(1, 2)  # E: Call to incomplete function \"foo\" in typed context  [no-untyped-call] \\\n           # N: Type is \"def (a: int, b: Untyped) -> None\"\n\n[file b.py]\ndef foo(a: int, b): ...\n\n[file mypy.ini]\n\\[mypy]\nincomplete_is_typed = True\nallow_incomplete_defs = True\nallow_untyped_defs = True\n\\[mypy-b]\nincomplete_is_typed = False\n\n\n[case testCallingIncompleteAsTyped]\n# flags: --config-file tmp/mypy.ini\nfrom b import foo\nfoo(1, 2)\n\n[file b.py]\ndef foo(a: int, b): ...\n\n[file mypy.ini]\n\\[mypy]\nincomplete_is_typed = False\nallow_incomplete_defs = True\nallow_untyped_defs = True\n\\[mypy-b]\nincomplete_is_typed = True\n\n\n[case typeIgnoreWorksProperly]\n# This test is to check that the `notes` param on `mypy.errors.Errors.report` works correctly\ndef f(a, b: int = 1): ...  # type: ignore[no-untyped-def]\nf(\n1)  # type: ignore[no-untyped-call]\n[out]\n"
  },
  {
    "path": "test-data/unit/check-based-infer-function-types.test",
    "content": "-- Type checker test cases for infer-function-types.\n\n[case testInferFunctionTypesUntyped-xfail]\n# flags: --allow-untyped-defs --allow-incomplete-defs --allow-any-expr\n\ndef f(): ...\nreveal_type(f)  # N: Revealed type is \"def () -> Untyped\"\nf()  # E: Call to untyped function \"f\" in typed context  [no-untyped-call]\n\ndef g(i=1, b=\"\"): ...\nreveal_type(g)  # N: Revealed type is \"def (i: int =, b: str =) -> Untyped\"\ng()  # E: Call to untyped function \"g\" in typed context  [no-untyped-call]\n\nclass A1:\n    def __new__(cls): ...\n    def __init__(self): ...\nclass B1(A1):\n    def __new__(cls): ...\n    def __init__(self): ...\n\nreveal_type(A1.__new__)  # N: Revealed type is \"def (cls: type[__main__.A1]) -> Untyped\"\nreveal_type(B1.__new__)  # N: Revealed type is \"def (cls: type[__main__.B1]) -> Untyped\"\nreveal_type(A1.__init__)  # N: Revealed type is \"def (self: __main__.A1) -> None\"\nreveal_type(B1.__init__)  # N: Revealed type is \"def (self: __main__.B1) -> None\"\n\nclass A2:\n    def __new__(cls, a: int): ...\n    def __init__(self, a: int): ...\nclass B2(A2):\n    def __new__(cls, a): ...\n    def __init__(self, a): ...\n\nreveal_type(A2.__new__)  # N: Revealed type is \"def (cls: type[__main__.A2], a: int) -> __main__.A2\"\nreveal_type(B2.__new__)  # N: Revealed type is \"def (cls: type[__main__.B2], a: int) -> __main__.B2\"\nreveal_type(A2.__init__)  # N: Revealed type is \"def (self: __main__.A2, a: int) -> None\"\nreveal_type(B2.__init__)  # N: Revealed type is \"def (self: __main__.B2, a: int) -> None\"\n\n\n[case testInferFunctionTypesComplete-xfail]\nclass A1:\n    def __new__(cls): ...\n    def __init__(self): ...\nclass B1(A1):\n    def __new__(cls): ...\n    def __init__(self): ...\n\nreveal_type(A1.__new__)  # N: Revealed type is \"def (cls: type[__main__.A1]) -> __main__.A1\"\nreveal_type(B1.__new__)  # N: Revealed type is \"def (cls: type[__main__.B1]) -> __main__.B1\"\nreveal_type(A1.__init__)  # N: Revealed type is \"def (self: __main__.A1) -> None\"\nreveal_type(B1.__init__)  # N: Revealed type is \"def (self: __main__.B1) -> None\"\n\nclass A2:\n    def __new__(cls, a: int): ...\n    def __init__(self, a: int): ...\nclass B2(A2):\n    def __new__(cls, a): ...\n    def __init__(self, a): ...\n\nreveal_type(A2.__new__)  # N: Revealed type is \"def (cls: type[__main__.A2], a: int) -> __main__.A2\"\nreveal_type(B2.__new__)  # N: Revealed type is \"def (cls: type[__main__.B2], a: int) -> __main__.B2\"\nreveal_type(A2.__init__)  # N: Revealed type is \"def (self: __main__.A2, a: int) -> None\"\nreveal_type(B2.__init__)  # N: Revealed type is \"def (self: __main__.B2, a: int) -> None\"\n\n\n[case testDefaultInstance-xfail]\nclass A: ...\ndef f(a=A()): ...\nreveal_type(f)  # N: Revealed type is \"def (a: __main__.A =) -> None\"\n\nclass B:\n    def foo(self, a: object): ...\nclass C(B):\n    def foo(self, a=A()): ...\n\nreveal_type(C.foo)  # N: Revealed type is \"def (self: __main__.C, a: object =) -> None\"\n\n\n[case testDontInferFunctionTypes]\n# flags: --no-infer-function-types --allow-untyped-defs --allow-incomplete-defs --allow-any-expr --no-default-return\n\ndef f(): ...\nreveal_type(f)  # N: Revealed type is \"def () -> Untyped\"\n\ndef g(i=1, b=\"\"): ...\nreveal_type(g)  # N: Revealed type is \"def (i: Untyped =, b: Untyped =) -> Untyped\"\n\nclass A1:\n    def __new__(cls): ...\n    def __init__(self): ...\nclass B1(A1):\n    def __new__(cls): ...\n    def __init__(self): ...\n\nreveal_type(A1.__new__)  # N: Revealed type is \"def (cls: type[__main__.A1]) -> Untyped\"\nreveal_type(B1.__new__)  # N: Revealed type is \"def (cls: type[__main__.B1]) -> Untyped\"\nreveal_type(A1.__init__)  # N: Revealed type is \"def (self: __main__.A1) -> Untyped\"\nreveal_type(B1.__init__)  # N: Revealed type is \"def (self: __main__.B1) -> Untyped\"\n\nclass A2:\n    def __new__(cls, a: int): ...\n    def __init__(self, a: int): ...\nclass B2(A2):\n    def __new__(cls, a): ...\n    def __init__(self, a): ...\n\nreveal_type(A2.__new__)  # N: Revealed type is \"def (cls: type[__main__.A2], a: int) -> Untyped\"\nreveal_type(B2.__new__)  # N: Revealed type is \"def (cls: type[__main__.B2], a: Untyped) -> Untyped\"\nreveal_type(A2.__init__)  # N: Revealed type is \"def (self: __main__.A2, a: int) -> None\"\nreveal_type(B2.__init__)  # N: Revealed type is \"def (self: __main__.B2, a: Untyped) -> Untyped\"\n\n\n[case testSimpleOverload]\nfrom typing import overload\n\n@overload\ndef f(i: int) -> int: ...\n@overload\ndef f(i: str) -> str: ...\n\ndef f(i):\n    reveal_type(i)  # N: Revealed type is \"int | str\"\n    reveal_type(f)  # N: Revealed type is \"Overload(def (i: int) -> int, def (i: str) -> str)\"\n    if i:\n        return \"asdf\"\n    elif bool():\n        return 100\n    return None  # E: Incompatible return value type (got \"None\", expected \"int | str\")  [return-value]\n\n\n[case testPartialOverload]\nfrom typing import overload\n\n@overload\ndef f(*, i: int, j: int) -> int: ...\n@overload\ndef f(*, j: str) -> str: ...\n\ndef f(i: object = 1, j = \"1\"):\n    reveal_type(i)  # N: Revealed type is \"object\"\n    reveal_type(j)  # N: Revealed type is \"int | str\"\n    if j:\n        return \"asdf\"\n    elif i:\n        return 100\n    return None  # E: Incompatible return value type (got \"None\", expected \"int | str\")  [return-value]\n\n\n[case testInvalidOverload]\n@overload  # E: Name \"overload\" is not defined  [name-defined]\ndef a(x: int): ...\n@overload  # E: Name \"a\" already defined on line 1  [no-redef] \\\n           # E: Name \"overload\" is not defined  [name-defined]\ndef a(x: str): ...\ndef a(x: object): ...  # E: Name \"a\" already defined on line 1  [no-redef]\n\ndef b(): ...\ndef b(x: str): ...  # E: Name \"b\" already defined on line 7  [no-redef]\n\n\n[case testOverloadAndDefault]\nfrom typing import overload\n\n@overload\ndef foo(a: int) -> None:\n    ...\n@overload\ndef foo(a='1') -> None:\n    ...\ndef foo(a=\"1\") -> None:\n    reveal_type(a)  # N: Revealed type is \"int | str\"\n\nreveal_type(foo)  # N: Revealed type is \"Overload(def (a: int) -> None, def (a: str =) -> None)\"\n\n\n[case testOverloadMixedPositionalKeyword]\nfrom typing import overload\n\n@overload\ndef f(a: int, *, b: str): ...\n@overload\ndef f(z: int, /, b: str): ...\n\ndef f(a, b):\n    reveal_type(a)\n    reveal_type(b)\n[out]\nmain:9: note: Revealed type is \"int\"\nmain:10: note: Revealed type is \"str\"\n\n\n[case testOverloadMixedPositional]\nfrom typing import overload\n\n@overload\ndef f(a: int, b: str): ...\n@overload\ndef f(z: str, /, b: str): ...\n\ndef f(a, b):\n    reveal_type(a)\n    reveal_type(b)\n[out]\nmain:9: note: Revealed type is \"int | str\"\nmain:10: note: Revealed type is \"str\"\n\n\n[case testOverloadPositionalDifferentPosition]\nfrom typing import overload\n\n@overload\ndef f(x: int, /, b: int): ...\n@overload\ndef f(y: str, z: str, /): ...\n\ndef f(a, b):\n    reveal_type(a)\n    reveal_type(b)\n[out]\nmain:9: note: Revealed type is \"int | str\"\nmain:10: note: Revealed type is \"int | str\"\n\n\n[case testVariadic]\n# flags: --allow-any-expr --disable-error-code truthy-bool --implicit-optional\nfrom typing import overload\n\n@overload\ndef f(__a: str): ...\n@overload\ndef f(__a: int): ...\n\ndef f(*args):  # E: Function is missing a type annotation for one or more arguments  [no-untyped-def]\n    reveal_type(args)  # N: Revealed type is \"tuple[Untyped, ...]\"\n    if args:\n        return \"asdf\"  # E: No return value expected  [return-value]\n[builtins fixtures/tuple.pyi]\n\n\n[case testKariadic]\n# flags: --allow-any-expr\nfrom typing import overload\n\n@overload\ndef f(*, kwargs: str): ...\n@overload\ndef f(*, kwargs: int): ...\n\ndef f(**kwargs):  # E: Function is missing a type annotation for one or more arguments  [no-untyped-def]\n    reveal_type(kwargs)  # N: Revealed type is \"dict[str, Untyped]\"\n    return 1 # E: No return value expected  [return-value]\n[builtins fixtures/dict.pyi]\n\n\n[case testInferOverloadWithPositionalOnly]\nfrom typing import overload\n\n@overload\ndef foo(a: int, /): ...\n@overload\ndef foo(a: str, /): ...\n\ndef foo(a):\n    reveal_type(a)\n\n@overload\ndef bar(x: int, /, b: str): ...\n@overload\ndef bar(y: None, /, b: ellipsis): ...\n\ndef bar(z, b):\n    reveal_type(z)\n    reveal_type(b)\n[out]\nmain:9: note: Revealed type is \"int | str\"\nmain:17: note: Revealed type is \"int | None\"\nmain:18: note: Revealed type is \"str | ellipsis\"\n\n[case testOverrideOverload-xfail]\n# this is turned off for now\nfrom typing import overload, Union\nfrom s import S\n\nclass A:\n    @overload\n    def f(self, f: int) -> str: ...\n    @overload\n    def f(self, f: str) -> int: ...\n    def f(self, f): ...\n\nclass B(A):\n    def f(self, f):\n        reveal_type(self)  # N: Revealed type is \"__main__.B\"\n        reveal_type(f)  # N: Revealed type is \"int | str\"\n        return None  # E: Incompatible return value type (got \"None\", expected \"str | int\")  [return-value]\nclass C(A):\n    def f(self, f: Union[int, str]):\n        reveal_type(self)  # N: Revealed type is \"__main__.C\"\n        reveal_type(f)  # N: Revealed type is \"int | str\"\n        return None  # E: Incompatible return value type (got \"None\", expected \"str | int\")  [return-value]\nclass D(A):\n    def f(self, f: str):  # E: Overloaded function implementation does not accept all possible arguments of signature 1  [misc]\n        reveal_type(self)  # N: Revealed type is \"__main__.D\"\n        reveal_type(f)  # N: Revealed type is \"str\"\n        return None  # E: Incompatible return value type (got \"None\", expected \"str | int\")  [return-value]\nclass E(A):\n    def f(self, f: str) -> None:  # E: Signature of \"f\" incompatible with supertype \"A\"  [override] \\\n                                  # N:      Superclass: \\\n                                  # N:          @overload \\\n                                  # N:          def f(self, f: int) -> str \\\n                                  # N:          @overload \\\n                                  # N:          def f(self, f: str) -> int \\\n                                  # N:      Subclass: \\\n                                  # N:          def f(self, f: str) -> None\n        reveal_type(self)  # N: Revealed type is \"__main__.E\"\n        reveal_type(f)  # N: Revealed type is \"str\"\n        return None\nclass F(A):\n    def f(self, f=\"\") -> Union[str, int]:\n        reveal_type(self)  # N: Revealed type is \"__main__.F\"\n        reveal_type(f)  # N: Revealed type is \"int | str\"\n        return None  # E: Incompatible return value type (got \"None\", expected \"str | int\")  [return-value]\nclass G(S):\n    def f(self, f=\"\"):\n        reveal_type(self)  # N: Revealed type is \"__main__.G\"\n        reveal_type(f)  # N: Revealed type is \"int | str\"\n        return None  # E: Incompatible return value type (got \"None\", expected \"str | int\")  [return-value]\n\n\nreveal_type(A.f)  # N: Revealed type is \"Overload(def (self: __main__.A, f: int) -> str, def (self: __main__.A, f: str) -> int)\"\nreveal_type(B.f)  # N: Revealed type is \"Overload(def (self: __main__.B, f: int) -> str, def (self: __main__.B, f: str) -> int)\"\nreveal_type(C.f)  # N: Revealed type is \"Overload(def (self: __main__.C, f: int) -> str, def (self: __main__.C, f: str) -> int)\"\nreveal_type(D.f)  # N: Revealed type is \"Overload(def (self: __main__.D, f: int) -> str, def (self: __main__.D, f: str) -> int)\"\nreveal_type(E.f)  # N: Revealed type is \"def (self: __main__.E, f: str) -> None\"\nreveal_type(F.f)  # N: Revealed type is \"Overload(def (self: __main__.F, f: int) -> str, def (self: __main__.F, f: str) -> int)\"\nreveal_type(G.f)  # N: Revealed type is \"Overload(def (self: __main__.G, f: int) -> str, def (self: __main__.G, f: str) -> int)\"\n\n[file s.pyi]\nfrom typing import overload\n\nclass S:\n    @overload\n    def f(self, f: int) -> str: ...\n    @overload\n    def f(self, f: str) -> int: ...\n\n\n[case testCheckUntypedDefs]\n# flags: --no-check-untyped-defs --allow-untyped-defs\n\ndef foo(a=1):\n    1 + \"\"\n\nfoo()  # E: Call to untyped function \"foo\" in typed context  [no-untyped-call]\nreveal_type(foo)  # E: Expression type contains \"Any\" (has type \"def (a: int=...) -> Untyped\")  [any] \\\n                  # E: Expression type contains \"Any\" (has type \"def (a: int=...) -> Untyped\")  [any] \\\n                  # N: Revealed type is \"def (a: int =) -> Untyped\"\n\ndef bar(a=1) -> None:\n    1 + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")  [operator]\n\nbar()\nreveal_type(bar)  # N: Revealed type is \"def (a: int =) -> None\"\n\n\n[case inferPropertyTypes]\n# flags: --no-infer-function-types --no-default-return --no-check-untyped-defs\nclass A:\n    @property\n    def f(self) -> int: ...\n    @f.setter\n    def f(self, value): ...\n    @f.deleter\n    def f(self): ...\n\na = A()\nreveal_type(a.f)  # N: Revealed type is \"int\"\na.f = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\ndel a.f\n\nclass B:\n    @property\n    def f(self): ...  # E: Function is missing a return type annotation  [no-untyped-def] \\\n                      # N: Use \"-> None\" if function does not return a value \\\n                      # E: Type of decorated function contains type \"Any\" (\"def (self: B) -> Untyped\")  [decorated-any]\n    @f.setter\n    def f(self, value):\n        1 + \"\"\n    @f.deleter\n    def f(self): ...\n\nb = B()\nreveal_type(b.f)  # E: Expression has type \"Untyped\"  [any] \\\n                  # E: Expression has type \"Untyped\"  [any] \\\n                  # N: Revealed type is \"Untyped\"\nb.f = 1  # E: Usage of untyped name \"f\" in typed context  [no-untyped-usage]\ndel b.f\n[builtins fixtures/property.pyi]\n\n\n[case testPropertyNoAnnotation]\nclass A:\n    @property\n    def p(self): ...  # E: Property is missing a type annotation  [no-untyped-def]\n    @p.setter\n    def p(self, value): ...\n    @p.deleter\n    def p(self): ...\n\na = A()\nreveal_type(a.p)  # N: Revealed type is \"None\"\na.p = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"None\")  [assignment]\ndel a.p\n[builtins fixtures/property.pyi]\n\n\n[case testPropertyInheritInfer-xfail]\n# Overloaded overrides aren't supported yet, so this is only the getter\n# xfail because infer function types has been disabled for now.\nclass A:\n    @property\n    def p(self) -> int: ...\nclass B(A):\n    @property\n    def p(self):\n        1 + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")  [operator]\n        return 1\n\nb = B()\nreveal_type(b.p)  # N: Revealed type is \"int\"\nc = b.p\n[builtins fixtures/property.pyi]\n\n\n[case testDefaultReturnOverride-xfail]\nclass A:\n    def foo(self) -> int: ...\n    def bar(self, i: int) -> int: ...\n\nclass B(A):\n    def foo(self): ...\n    def bar(self, i: int): ...\n\nb: B\nreveal_type(b.foo)  # N: Revealed type is \"def () -> int\"\nreveal_type(b.bar)  # N: Revealed type is \"def (i: int) -> int\"\n\n\n[case testUntypedInit]\n# flags: --allow-untyped-defs\nclass A:\n    def __init__(self, foo): ...\n\n\n[case testInferFromDefaultWhenDecorated]\nfrom helper import T\n\ndef deco(func: T) -> T: ...\n\n@deco\ndef b(b=True) -> None: ...\n\nreveal_type(b)  # N: Revealed type is \"def (b: bool =) -> None\"\n\n\n[case testInferFromDefaultNested]\ndef f1():\n    def f2(a=True): ...\n    reveal_type(f2)  # N: Revealed type is \"def (a: bool =) -> None\"\n\n\n[case testNotesAppearForInferredFunction]\n# flags: --show-error-context\ndef f(): ...  # N: \"f\" defined here\nf(x=1)  # E: Unexpected keyword argument \"x\" for \"f\"  [call-arg]\n\n\n[case testUnusedParamObject]\ndef f0(_: int):\n    reveal_type(_)  # N: Revealed type is \"int\"\nreveal_type(f0)  # N: Revealed type is \"def (_: int) -> None\"\ndef f1(_):\n    reveal_type(_)  # N: Revealed type is \"object\"\nreveal_type(f1)  # N: Revealed type is \"def (_: object) -> None\"\ndef f2(a: int, _):\n    reveal_type(a)  # N: Revealed type is \"int\"\n    reveal_type(_)  # N: Revealed type is \"object\"\nreveal_type(f2)  # N: Revealed type is \"def (a: int, _: object) -> None\"\ndef f3(*_):\n    reveal_type(_)  # N: Revealed type is \"tuple[object, ...]\"\nreveal_type(f3)  # N: Revealed type is \"def (*_: object) -> None\"\ndef f4(**_):\n    reveal_type(_)  # N: Revealed type is \"dict[str, object]\"\nreveal_type(f4)  # N: Revealed type is \"def (**_: object) -> None\"\ndef f5(_, __, ___):\n    reveal_type((_, __, ___))  # N: Revealed type is \"(object, object, object)\"\nreveal_type(f5)  # N: Revealed type is \"def (_: object, __: object, ___: object) -> None\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-intersection.test",
    "content": "[case testIntersection]\nfrom basedtyping import Intersection\ni: Intersection[int, str]\nreveal_type(i)  # N: Revealed type is \"int & str\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionSyntax]\nfrom __future__ import annotations\ni: int & str\nreveal_type(i)  # N: Revealed type is \"int & str\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testNoIntersectionSyntax]\ni: int & str  # E: `X & Y` syntax for intersections requires `from __future__ import annotations` or quoted types  [valid-type]\n\n\n[case testIntersectionAttribute]\nfrom __future__ import annotations\nclass A:\n    a: int\n\nclass B:\n    b: str\n\ni: A & B\nreveal_type(i.a)  # N: Revealed type is \"int\"\nreveal_type(i.b)  # N: Revealed type is \"str\"\nreveal_type(i.c)  # E: \"A & B\" has no attribute \"c\"  [attr-defined] \\\n                  # N: Revealed type is \"Any (from error)\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionAssignability]\n# flags: --disallow-redefinition\nfrom __future__ import annotations\nclass A: pass\nclass B: pass\nclass AB(A, B): pass\nclass D: pass\n\nab: AB\ncd: AB & D\nab_or_d: AB | D\nd: D\ni: A & B\ni = A()  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"A & B\")  [assignment]\nba: B & A = i\ni = ab\ni = d  # E: Incompatible types in assignment (expression has type \"D\", variable has type \"A & B\")  [assignment]\ni = ab_or_d  # E: Incompatible types in assignment (expression has type \"AB | D\", variable has type \"A & B\")  [assignment]\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionFromNarrowing]\nfrom __future__ import annotations\nclass A: pass\nclass B: pass\n\ni: A\nassert isinstance(i, B)\nreveal_type(i)  # N: Revealed type is \"__main__.A & __main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionWithBothCallable]\nfrom __future__ import annotations\nfrom typing import Callable\nclass A:\n    def __call__(self, a: int): ...\nfoo: A & Callable[[], int]\nreveal_type(foo())  # N: Revealed type is \"int\"\nfoo(\"\")  # E: No overload variant of \"A & () -> int\" matches argument type \"str\"  [call-overload] \\\n         # N: Possible overload variants: \\\n         # N:     _NamedCallable & __call__(self, a: int) -> None \\\n         # N:     () -> int\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionOneCallable]\nfrom __future__ import annotations\nfrom typing import Callable\nclass A:\n    pass\nfoo: A & Callable[[], int]\nreveal_type(foo())  # N: Revealed type is \"int\"\nfoo(\"\")  # E: No overload variant of \"A & () -> int\" matches argument type \"str\"  [call-overload] \\\n         # N: Possible overload variant: \\\n         # N:     () -> int\n[builtins fixtures/tuple.pyi]\n\n\n[case testIndexable]\nfrom __future__ import annotations\n\nclass A:\n    def __getitem__(self, item: str): ...\na: list[str] & A\na[0]\na[\"i\"]\na[None]  # E: No overload variant of \"_NamedCallable & (int) -> str & _NamedCallable & (str) -> None\" matches argument type \"None\"  [call-overload] \\\n         # N: Possible overload variants: \\\n         # N:     _NamedCallable & __getitem__(self, int, /) -> str \\\n         # N:     _NamedCallable & __getitem__(self, str, /) -> None\n[builtins fixtures/list.pyi]\n\n\n[case testMultipleNarrowedIntersection-xfail]\nfrom __future__ import annotations\nclass A: pass\nclass B: pass\nclass C: pass\n\nx: A\nreveal_type(x)  # N: Revealed type is \"__main__.A\"\nassert isinstance(x, B)\nreveal_type(x)  # N: Revealed type is \"__main__.A & __main__.B\"\nassert isinstance(x, C)\nreveal_type(x)  # N: Revealed type is \"__main__.A & __main__.B & __main__.C\"\n\ny: (A & B) | (A & C)\nassert isinstance(y, C)\nreveal_type(y)  # N: Revealed type is \"__main__.A & __main__.B & __main__.C | __main__.A & __main__.C\"\n[builtins fixtures/tuple.pyi]\n\n\n-- This is not implemented yet, maybe next sprint\n[case testInvalidIntersection-xfail]\nfrom __future__ import annotations\n\na: int & str  # E: Intersection of \"int & str\" cannot exist: would have incompatible method signatures  [unreachable]\na: 1 & 2  # E: Intersection of \"1 & 2\" cannot exist: would have incompatible method signatures  [unreachable]\n\n\n[case testIntersectionWithAny]\n# flags: --allow-any-expr --allow-any-explicit --disallow-redefinition\nfrom __future__ import annotations\n\nfrom typing import Any\n\na: Any & str\nreveal_type(a)  # N: Revealed type is \"Any & str\"\na = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Any & str\")  [assignment]\na = \"\"\n\nb: Any\nassert isinstance(b, str)\nreveal_type(b)  # N: Revealed type is \"str\" (narrowed from \"Any\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testOverrideInIntersection]\nfrom __future__ import annotations\n\nclass A:\n    def foo(self) -> int:\n        return True\nclass B(A):\n    def foo(self) -> bool:\n        return True\n\nb: A & B\nreveal_type(b.foo())  # N: Revealed type is \"bool\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testOverloaded]\nfrom __future__ import annotations\nfrom typing import overload\nclass A:\n    @overload\n    def foo(self): ...\n    @overload\n    def foo(self, x: int): ...\n    def foo(self, x=1): ...\nclass B:\n    def foo(self, x: str): ...\n\nx: A & B\nx.foo(None)  # E: No overload variant of \"foo\" of \"__main__.A & __main__.B\" matches argument type \"None\"  [call-overload] \\\n             # N: Possible overload variants: \\\n             # N:     foo(self) -> None \\\n             # N:     foo(self, x: int) -> None \\\n             # N:     _NamedCallable & foo(self, x: str) -> None\n[builtins fixtures/tuple.pyi]\n\n\n[case testGenericFunction]\nfrom __future__ import annotations\n\nfrom typing import TypeVar\n\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef foo(x: T, y: U) -> T & U: pass\na: int\nb: object\nreveal_type(foo(a, b))  # N: Revealed type is \"int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionInferenceWithTypeVarValues]\nfrom __future__ import annotations\nfrom typing import TypeVar\nAnyStr = TypeVar('AnyStr', bytes, str)\nclass A: pass\nstrA: str & A\ndef f(x: AnyStr & A, *a: AnyStr): pass\nf(strA)\nf(strA, 'bar')\nf(strA, b'bar')  # E: Value of type variable \"AnyStr\" of \"f\" cannot be \"str | bytes\"  [type-var] \\\n                 # N: \"AnyStr\" of \"f\" is a constrained type variable, it is not generic\n[builtins fixtures/tuple.pyi]\n\n-- what's going on here?\n[case testIntersectionTwoPassInference-xfail]\nfrom __future__ import annotations\nfrom typing import TypeVar\nT = TypeVar('T')\nU = TypeVar('U')\ndef j(x: 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/tuple.pyi]\n\n\n[case testIntersectionContext]\nfrom __future__ import annotations\n\nfrom typing import TypeVar\n\nclass A: pass\nclass B: pass\n\nT = TypeVar('T')\ndef f() -> list[T]: pass\nd1: list[int] & A = f()  # E: Incompatible types in assignment (expression has type \"list[int]\", variable has type \"list[int] & A\")  [assignment]\nd2: A & B = f() # E: Incompatible types in assignment (expression has type \"list[Never]\", variable has type \"A & B\")  [assignment]\n[builtins fixtures/tuple.pyi]\n\n\n[case testGenericFunctionSubtypingWithIntersections]\n# flags: --disallow-redefinition\nfrom __future__ import annotations\nfrom typing import TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\ndef k1(x: int, y: list[T]) -> list[T & int]: pass\ndef k2(x: S, y: list[T]) -> list[T & int]: pass\na = k2\na = k1 # E: Incompatible types in assignment (expression has type \"def [T] (x: int, y: list[T]) -> list[T & int]\", variable has type \"def [S, T] (x: S, y: list[T]) -> list[T & int]\")  [assignment]\nb = k1\nb = k2\n[builtins fixtures/list.pyi]\n\n\n[case testEqual-xfail]\n# flags: --disallow-redefinition\nfrom __future__ import annotations\nfrom typing import Generic\n\nT = TypeVar(\"T\")\nclass A: pass\nclass B: pass\nclass G(Generic[T]): pass\n\nl1: G[A] & G[B]\nl2: G[A & B]\n\nl1 = l2\nl2 = l1\n[builtins fixtures/tuple.pyi]\n\n\n[case testOverloadIsIntersection-xfail]\n# flags: --disallow-redefinition\nfrom __future__ import annotations\nfrom typing import overload\n\n@overload\ndef _foo(x: int) -> str: ...\n@overload\ndef _foo(x: str) -> int: ...\ndef _foo(x): return x\n\nfoo = _foo\nbar: Callable[[int], str] & Callable[[int], int]\n\nbar = foo\nfoo = bar\n[builtins fixtures/tuple.pyi]\n\n\n[case testNarrowDoesntAddAny]\nfrom __future__ import annotations\nx: list[int]\nassert isinstance(x, list)\nreveal_type(x)  # N: Revealed type is \"list[int]\"\n[builtins fixtures/tuple.pyi]\n\n\n\n[case testTypeAttributeAccess]\nfrom __future__ import annotations\n\nclass A:\n    a: int\nclass B:\n    pass\n\nx: A & B\nreveal_type(x.a)  # N: Revealed type is \"int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testComplexNarrow-xfail]\nfrom __future__ import annotations\nfrom typing import Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nx: A\nreveal_type(x)  # N: Revealed type is \"__main__.A\"\nassert isinstance(x, Union[B, C])\nreveal_type(x)  # N: Revealed type is \"__main__.A & __main__.B\"\nassert isinstance(x, C)\nreveal_type(x)  # N: Revealed type is \"__main__.A & __main__.B & __main__.C | __main__.A & __main__.C\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testIntersectionAlias]\nfrom basedtyping import Intersection\nA = Intersection[int, str]\na: A\n\n\n[case testTypeApplication]\nimport types\nfrom typing import Generic, TypeVar, List\nT = TypeVar(\"T\")\nList[int & str]  # E: `X & Y` syntax for intersections requires `from __future__ import annotations` or quoted types  [valid-type]\nList[int | str]  # E: `X | Y` syntax for unions requires Python 3.10 or above  [valid-type]\na: List[int & str]  # E: `X & Y` syntax for intersections requires `from __future__ import annotations` or quoted types  [valid-type]\nb: List[int | str]  # E: `X | Y` syntax for unions requires Python 3.10 or above  [valid-type]\ndef f():\n    a: List[int & str]\n    b: List[int & str]\n\nimport future\n[file future.py]\nfrom __future__ import annotations\nfrom typing import Generic, TypeVar, List\nT = TypeVar(\"T\")\nList[int & str]  # E: `X & Y` syntax for intersections requires `from __future__ import annotations` or quoted types  [valid-type]\nList[int | str]  # E: `X | Y` syntax for unions requires Python 3.10 or above  [valid-type]\na: List[int & str]\nb: List[int & str]\ndef f():\n    a: List[int & str]\n    b: List[int & str]\nList[1 >> 2]  # E: Type expected within [...]  [misc] \\\n              # E: Unsupported left operand type for >> (\"int\")  [operator]\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-misc.test",
    "content": "[case testXDefinedHere]\n# mypy: show-error-context\nimport a\ndef f(): ...  # N: \"f\" defined here\nf(a=1)  # E: Unexpected keyword argument \"a\" for \"f\"  [call-arg]\n[file a.py]\ndef f(): ...\nf(a=1)  # E: Unexpected keyword argument \"a\" for \"f\"  [call-arg]\n\n\n[case testIgnoreOnReveal]\nfrom typing import Any\n\na: Any = 1  # E: Explicit \"Any\" is not allowed  [explicit-any]\nreveal_type(a)  # type: ignore[any]  # N: Revealed type is \"Any\"\n\n\n[case testFakeColumn]\n# flags: --show-error-end\nif bool():  # type: ignore[truthy-bool]\n    1  # type: ignore[operator]\n[out]\nmain:3:5:3:31: error: Unused \"type: ignore\" comment  [unused-ignore]\n\n\n[case testNarrowOnInitialAssignment]\na: object = 1\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\n\n[case testNarrowWithAny]\n# mypy: allow-any-explicit, allow-any-expr\nfrom typing import Any, Union\n\na: Union[int, Any]\nif bool():\n    a = 1\n    reveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"int | Any\")\nb: Any = 1\nreveal_type(b)  # N: Revealed type is \"Any\"\nc: Any\nc = 1\nreveal_type(c)  # N: Revealed type is \"Any\"\n\n\n[case testNarrowWithTuple]\n# mypy: disallow-redefinition\nfrom typing import Tuple, TypeVar\nT = TypeVar('T')\n\ndef f(x: T) -> Tuple[T, T]: ...\nx = None\nreveal_type(x) # N: Revealed type is \"None\" (narrowed from \"partially defined: ? | None\")\nx, *_ = f('')\nreveal_type(x) # N: Revealed type is \"str\" (narrowed from \"str | None\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testNarrowWithFinal]\n# mypy: allow-any-expr, allow-any-explicit\nfrom __future__ import annotations\nfrom typing import Final, Any\n\none: 1\na1: Final[object] = 1\nreveal_type(a1)  # N: Revealed type is \"1\"\nb1: Final[object] = True\nreveal_type(a1)  # N: Revealed type is \"1\"\nreveal_type(b1)  # N: Revealed type is \"True\"\nb2: Final[object] = one\nreveal_type(b2)  # N: Revealed type is \"1\"\n\nany: Any\nlist_any: list[Any]\n\nc: list[int] = list_any\nd: Final[list[object]] = list_any\ne: Final[list[int]] = list_any\n\n# make sure they don't become Any\nreveal_type(c)  # N: Revealed type is \"list[int]\"\nreveal_type(d)  # N: Revealed type is \"list[object]\"\nreveal_type(e)  # N: Revealed type is \"list[int]\"\n\nclass C: ...\nclass A:\n    a1: Final[object] = C()\n    b1: Final[int] = 1\n    c1: Final[list[object]] = list_any\n    def __init__(self):\n        self.a2: Final[object] = C()\n        self.b2: Final[int] = 1\n        self.c2: Final[list[object]] = list_any\na: Final[object] = A()\nreveal_type(a)  # N: Revealed type is \"__main__.A\" (narrowed from \"object\")\nreveal_type(a.a1)  # N: Revealed type is \"__main__.C\"\nreveal_type(a.a2)  # N: Revealed type is \"__main__.C\"\nreveal_type(a.b1)  # N: Revealed type is \"1\"\nreveal_type(a.b2)  # N: Revealed type is \"1\"\nreveal_type(a.c1)  # N: Revealed type is \"list[object]\"\nreveal_type(a.c2)  # N: Revealed type is \"list[object]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testFunctionAnnotations]\n# flags: --python-version=3.8\nfrom typing import List\ndef f():\n    a: list[int]\n    class A:\n        a: list[int]  # E: \"list\" is not subscriptable, use \"typing.List\" instead  [misc]\n        b: List[int]\n        def f(self):\n            a: list[int]\n            b: List[int]\n    def f(a: list[int], b: List[int]):  # E: \"list\" is not subscriptable, use \"typing.List\" instead  [misc]\n        ...\n[file main.pyi]\nfrom typing import List\ndef f():\n    a: list[int]\n    class A:\n        a: list[int]\n        b: List[int]\n        def f(self):\n            a: list[int]\n            b: List[int]\n    def f(a: list[int], b: List[int]): ...\n\n[case testCastAtRuntime]\n# flags: --python-version=3.8\nfrom typing import cast, List\ncast(list[int], [])  # E: \"list\" is not subscriptable, use \"typing.List\" instead  [misc]\ncast(\"list[int]\", [])\ncast(List[int], [])\n\n\n[case testCastAtRuntimeFuture]\n# flags: --python-version=3.8\nfrom __future__ import annotations\nfrom typing import cast, List\ncast(list[int], [])  # E: \"list\" is not subscriptable, use \"typing.List\" instead  [misc]\ncast(\"list[int]\", [])\ncast(List[int], [])\n[builtins fixtures/tuple.pyi]\n\n\n[case testBasedTypesInFunction]\ndef f():\n    a: 1 | 2\n    b: int & str\n    c: (int, str)\n    d: True | False\n    def guard(x: object) -> x is int:  # E: You need to put quotes around the entire type-guard, or enable `__future__.annotations`  [misc]\n        ...\n[builtins fixtures/tuple.pyi]\n\n\n[case testUsingDecoratedNone]\nfrom typing import TypeVar, Callable\nT = TypeVar(\"T\")\ndef deco(t: T) -> T: ...\n@deco\ndef f1(): ...\n\na = f1()  # E: \"f1\" does not return a value (it only ever returns None)  [func-returns-value]\n\ndef becomes_none(f: object) -> Callable[[], None]: ...\n\n@becomes_none\ndef f2() -> object: ...\n\na = f2()  # E: \"f2\" does not return a value (it only ever returns None)  [func-returns-value]\ndef becomes_object(f: object) -> Callable[[], object]: ...\n\n@becomes_object\ndef f3(): ...\n\na = f3()\n\n\n[case testDoubleAlwaysTrue]\n# testing that it doesn't become \"True\" after a condition\n# mypy: always-true=a\na = False\n\nif a:\n    b = 1\nif a:\n    b = 1\n\n\n[case testAlwaysTrueDoesntNarrow]\n# testing that it doesn't become \"True\" after a condition\n#  but that narrowings in the body do\n# mypy: always-true=a\na = False\n\nb: object\nif a:\n    b = 1\nreveal_type(b)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\n\n[case testRedundantExprOnWhileTrue]\n\n\n[case testWorkNotProperlyFunctionNamesModule]\n# flags: --config-file tmp/pyproject.toml\nimport other\n\nclass A:\n    def f(self, a: int): ...\nclass B(A):\n    def f(self, b: int): ...  # E: Signature of \"f\" incompatible with supertype \"A\"  [override] \\\n                              # N:      Superclass: \\\n                              # N:          f(self, a: int) -> None \\\n                              # N:      Subclass: \\\n                              # N:          f(self, b: int) -> None \\\n                              # E: Method \"f\" is not using @override but is overriding a method in class \"__main__.A\"  [explicit-override]\n\n[file other.py]\nclass A:\n    def f(self, a: int): ...\nclass B(A):\n    def f(self, b: int): ...  # E: Method \"f\" is not using @override but is overriding a method in class \"other.A\"  [explicit-override]\n\n[file pyproject.toml]\n\\[[tool.mypy.overrides]]\nmodule=\"other\"\nwork_not_properly_function_names=true\n\n\n[case testErasedSelfType]\n\nclass A:\n    def f(self: B):\n        reveal_type(self) # N: Revealed type is \"__main__.B\"\nclass B(A): ...\nA().f()  # E: Invalid self argument \"A\" to attribute function \"f\" with type \"def (self: B) -> None\"  [misc]\nB().f()  # no error\n"
  },
  {
    "path": "test-data/unit/check-based-none.test",
    "content": "[case testNoneTypeIsNone]\nfrom typing import Type\nfrom typing_extensions import TypeAlias\n\n# should be the same as types.pyi\nNoneType: TypeAlias = type(None)\n\nreveal_type(NoneType) # N: Revealed type is \"type[None]\"\nn1: NoneType = None\nn2: Type[NoneType] = NoneType\nn3: Type[NoneType] = type(None)\nn4: Type[None] = NoneType\nn5: Type[None] = type(None)\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-overload.test",
    "content": "[case testAnyOverloadMatch]\nfrom typing import overload, Any, Callable\n\n@overload\ndef f(fn: Callable[[], bool]) -> str: ...\n@overload\ndef f(fn: Callable[[], None]) -> int: ...\ndef f(fn: object = 1) -> object: ...\n\ndef n(x: object) -> None: ...\na: Any  # type: ignore[explicit-any]\nx = f(lambda:\n      n(a))  # E: Expression has type \"Any\"  [any]\nreveal_type(x)  # N: Revealed type is \"int\"\n\n\n\n[case testAnyExprInHigherOrderOverload]\nfrom typing import Any, Callable, overload\n\n@overload\ndef f(fn: Callable[[int], object]) -> None: ...\n@overload\ndef f(fn: object=...) -> None: ...\n\ndef f(fn: object=1) -> None: ...\n\n# don't reveal erroneous Any\nf(lambda x: reveal_type(x))  # N: Revealed type is \"int\"\n\n# do reveal real Any\na: Any  # type: ignore[explicit-any]\ndef noop(x: object) -> None: ...\nf(lambda x: noop(a))  # E: Expression has type \"Any\"  [any]\nf(a)  # E: Expression has type \"Any\"  [any]\n\n# don't reveal narrowed type\no: object\nassert isinstance(o, str)\nf(lambda _: reveal_type(o))  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPositional]\nfrom typing import overload\n\n@overload\ndef f(a: int, b: int): ...\n@overload\ndef f(a: int, c: str, /): ...\ndef f(a, b):\n    reveal_type(a)  # N: Revealed type is \"int\"\n    reveal_type(b)  # N: Revealed type is \"int | str\"\n\n\n[case testInferDefault]\nfrom typing import overload\n\n@overload\ndef f(a: int, b: int, c: 1): ...\n@overload\ndef f(a: int, b: str, c: 2): ...\ndef f(a=\"who\", b=None, c=3):\n    reveal_type(a)  # N: Revealed type is \"int | 'who'\"\n    reveal_type(b)  # N: Revealed type is \"int | str | None\"\n    reveal_type(c)  # N: Revealed type is \"1 | 2 | 3\"\n"
  },
  {
    "path": "test-data/unit/check-based-python313.test",
    "content": "[case testTypeVarDefault]\n# this will probable be fixed upstream\nclass A[T=None]: pass\n\nreveal_type(A)  # N: Revealed type is \"[T = None] () -> __main__.A[T = None]\"\n"
  },
  {
    "path": "test-data/unit/check-based-tuple-literal.test",
    "content": "[case testTupleLiteralType]\nfrom __future__ import annotations\n\na: (1, str) = (1, \"\")\nreveal_type(a)  # N: Revealed type is \"(1, str)\"\nb: (str,) = (\"sus\",)\nreveal_type(b)  # N: Revealed type is \"(str,)\"\nc: () = (1,)  # E: Incompatible types in assignment (expression has type \"(int,)\", variable has type \"()\")  [assignment]\nreveal_type(c)  # N: Revealed type is \"()\"\n\ndef f1() -> (int, str):\n    return 1, \"\"\nreveal_type(f1) # N: Revealed type is \"def () -> (int, str)\"\n\ndef f2() -> (str,):\n    return \"sus\",\nreveal_type(f2) # N: Revealed type is \"def () -> (str,)\"\n\ndef f3() -> ():\n    return 1,  # E: Incompatible return value type (got \"(int,)\", expected \"()\")  [return-value]\nreveal_type(f3) # N: Revealed type is \"def () -> ()\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testInvalidVariadic]\nfrom __future__ import annotations\n\na: (1, ...) = (1, ...)   # E: Unexpected \"...\"  [misc]\nb: (1, ...) = (1, 1)   # E: Unexpected \"...\"  [misc]\n[builtins fixtures/tuple.pyi]\n\n\n[case testInvalidUsage]\n# flags: --allow-any-explicit --allow-any-expr\nfrom typing import TypeVar\nfrom typing_extensions import TypeAlias\n\nA = TypeVar(\"A\", bound=(int, str))  # E: \"int\" not callable  [operator] \\\n                                    # E: TypeVar \"bound\" must be a type  [misc]\nB: TypeAlias = (int, str)  # E: Invalid type alias: expression is not a valid type  [valid-type]\n[builtins fixtures/tuple.pyi]\n\n\n[case testInvalidSyntax]\na: int, str = 1, \"\"  # E: invalid syntax  [syntax]\n[builtins fixtures/tuple.pyi]\n\n\n[case testTupleLiteralInOperation]\n# flags: --python-version 3.12\na: (int, str) | int  # E: \"(int, str)\" is a bare literal and shouldn't be used in a type operation without \"__future__.annotations\"  [valid-type]\n[builtins fixtures/tuple.pyi]\n\n\n[case testTupleLiteralInOperationFuture]\nfrom __future__ import annotations\na: (int, str) | int\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-type-check-only.test",
    "content": "[case testSimple]\nfrom typing import type_check_only  # E: Symbol \"type_check_only\" is not accessible at runtime  [type-check-only]\n\nfrom a import a, A  # E: Symbol \"a\" is not accessible at runtime  [type-check-only] \\\n                    # E: Symbol \"A\" is not accessible at runtime  [type-check-only]\na  # E: Symbol \"a\" is not accessible at runtime  [type-check-only]\nA  # E: Symbol \"A\" is not accessible at runtime  [type-check-only]\nb: A  # E: Symbol \"A\" is not accessible at runtime  [type-check-only]\n\nimport f\n[file f.py]\nfrom __future__ import annotations\n\nfrom a import a, A  # E: Symbol \"a\" is not accessible at runtime  [type-check-only] \\\n                    # E: Symbol \"A\" is not accessible at runtime  [type-check-only]\na  # E: Symbol \"a\" is not accessible at runtime  [type-check-only]\nA  # E: Symbol \"A\" is not accessible at runtime  [type-check-only]\nb: A\n\n[file a.pyi]\nfrom typing import type_check_only\n\n@type_check_only\ndef a(): ...\na\n\n@type_check_only\nclass A: pass\n\nA\nb: A\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testTypeImport]\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from typing import type_check_only\n\n    @type_check_only\n    def f():\n        ...\nf()  # E: Symbol \"f\" is not accessible at runtime  [type-check-only]\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-type-render.test",
    "content": "[case testGenericMethod]\nfrom typing import TypeVar, Generic, Union\n\nT = TypeVar('T', bound=str)\nT2 = TypeVar('T2', bound=int)\n\nclass A(Generic[T2]):\n    def f(self, t: T, t2: T2) -> Union[T, T2]:\n        reveal_type(t)  # N: Revealed type is \"T@f\"\n        reveal_type(t2)  # N: Revealed type is \"T2@A\"\n        if bool():\n            t = t2  # E: Incompatible types in assignment (expression has type \"T2@A\", variable has type \"T@f\")  [assignment]\n        return t\n\nreveal_type(A.f)  # N: Revealed type is \"def [T2 (from A): int, T: str] (self: __main__.A[T2], t: T, t2: T2) -> T | T2\"\nreveal_type(A[int]().f)  # N: Revealed type is \"_NamedCallable & [T: str] (t: T, t2: int) -> T | int\"\nA.f = 1  # E: Cannot assign to a method  [method-assign] \\\n         # E: Incompatible types in assignment (expression has type \"int\", variable has type \"def [T2 (from A): int, T: str] (self: A[T2], t: T, t2: T2) -> T | T2\")  [assignment]\n\n\n[case testGenericFunction]\nfrom typing import TypeVar\nT = TypeVar(\"T\", bound=int)\n\ndef foo(t: T) -> T: ...\nreveal_type(foo)  # N: Revealed type is \"def [T: int] (t: T) -> T\"\nfoo = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"def [T: int] (t: T) -> T\")  [assignment]\n\n\n[case testRenderAny]\n# flags: --allow-any-generics --allow-any-expr --allow-any-explicit\nfrom typing import Any, List\na: list\nreveal_type(a)  # N: Revealed type is \"list[Untyped]\"\nb: List[Any]\nreveal_type(b)  # N: Revealed type is \"list[Any]\"\n\n\n[case testRenderBareLiterals]\n# flags: --python-version 3.10\nfrom typing import Literal\n\na: Literal['1'] = 2  # E: Incompatible types in assignment (expression has type \"2\", variable has type \"'1'\")  [assignment]\nreveal_type(a)  # N: Revealed type is \"'1'\"\nb: Literal[1, 2, 3] = 4  # E: Incompatible types in assignment (expression has type \"4\", variable has type \"1 | 2 | 3\")  [assignment]\nreveal_type(b)  # N: Revealed type is \"1 | 2 | 3\"\nc: Literal[1, 2, 3] | str = 4  # E: Incompatible types in assignment (expression has type \"4\", variable has type \"1 | 2 | 3 | str\")  [assignment]\nreveal_type(c)  # N: Revealed type is \"1 | 2 | 3 | str\"\n[typing fixtures/typing-medium.pyi]\n\n\n[case testRenderInferredLiteral]\nreveal_type(1)  # N: Revealed type is \"1\"\n\n\n[case testRenderGenericUpperBound]\nfrom typing import TypeVar\nT = TypeVar(\"T\", bound=int)\n\ndef foo(t: T): ...\nreveal_type(foo)  # N: Revealed type is \"def [T: int] (t: T) -> None\"\n\n\n[case testInferredNever]\na: int = []  # E: Incompatible types in assignment (expression has type \"list[Never]\", variable has type \"int\")  [assignment]\nreveal_type([])  # N: Revealed type is \"list[Never]\"\n\n\n[case testNoReturnAsNever]\nfrom typing import NoReturn\na: NoReturn = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Never\")  [assignment]\ndef b() -> NoReturn: ...\nreveal_type(a)  # N: Revealed type is \"Never\"\nreveal_type(b)  # N: Revealed type is \"def () -> Never\"\nb = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"def () -> Never\")  [assignment]\n\n\n[case testRenderNoneReturn]\ndef foo(): ...\nreveal_type(foo)  # N: Revealed type is \"def () -> None\"\nfoo = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"def () -> None\")  [assignment]\n\n\n[case testRenderErrorStar]\nfrom typing import Callable, ParamSpec\n\nP = ParamSpec(\"P\")\n\ndef f(fn: Callable[P, None]): ...\nf(1)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"(*Never, **Never) -> None\"  [arg-type]\ndef f2(*args: int, **kwargs: str): ...\na = f2\na = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"def (*args: int, **kwargs: str) -> None\")  [assignment]\n[builtins fixtures/tuple.pyi]\n\n\n[case testNarrowedFrom]\na: object\na = 1\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\n\n[case testNarrowedFromClass]\n# XFAIL\nclass A:\n    a: object\nclass B(A):\n    a: int\na: A\na = B()\nreveal_type(a.a)  # N: Revealed type is \"int\"\n# Actually expected N: Revealed type is \"int\" (narrowed from \"object\")\n\n\n[case testNarrowedFromPartial]\na = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")  [var-annotated]\nreveal_type(a)  # E: Expression type contains \"Any\" (has type \"list[Any (unannotated)]\")  [any] \\\n                # E: Expression type contains \"Any\" (has type \"list[Any (unannotated)]\")  [any] \\\n                # N: Revealed type is \"partially defined: list[?]\"\nb = None  # E: Need type annotation for \"b\" (hint: \"b: Optional[<type>] = ...\")  [var-annotated]\nreveal_type(b)  # N: Revealed type is \"None\" (narrowed from \"partially defined: ? | None\")\n"
  },
  {
    "path": "test-data/unit/check-based-typechecking.test",
    "content": "[case testBasedmypyTypeChecking]\nBASEDMYPY_TYPE_CHECKING = False\nif not BASEDMYPY_TYPE_CHECKING:\n    1 + \"\"\n\n\n[case testTypeChecking]\nfrom typing import TYPE_CHECKING\nfrom typing_extensions import TypeAlias\n\nif TYPE_CHECKING:\n    a: list[1 | 2]\n    class B: ...\n    b: B & int\n    c: (int, str) | int\n    def f(l: object) -> l is list[1 | 2]: ...\n    A: TypeAlias = list[1 | 2]\n    C = list[1 | 2]\n[builtins fixtures/tuple.pyi]\n\n\n[case testOverload]\nfrom typing import TYPE_CHECKING, overload\n\nif TYPE_CHECKING:\n    @overload\n    def f(): ...\n    @overload\n    def f(i: int): ...\n\n\n[case testStringType]\n# flags: --python-version 3.8\na: \"list[list[str]]\"\nb: \"int | str\"\nfrom typing import List\nc: List[\"list[str]\"]\nfrom types import FunctionType\nd: \"list[FunctionType[[], None]]\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-typeguard.test",
    "content": "[case testRetainGenericTypeGuard]\nfrom typing_extensions import TypeGuard\nfrom helper import T\ndef f(it: object) -> TypeGuard[int]: ...\ndef r(t: T) -> T: ...\n\na: object\nf2 = r(f)\nassert f2(a)\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\nb: object\nassert (lambda x: (lambda y: r(f)(y))(x))(b)\nreveal_type(b)  # N: Revealed type is \"int\" (narrowed from \"object\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testIIFETypeGuard]\nfrom typing_extensions import TypeGuard\ndef f(it: object) -> TypeGuard[int]: ...\n\na: object\nassert (lambda: f(a))()\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testSubtype]\nfrom typing_extensions import TypeGuard\nfrom typing import Callable\ndef takes_typeguard(x: Callable[[object], TypeGuard[int]]): ...\ndef typeguard1(x: object) -> \"x is int\": ...\ndef typeguard2(x: object, y: object) -> \"y is int\": ...\n\ntakes_typeguard(typeguard1)\ntakes_typeguard(typeguard2)  # E: Argument 1 to \"takes_typeguard\" has incompatible type \"def (x: object, y: object) -> y is int\"; expected \"(object) -> first argument is int\"  [arg-type]\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypeguardLambdaTargetMapping]\ndef guard(x: object) -> \"x is int\": ...\n\no: object\no2: object\nif (lambda y: guard(y))(o):\n    reveal_type(o)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\nif (lambda _, y: guard(y))(1, o):\n    reveal_type(o)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\nif (lambda _, y: guard(x=y))(1, o):\n    reveal_type(o)  # N: Revealed type is \"int\" (narrowed from \"object\")\n\nif (lambda _, y: guard(y))(o, o2):\n    reveal_type(o)  # N: Revealed type is \"object\"\n\nclass A:\n    def guard(self) -> \"self is B\": ...\nclass B(A): ...\na: A\nassert (lambda x: x.guard())(a)\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypeguardSubtype]\ndef guard(x: int) -> \"x is str\":  # E: A type-guard's type must be assignable to its parameter's type. (guard has type \"str\", parameter has type \"int\")  [typeguard-subtype] \\\n                                  # N: If this is correct, try making it an intersection with the parameter type\n    ...\n\n\n[case testOtherArg]\ndef guard(x: object, y: object) -> \"y is int\": ...\n\na: object\nb: object\n\nif guard(a, b):\n    reveal_type((a, b))  # N: Revealed type is \"(object, int)\"\n\nif guard(x=a, y=b):\n    reveal_type((a, b))  # N: Revealed type is \"(object, int)\"\n\nif guard(y=a, x=b):\n    reveal_type((a, b))  # N: Revealed type is \"(int, object)\"\n\nif guard(y=b, x=a):\n    reveal_type((a, b))  # N: Revealed type is \"(object, int)\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testUnsupportedDoubleGuardIIFE]\n# unsupported scenario\ndef guard(x: object) -> \"x is int\": return True\n\na: object\nb: object\n\nif (lambda x, y: guard(x) and guard(y))(a, b):\n    # both of these should be \"int\"\n    reveal_type((a, b))  # N: Revealed type is \"(object, object)\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testTargetDoesntExist]\ndef guard(x: object) -> \"y is int\": ...  # E: Cannot find parameter \"y\"  [name-defined]\n\n\n[case testInvalidType]\ndef guard(x: object) -> \"x is Sus\": ...  # E: Name \"Sus\" is not defined  [name-defined]\n\n\n[case testExplicitSelf]\nfrom typing_extensions import TypeGuard\n\nclass A:\n    def guard(self, x: object) -> TypeGuard[int]: ...\n\na: object\nassert A.guard(A(), a)\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testGuardSelf]\nclass A:\n    def guard(self) -> \"self is B\": ...\n\nclass B(A): ...\n\na: A\nassert a.guard()\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n\n\n[case testGuardCls]\nfrom typing import Type\nclass A:\n    @classmethod\n    def guard(cls) -> \"cls is Type[B]\": ...\n\nclass B(A): ...\n\na: Type[A]\nassert a.guard()\nreveal_type(a)  # N: Revealed type is \"type[__main__.B]\" (narrowed from \"type[__main__.A]\")\n[builtins fixtures/classmethod.pyi]\n\n\n[case testPositionalGuard]\ndef guard(x: object, /) -> \"x is int\": ...\n\na: object\nassert guard(a)\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\nreveal_type(guard)  # N: Revealed type is \"def (object) -> argument 1 is int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testUnquotedFuture]\nfrom __future__ import annotations\ndef guard(x: object) -> x is int: ...\na: object\nassert guard(a)\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testUnquotedPast]\ndef guard(x: object) -> x is int:  # E: You need to put quotes around the entire type-guard, or enable `__future__.annotations`  [misc]\n    ...\n[builtins fixtures/tuple.pyi]\n\n\n[case testCallableType]\nfrom typing import Callable\nfrom typing_extensions import TypeGuard\n\ndef make_guard() -> Callable[[object], TypeGuard[int]]: ...\n\na: object\nassert make_guard()()  # E: Too few arguments  [call-arg]\nassert make_guard()(a)\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testAssignmentExprSelf]\nclass A:\n    def g(self) -> \"self is B\": ...\nclass B(A): ...\n\nassert (a := A()).g()\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testUnsupportedAssignmentExprSelfCall]\n# unsupported scenario\nclass A:\n    def __call__(self) -> \"self is B\": ...\nclass B(A): ...\n\nassert (a := A())()\n# Actually expect \"__main__.B\"\nreveal_type(a)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testUnsupportedAssignmentExprCall]\n# unsupported scenario\nclass A:\n    def __call__(self, a: object) -> \"a is int\": ...\n\nb: object\nassert (a := A())(b)\n# Actually expect \"int\"\nreveal_type(b)  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testCallGuard]\nclass A:\n    def __call__(self) -> \"self is B\": ...\nclass B(A): ...\n\na: A\nassert a()\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testGuardSelfLambda]\n\nclass A:\n    def guard(self) -> \"self is B\": ...\n    def __call__(self) -> \"self is B\": ...\nclass B(A): ...\n\na: A\nif (lambda x: x.guard())(a):\n    reveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\nif (lambda x: x())(a):\n    reveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testGuardMemberSelf]\nclass A:\n    def guard(self) -> \"self is B\": ...\nclass B(A): ...\nclass AA:\n    a: A\na: AA\nassert a.a.guard()\nreveal_type(a.a)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPositionalSelf]\nclass A:\n    def guard(self, b: object=1, /) -> \"self is B\": ...\nclass B(A): ...\na: A\no: object\nassert a.guard(o)\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\nreveal_type(o)  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testGuardPositionalAssignment]\n# mypy: disallow-redefinition\nclass A:\n    def guard(self, b: object, /) -> \"self is B\": ...\nclass B(A): ...\n\ndef guard(a: object, /) -> \"a is B\": ...\n\nf1 = guard\nf1 = A().guard  # E: Incompatible types in assignment (expression has type \"_NamedCallable & (object) -> instance argument is B\", variable has type \"def (object) -> argument 1 is B\")  [assignment]\n\nf2 = A().guard\nf2 = guard\n[builtins fixtures/tuple.pyi]\n\n\n[case testLambdaMemberExprUnsupported]\n# TODO: This case is unsupported\nclass A:\n    def guard(self) -> \"self is B\": ...\nclass B(A): ...\nclass AA:\n    a: A\na: AA\nassert (lambda x: x.a.guard())(a)\nreveal_type(a)  # N: Revealed type is \"__main__.AA\"\n# Actual expected type is \"__main__.B\"\nreveal_type(a.a)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testClassmethodOnInstance]\nfrom typing import Type\nclass A:\n    @classmethod\n    def guard(cls) -> 'cls is Type[B]': ...\nclass B(A): ...\na: A\nassert a.guard()\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testClassmethodPositional]\nfrom typing import Type\nclass A:\n    @classmethod\n    def guard(cls, /) -> 'cls is Type[B]': ...\nclass B(A): ...\na: A\nassert a.guard()\nreveal_type(a)  # N: Revealed type is \"__main__.B\" (narrowed from \"__main__.A\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testGuardIsStringLiteral]\ndef guard(a: object) -> 'a is int': ...\n\na: object\nassert guard(a)\nreveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"object\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testEmptyTarget]\ndef guard(a: object) -> '\"\" is int':  # E: Invalid type comment or annotation  [valid-type]\n    ...\na: object\nassert guard(a)\nreveal_type(a)  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testNumericTarget]\ndef guard(a: object) -> '0 is int':  # E: Invalid type comment or annotation  [valid-type]\n    ...\na: object\nassert guard(a)\nreveal_type(a)  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testQuotedTarget]\ndef guard(a: object) -> '\"a\" is int':  # E: Invalid type comment or annotation  [valid-type]\n    ...\na: object\nassert guard(a)\nreveal_type(a)  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPositionalInstance]\n# TODO: This case is unsupported\nclass A:\n    def guard(self, b: object, /) -> 'b is int': ...\n\na: A\no: object\nif A.guard(a, o):  # E: type-guard on positional class function is unsupported  [typeguard-limitation]\n    reveal_type(a)  # N: Revealed type is \"__main__.A\"\n    # Actually expect \"int\"\n    reveal_type(o)  # N: Revealed type is \"object\"\nif a.guard(o):  # E: type-guard on positional class function is unsupported  [typeguard-limitation]\n    reveal_type(a)  # N: Revealed type is \"__main__.A\"\n    # Actually expect \"int\"\n    reveal_type(o)  # N: Revealed type is \"object\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPositionalInstanceType]\n# TODO: This case is unsupported\nclass A:\n    def guard(self, b: object, /) -> 'b is int': ...\n\n# Actually expect \"_NamedCallable & (object) -> argument 1 is int\"\nreveal_type(A().guard)  # N: Revealed type is \"_NamedCallable & (object) -> argument 2 is int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testNegativeGuard]\nfrom __future__ import annotations\n\ndef guard(x: object) -> x is int: ...\na: int | str\nif guard(a):\n    reveal_type(a)  # N: Revealed type is \"int\" (narrowed from \"int | str\")\nelse:\n    reveal_type(a)  # N: Revealed type is \"str\" (narrowed from \"int | str\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testNegativeGuardGeneric]\nfrom __future__ import annotations\n\ndef guard(x: object) -> x is list[int]: ...\na: list[int] | list[str]\nif guard(a):\n    reveal_type(a)  # N: Revealed type is \"list[int]\" (narrowed from \"list[int] | list[str]\")\nelse:\n    reveal_type(a)  # N: Revealed type is \"list[str]\" (narrowed from \"list[int] | list[str]\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypeGuardOnlyTrue]\nfrom __future__ import annotations\n\ndef guard(x: object) -> x is int:\n    return isinstance(x, int)\n\ndef guard_true(x: object) -> x is int if True else False:\n    return isinstance(x, int) and bool()\n\nx: int | str\nif guard(x):\n    reveal_type(x)  # N: Revealed type is \"int\" (narrowed from \"int | str\")\nelse:\n    reveal_type(x)  # N: Revealed type is \"str\" (narrowed from \"int | str\")\n\nif guard_true(x):\n    reveal_type(x)  # N: Revealed type is \"int\" (narrowed from \"int | str\")\nelse:\n    reveal_type(x)  # N: Revealed type is \"int | str\"\n\ny: int\nif guard(y):  # E: Condition is always true  [redundant-expr]\n    reveal_type(y)  # N: Revealed type is \"int\"\nelse:\n    reveal_type(y)  # E: Statement is unreachable  [unreachable]\n\nif guard_true(x):\n    reveal_type(y)  # N: Revealed type is \"int\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"int\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testAsymetricTypeGuardSubtype]\n# flags: --disallow-redefinition\nfrom __future__ import annotations\ndef f1(x: object) -> x is int: ...\ndef f2(x: object) -> x is int if True else False: ...\n\nx = f2\nx = f1\n\ny = f1\ny = f2  # E: Incompatible types in assignment (expression has type \"def (x: object) -> x is int if True else False\", variable has type \"def (x: object) -> x is int\")  [assignment]\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypeGuardUnreachable]\nfrom __future__ import annotations\n\ndef guard(x: object) -> x is list[int]: ...\n\na: list[object]\nif guard(a):  # E: Condition is always false  [redundant-expr] \\\n              # E: Intersection of \"list[object] & list[int]\" cannot exist: would have inconsistent method resolution order  [unreachable]\n    ...\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypeGuardUnsupported]\nfrom __future__ import annotations\ndef guard1(a: object, b: object) -> a is int | b is int: ...  # E: Invalid type comment or annotation  [valid-type]\ndef guard2(a: object, b: object) -> a is int & b is int: ...  # E: Invalid type comment or annotation  [valid-type]\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-typevar.test",
    "content": "[case testConstrainedTypeVarWithVariance]\nfrom typing import Protocol, TypeVar\n\nT1 = TypeVar(\"T1\", int, str)\nT2 = TypeVar(\"T2\", int, str, covariant=True)  # E: TypeVar with constraints cannot have variance  [valid-type]\nT3 = TypeVar(\"T3\", int, str, contravariant=True)  # E: TypeVar with constraints cannot have variance  [valid-type]\nT4 = TypeVar(\"T4\", int, str, infer_variance=True)  # E: Unexpected argument to \"TypeVar()\": \"infer_variance\"  [misc] \\\n                                                   # E: \"int\" not callable  [operator]  # stupid fake stubs moment\n\nclass A(Protocol[T1]):\n    \"\"\"inferred as covariant, but it's constrained so it's valid\"\"\"\n    def f(self) -> T1:\n        pass\n\n\n[case testTypeVarWrongNameStillWorks]\nfrom typing import TypeVar\n\nT = TypeVar(\"NotT\")  # E: String argument 1 \"NotT\" to TypeVar(...) does not match variable name \"T\"  [misc]\n\ndef f(t: T): ...\n\n\n[case testConstrainedTypeVarTypeApplication]\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\", \"int | str\", str)\n\nclass A(Generic[T]): ...\n\nA[int]()  # E: Value of type variable \"T\" of \"A\" cannot be \"int\"  [type-var]  \\\n          # N: \"T\" of \"A\" is a constrained type variable, it is not generic\n\n\n[case testConstrainedTypeAliasExtra-3.12]\nclass A[T: (int, str)]: ...\n\ntype BoolA[T: bool] = A[T]\nBoolA[bool]  # E: Value of type variable \"T\" of \"A\" cannot be \"bool\"  [type-var] \\\n             # N: \"T\" of \"A\" is a constrained type variable, it is not generic\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n\n[case testConstraintAllowAny]\nfrom typing import TypeVar, Generic, Any\nfrom typing_extensions import TypeAlias\n\nT = TypeVar(\"T\", int, str)\nclass A(Generic[T]): ...\n\na = A[Any]()  # E: Expression type contains \"Any\" (has type \"A[Any]\")  [any]\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-based-union-join.test",
    "content": "[case testSimpleUnionAtJoin]\na = [1, \"\"]\nreveal_type(a)  # N: Revealed type is \"list[int | str]\"\n\n\n[case testSubtype]\nclass A: pass\nclass B(A): pass\n\nreveal_type([A(), B()])  # N: Revealed type is \"list[__main__.A]\"\n\n\n[case testConditionalExpression]\nclass A: pass\nclass B: pass\n\nres = A() if bool() else B()\n\nreveal_type(res)  # N: Revealed type is \"__main__.A | __main__.B\"\n\n\n[case testChainedConditionalExpression]\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\n\nres = A() if bool() else B() if bool() else C() if bool() else D()\n\nreveal_type(res)  # N: Revealed type is \"__main__.A | __main__.B | __main__.C | __main__.D\"\n\n\n[case testTupleUnion]\nreveal_type([(1, \"\"), (None, False)])  # N: Revealed type is \"list[(int, str) | (None, bool)]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testUnionType]\nreveal_type(type([1, \"\"][0]))  # N: Revealed type is \"type[int] | type[str]\"\n\n\n[case testAbstractTypeCollection]\nfrom typing import Protocol\nclass Base(Protocol):\n    a: int\nclass A(Base):\n    pass\nclass B(Base):\n    pass\nclass C(Base):\n    pass\n\nreveal_type([A, B, C])  # N: Revealed type is \"list[() -> __main__.A | () -> __main__.B | () -> __main__.C]\"\n\n\n[case testTypeInIf]\nfrom typing import Type\n\nclass Ba: pass\nclass A(Ba): pass\nclass B(Ba): pass\nclass C(Ba): pass\nclass D(Ba): pass\n\ndef f() :\n    if 1 + 1:\n        cls: Type[Ba] = A\n    elif 1 + 1:\n        cls = B\n    elif 1 + 1:\n        cls = C\n    else:\n        cls = D\n\n\n[case testLiteralUnion]\nreveal_type(1 if bool() else 2)  # N: Revealed type is \"1 | 2\"\nreveal_type([1] if bool() else [])  # N: Revealed type is \"list[int]\"\n\n\n[case testLiteralUnionMessage]\na: 2 = 1 if bool() else 2  # E: Incompatible types in assignment (expression has type \"1 | 2\", variable has type \"2\")  [assignment]\n"
  },
  {
    "path": "test-data/unit/check-based-unsafe-variance.test",
    "content": "[case testUnsafeVarianceCo]\nfrom helper import T_out\nfrom typing import Generic\nclass G(Generic[T_out]):\n    def f(self, t: T_out): ...  # E: This usage of this covariant type variable is unsafe as an input parameter.  [unsafe-variance] \\\n                                # N: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\n\n\n[case testUnsafeVarianceContra]\nfrom helper import T_in\nfrom typing import Generic\nclass G(Generic[T_in]):\n    def f(self) -> T_in: ...  # E: This usage of this contravariant type variable is unsafe as a return type.  [unsafe-variance] \\\n                              # N: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\n\n\n[case testIgnore]\nfrom helper import T_in\nfrom typing import Generic\nclass G(Generic[T_in]):\n    def f(self) -> T_in: ...  # type: ignore[unsafe-variance]\n"
  },
  {
    "path": "test-data/unit/check-based-untyped.test",
    "content": "[case testUntypedReference]\nfrom basedtyping import Untyped\na: Untyped\nc: int\n\na = 1  # E: Usage of untyped name \"a\" in typed context  [no-untyped-usage]\nc = a  # E: Usage of untyped name \"a\" in typed context  [no-untyped-usage]\ndel a  # E: Usage of untyped name \"a\" in typed context  [no-untyped-usage]\n\nclass A:\n    b: Untyped\na1: A\ndel a1.b  # E: Usage of untyped name \"b\" in typed context  [no-untyped-usage]\ndel a1.b[1]  # E: Expression has type \"Untyped\"  [any] \\\n             # E: Expression has type \"Untyped\"  [any]\ndel a1.b.c  # E: Expression has type \"Untyped\"  [any] \\\n            # E: Usage of untyped name \"c\" in typed context  [no-untyped-usage]\na2: A\nc = a1.b  # E: Usage of untyped name \"b\" in typed context  [no-untyped-usage]\na1.b = 1  # E: Usage of untyped name \"b\" in typed context  [no-untyped-usage]\n\n\n[case testUntypedIndex]\n# flags: --allow-any-generics\nfrom typing import List\nfrom basedtyping import Untyped\n\nclass A(list): ...\na = A()\na[0] = 1  # E: Untyped indexed-assignment to \"a\" in typed context  [no-untyped-usage]\nclass B(List[Untyped]):\n    a: A\nb = B()\nb[0] = 1  # E: Untyped indexed-assignment to \"b\" in typed context  [no-untyped-usage]\nb.a[0] = 1  # E: Untyped indexed-assignment to \"a\" in typed context  [no-untyped-usage]\nc: Untyped\nc()[1] = 1  # E: Expression has type \"Untyped\"  [any]\n[builtins fixtures/list.pyi]\n\n\n[case testUntypedOmittedGeneric]\n# flags: --allow-any-generics\nfrom typing import List\nfrom basedtyping import Untyped\n\ndef f1(a: List): ...\ndef f2(a: List[Untyped]): ...\na = [1]\nf1(a)  # E: Call to incomplete function \"f1\" in typed context  [no-untyped-call] \\\n       # N: Type is \"def (a: list[Untyped]) -> None\"\nf2(a)  # E: Call to incomplete function \"f2\" in typed context  [no-untyped-call] \\\n       # N: Type is \"def (a: list[Untyped]) -> None\"\n\n\n[case testIncompleteCall]\n# flags: --allow-any-explicit\nfrom typing import Any\nfrom basedtyping import Untyped\n\ndef f1(a: Any): ...\ndef f2(a: Untyped) -> int: ...\n\nf1(1)\nf2(1)  # E: Call to incomplete function \"f2\" in typed context  [no-untyped-call] \\\n       # N: Type is \"def (a: Untyped) -> int\"\n\n\n[case testUntypedProperty]\n# flags: --allow-untyped-defs --allow-any-decorated\nfrom basedtyping import Untyped\n\nclass A:\n    @property\n    def foo(self): ...\n    @foo.setter\n    def foo(self, value): ...\n    @property\n    def bar(self) -> Untyped: ...\n    @bar.setter\n    def bar(self, value: Untyped) -> None: ...\n\na: A\na.foo = 1  # E: Usage of untyped name \"foo\" in typed context  [no-untyped-usage]\na.bar = 1  # E: Usage of untyped name \"bar\" in typed context  [no-untyped-usage]\n[builtins fixtures/property.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 \"Union[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]\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]\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]\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]\nnone = None\nb = none.__bool__()\nreveal_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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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\nfrom typing_extensions import 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 List, Optional, Union, Sequence, NamedTuple, Tuple, Type\nfrom typing_extensions import Literal, Final, 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 \"Optional[a.A]\", expected \"Optional[b.A]\")\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 \"Union[a.A, int]\", expected \"Union[b.A, int]\")\n\ndef spam() -> Optional[A]:\n    return a.A()  # E: Incompatible return value type (got \"a.A\", expected \"Optional[b.A]\")\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\n[builtins fixtures/dict.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 \"Union[builtins.int, builtins.str]\"\n\ny: \"\"\"(\n    int |\n    str\n)\n\"\"\"\nreveal_type(y)  # N: Revealed type is \"Union[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 --nonlocal-partial-types\nfrom typing import TypeVar, Generic\nT = TypeVar('T', bound=int)\nclass C(Generic[T]):\n    t: T\n    def get(self) -> T:\n        return self.t\nc1: C[None]\nc1.get()\nd = c1.get()  # E: \"get\" of \"C\" does not return a value (it only ever returns None)\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 --nonlocal-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)  # E: \"f\" does not return a value (it only ever returns None)\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: 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 \"Union[str, int]\"\nelse:\n    z = x + 6\n\n[builtins fixtures/callable.pyi]\n\n[case testUnionMultipleNonCallableTypes]\nfrom typing import Callable, Union\n\nx: 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 \"Union[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: 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: 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 \"Union[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: 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 \"Union[builtins.int, builtins.str]\"\n    else:\n        reveal_type(t)  # N: Revealed type is \"Union[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 testCallableWithNoneArgs]\n\nfn = None\nif callable(fn):\n  fn()\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: Union[None, Callable[[], int]]\nif bool():\n    fn = f\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 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 \"Callable[[Arg(int, 'x'), VarArg(Any), KwArg(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 \"Callable[[Arg(int, 'x'), VarArg(Any), KwArg(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 \"Callable[[Arg(int, 'x'), VarArg(Any), KwArg(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, Union[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, Union[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[[Base], 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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 \"object\"; supertype defines the argument type as \"object\"\nmain:2: note: This violates the Liskov substitution principle\nmain:2: note: See https://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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__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 types import FunctionType\n\ndef int_to_none(f: \"FunctionType[..., int]\") -> \"FunctionType[..., None]\": ...\ndef str_to_int(f: \"FunctionType[..., str]\") -> \"FunctionType[..., 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[builtins fixtures/tuple.pyi]\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 types import FunctionType\n\ndef str_to_int(f: \"FunctionType[..., str]\") -> \"FunctionType[..., 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[builtins fixtures/tuple.pyi]\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 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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 \"Optional[str]\"  [override] \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://kotlinisland.github.io/basedmypy/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    @func.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  # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], None]\", override has type \"Callable[[object], None]\")\n    def f(self) -> Callable[[object], None]: pass\n    @func.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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[__main__.WithMetaclass, None]\"\n\nf2 = join(WithMetaclass, func)\nreveal_type(f2())  # N: Revealed type is \"Union[__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 = None  # type: 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 = None  # type: 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[out]\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 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 \"Union[builtins.int, builtins.float]\"\nreveal_type(a + b)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\nreveal_type(b + a)  # N: Revealed type is \"Union[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 \"Union[Foo, Bar]\"\n\nb + a  # E: Unsupported operand types for + (\"Foo\" and \"Bar\") \\\n       # N: Right operand is of type \"Union[Foo, Bar]\"\n\na + c  # E: Unsupported operand types for + (\"Foo\" and \"Bar\") \\\n       # N: Left operand is of type \"Union[Foo, Bar]\"\n\nc + a  # E: Unsupported operand types for + (\"Bar\" and \"Foo\") \\\n       # N: Right operand is of type \"Union[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 \"Union[__main__.Foo, __main__.Bar]\"\nreveal_type(a + b)  # N: Revealed type is \"Union[__main__.Foo, __main__.Bar]\"\nreveal_type(b + a)  # N: Revealed type is \"Union[__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 \"Union[__main__.Out3, __main__.Out1, __main__.Out2, __main__.Out4]\"\nreveal_type(A() + y)  # N: Revealed type is \"Union[__main__.Out3, __main__.Out1]\"\nreveal_type(B() + y)  # N: Revealed type is \"Union[__main__.Out2, __main__.Out4]\"\nreveal_type(x + C())  # N: Revealed type is \"Union[__main__.Out3, __main__.Out2]\"\nreveal_type(x + D())  # N: Revealed type is \"Union[__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 \"Union[builtins.float, builtins.int]\"\nreveal_type(sum(x) / len(x))  # N: Revealed type is \"Union[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://kotlinisland.github.io/basedmypy/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: ...  # E: Method must have at least one argument. Did you forget the \"self\" argument? # E: Invalid signature \"Callable[[], None]\" for \"__setattr__\"\nt = Test()\nt.crash = 'test'  # 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 \"Optional[int]\"\n[builtins fixtures/__new__.pyi]\n\n[case testConstructInstanceWithDynamicallyTyped__new__]\nclass C:\n    def __new__(cls, foo):  # N: \"C\" defined here\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 __new__(cls, foo: int) -> C \\\n      # N:     def __new__(cls, 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 \"Union[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        u = 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 __init__(self) -> U\ntmp/foo.pyi:17: note:     def __init__(self, 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 == (\"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 = None  # type: 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 = None  # type: int\nclass B(A):\n    a = None  # type: 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 = None  # type: 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 = None  # type: 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 = None  # type: 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 = None  # type: 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 = None  # type: 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 = None  # type: List[T]\n    b = None  # type: 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[[A], 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 = None  # type: 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 = None  # type: Callable[[A, int], int]\nclass B(A):\n    def c(self, a: int) -> int: pass\n    b = c\n\n[case testClassSpecError]\nfrom typing import Callable\nclass A():\n    b = None  # type: Callable[[A, int], int]\nclass B(A):\n    def c(self, a: str) -> int: pass\n    b = c\n[out]\nmain:6: error: 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\n[builtins fixtures/staticmethod.pyi]\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"Callable[[str], None]\", base class \"A\" defined the type as \"Callable[[int], None]\")\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\"\nclass C(B):\n    x = object()\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\nmain:6: error: Incompatible types in assignment (expression has type \"object\", base class \"A\" defined the type as \"int\")\n\n[case testClassOneErrorPerLine]\nclass A:\n  x = 1\nclass B(A):\n  x = \"\"\n  x = 1.0\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\nmain:5: error: 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 = ''  # E: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n[out]\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[out]\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[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\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 mypy_extensions import TypedDict\n\nA = TypedDict('A', {'a': 'A'})  # type: ignore\na: A\n[builtins fixtures/isinstancelist.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 mypy_extensions 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\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 mypy_extensions import TypedDict\nfrom typing import Dict\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-medium.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\nfrom mypy_extensions import 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[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 mypy_extensions 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[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 mypy_extensions 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[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 \"Union[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 mypy_extensions import TypedDict\nfrom typing import 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[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 \"Union[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\nfrom mypy_extensions import 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[out]\n\n[case testCrashInvalidArgsSyntheticClassSyntaxReveals]\nfrom typing import List, NamedTuple\nfrom mypy_extensions import 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[out]\n\n[case testCrashInvalidArgsSyntheticFunctionSyntax]\nfrom typing import List, NewType, NamedTuple\nfrom mypy_extensions import 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[out]\n\n[case testCrashForwardSyntheticClassSyntax]\nfrom typing import NamedTuple\nfrom mypy_extensions import 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[out]\n\n[case testCrashForwardSyntheticFunctionSyntax]\nfrom typing import NamedTuple\nfrom mypy_extensions import 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[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\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[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[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: \"decorate\" defined here\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):\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[out]\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\nfrom types import FunctionType\n\nF = TypeVar('F', bound=Callable)\nT = TypeVar('T')\n\ndef decorator(f: F) -> F:\n    return f\n\ndef change(f: Callable) -> \"FunctionType[[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\n\nclass Base: ...\nclass Sub(Base): ...\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[__main__.Sub]\"\n    def other(self, cls: Type[T]) -> None:\n        if not issubclass(cls, Sub):\n            return\n        reveal_type(cls)  # N: Revealed type is \"Type[__main__.Sub]\"\n\n[builtins fixtures/isinstancelist.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 \"Union[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\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 = ''\n\n    def f(self) -> None:\n        # https://github.com/python/mypy/issues/7162\n        reveal_type(self.x) # N: Revealed type is \"builtins.str\"\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__.D.g, __main__.D.f, __main__.C.__init__, __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 \"Optional[Y]\")\n        pass\nclass Y:\n    def __new__(cls) -> Optional[int]:  # E: \"__new__\" must return a class instance (got \"Optional[int]\")\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\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\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\nclass ChildOfConflict1(Conflict3): ...  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases\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\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\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\"\ntmp/builtins.pyi:5: note: \"__init_subclass__\" of \"object\" defined here\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]\nimport _typeshed  # cringe moment\n\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\nimport _typeshed  # cringe moment\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 \"Union[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 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 \"Type[__main__.Base]\"\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 decorator is @y.setter\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 testFinalProtocolWithAbstractAttributes]\nfrom typing import Protocol, final\n\n@final #OK\nclass Inter(Protocol):\n    x: int\n\n    def y(self) -> int:\n        ...\n\n    @property\n    def z(self) -> int:\n        ...\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 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://kotlinisland.github.io/basedmypy/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)  # E: Type variable \"Foo.T\" cannot be used as an expression \\\n                    # N: Revealed type is \"Any\"\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\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:          None \\\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:          None \\\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:          None \\\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:          None \\\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\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 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\" aren't 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\" aren't 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\" aren't 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\" aren't 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\" aren't 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"
  },
  {
    "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 = None  # type: 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 = None  # type: 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 = None  # type: 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 = None  # type: 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: 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 = None  # type: 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 = None  # type: 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 = None  # type: 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 = None  # type: 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 \"Union[int, str]\")\nmain:9: note: Revealed type is \"Union[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 = None  # type: ClassVar[Union[A, B, C]]\nclass E(D):\n    x = None  # type: 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 = None  # type: ClassVar[Union[A, B]]\nclass E(D):\n    x = None  # type: ClassVar[Union[A, B, C]]\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"Union[A, B, C]\", base class \"D\" defined the type as \"Union[A, B]\")\n\n[case testAssignmentToCallableRet]\nfrom typing import ClassVar\nclass A:\n    x = None  # type: 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 = None  # type: ClassVar[int]\nclass B(A):\n    x = None  # type: 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 = None  # type: 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 = None  # type: 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]  # E: ClassVar cannot contain type variables\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]]]]  # E: ClassVar cannot contain type variables\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\nBad.x  # E: Access to generic class variables is ambiguous\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"
  },
  {
    "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]\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:1: \"f\" defined here\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:5: \"f\" defined here\n    (f(b=object())) # E:6: Unexpected keyword argument \"b\" for \"f\"\n\n[case testColumnInvalidType]\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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: --nonlocal-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://kotlinisland.github.io/basedmypy/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: --python-version 3.8 --disallow-any-generics\nfrom typing import List, Callable\ndef f(x: List) -> None: pass # E:10: Missing type parameters for generic type \"List\"\ndef g(x: list) -> None: pass # E:10: Implicit generic \"Any\". Use \"typing.List\" and specify generic parameters\nif int():\n    c: Callable # E:8: Missing type parameters 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 argument \"x\" (default has type \"str\", argument 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 arguments\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]\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                                  # N:12: \"T\" of \"C\" is a constrained type variable, it is not generic\n(C[object]()) # E:2: Value of type variable \"T\" of \"C\" cannot be \"object\" \\\n              # N:2: \"T\" of \"C\" is a constrained type variable, it is not generic \\\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[builtins fixtures/tuple.pyi]\n\n[case testColumnSyntaxErrorInTypeAnnotation2]\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:1: \"g\" defined here\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    # XXX: Disabled because the column differs in 3.8\n    # aa: List[int] = ['' for x in [1]] # :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"
  },
  {
    "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, Union[c_int, int], /) -> None \\\n                 # N:     def __setitem__(self, slice, List[Union[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, Union[MyCInt, int], /) -> None \\\n                           # N:     def __setitem__(self, slice, List[Union[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, Union[MyCInt, int], /) -> None \\\n                   # N:     def __setitem__(self, slice, List[Union[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 \"Union[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[Union[__main__.MyCInt, ctypes.c_uint]]\"\nreveal_type(mya[0])  # N: Revealed type is \"Union[__main__.MyCInt, builtins.int]\"\nreveal_type(mya[1:3])  # N: Revealed type is \"builtins.list[Union[__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, Union[MyCInt, int, c_uint], /) -> None \\\n                   # N:     def __setitem__(self, slice, List[Union[MyCInt, int, c_uint]], /) -> None\nfor myx in mya:\n    reveal_type(myx)  # N: Revealed type is \"Union[__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 \"Union[builtins.bytes, builtins.str]\"\ncua.raw  # E: Array attribute \"raw\" is only available with element type \"c_char\", not \"Union[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 \"Union[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 \"Union[c_char, c_int]\"\ncua.raw  # E: Array attribute \"raw\" is only available with element type \"c_char\", not \"Union[c_char, c_int]\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesAnyArrayAttrs]\nimport ctypes\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[typing fixtures/typing-medium.pyi]\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\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 \"Union[builtins.int, None]\"\nreveal_type(c.y)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.z)  # N: Revealed type is \"Union[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 mypy_extensions import TypedDict\nfrom typing import NamedTuple\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\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://kotlinisland.github.io/basedmypy/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 --nonlocal-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"
  },
  {
    "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)  # E: Too many positional arguments for \"Foo\"\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 \"Optional[bytes]\"\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 \"Optional[bytes]\")\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: Cannot inherit non-frozen dataclass from a frozen one\n    pass\n\n@dataclass\nclass NormalBase:\n    pass\n\n@dataclass(frozen=True)\nclass BadFrozenDerived(NormalBase):  # E: Cannot inherit frozen dataclass from a non-frozen one\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: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> _T \\\n                                 # N:     def [_T] field(*, default_factory: Callable[[], _T], init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> _T \\\n                                 # N:     def field(*, init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., 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: Union[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)  # E: Attributes without a default cannot follow attributes with one\n\nApplication(name='name', rating=5)\nApplication()  # E: Missing positional argument \"name\" in call to \"Application\"\nApplication('name')  # E: Too many positional arguments for \"Application\" # E: Too few arguments 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 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 \"def () -> typing.Callable\"\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: Union[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 type argument 1 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: 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: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> _T\nmain:6: note:     def [_T] field(*, default_factory: Callable[[], _T], init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> _T\nmain:6: note:     def field(*, init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., 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: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> _T \\\n                       # N:     def [_T] field(*, default_factory: Callable[[], _T], init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> _T \\\n                       # N:     def field(*, init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...) -> Any\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldWithTypedDictUnpacking]\nfrom dataclasses import dataclass, field\nfrom typing_extensions 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\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 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 \"Optional[str]\"\nChild(x='', y='')  # E: Argument \"y\" to \"Child\" has incompatible type \"str\"; expected \"Optional[int]\"\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 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]\n# flags: --python-version 3.9\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 \"Union[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 \"Optional[SubLinkedList]\"\nreveal_type(lst.next)  # N: Revealed type is \"Union[__main__.SubLinkedList, None]\"\nreveal_type(SubLinkedList)  # N: Revealed type is \"def (value: builtins.int, next: Union[__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 \"Union[A[int], B]\"\n_ = replace(a_or_b, x=42, y=True, z='42', init_var=42)  # E: Argument \"z\" to \"replace\" of \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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\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 \"Optional[int]\", 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 \"Optional[int]\")\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 \"Optional[int]\", expression has type \"int\")\n[builtins fixtures/tuple.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\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               # E: function __main__.f is deprecated: use f2 instead\n\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               # 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\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 \\\n                 # 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 testDeprecatedOverloadedSpecialMethods]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Iterator, Union\nfrom typing_extensions import deprecated, overload\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                     # 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, Optional, Union\nfrom typing_extensions import deprecated, overload\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 C:\n    d1 = D1()  # E: class __main__.D1 is deprecated: use E1 instead\n    d2 = D2()\n    d3 = D3()\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[builtins fixtures/property.pyi]\n\n\n[case testDeprecatedOverloadedFunction]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Union\nfrom typing_extensions import deprecated, overload\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(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(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(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[builtins fixtures/tuple.pyi]\n\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\nfrom typing_extensions import deprecated, overload\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\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 \"Union[Any, bool]\", variable has type \"C\")\nif int():\n    c = d or b  # E: Incompatible types in assignment (expression has type \"Union[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\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 \"Union[Literal[False], Any]\", variable has type \"C\")\nif int():\n    c = b or d  # E: Incompatible types in assignment (expression has type \"Union[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  # E: \"A\" has no attribute \"y\"\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\nt = d\nf = d\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://kotlinisland.github.io/basedmypy/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_extensions 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_extensions 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 \"Union[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 \"Union[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_extensions 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_extensions 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_extensions 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)  # N: Revealed type is \"__main__.F[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\n# TODO: The revealed type should be 'int' here\nreveal_type(A.x.value)  # N: Revealed type is \"Any\"\nreveal_type(B.a.value)  # N: Revealed type is \"Any\"\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_extensions 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\n# TODO: getting B1.x._value_ and B2.x._value_ to have type 'int' requires a typeshed change\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 \"Any\"\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\n# TODO: C1.x.value and C2.x.value should also be of type 'int'\n# This requires either a typeshed change or a plugin refinement\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 \"Any\"\nreveal_type(C1.x._value_)       # N: Revealed type is \"Any\"\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 \"Any\"\nreveal_type(D1.x._value_)       # N: Revealed type is \"Any\"\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]\nfrom enum import Enum\nfrom typing_extensions 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)  # No output here: this branch is unreachable\nreveal_type(x) # N: Revealed type is \"Union[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)  # No output here: this branch is unreachable\nreveal_type(x) # N: Revealed type is \"Union[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)  # No output here: this branch 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)  # No output here: this branch is unreachable\nreveal_type(y) # N: Revealed type is \"__main__.Foo\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityChecksWithOrdering]\nfrom enum import Enum\nfrom typing_extensions 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)  # No output here: this branch 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)  # No output here: this branch 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)  # No output here: this branch 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)  # No output here: this branch is unreachable\n[builtins fixtures/tuple.pyi]\n\n[case testEnumReachabilityChecksIndirect]\nfrom enum import Enum\nfrom typing_extensions import Literal, Final\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 \"Union[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 \"Union[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 \"Union[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 \"Union[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)  # No output: this branch is unreachable\n    reveal_type(z)  # No output: this branch is unreachable\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)  # No output: this branch is unreachable\n    reveal_type(z)  # No output: this branch is unreachable\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityNoNarrowingForUnionMessiness]\nfrom enum import Enum\nfrom typing_extensions 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\n# For the sake of simplicity, no narrowing is done when the narrower type is a Union.\nif x is y:\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(y)  # N: Revealed type is \"Union[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 \"Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]\"\n\nif y is z:\n    reveal_type(y)  # N: Revealed type is \"Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]\"\n    reveal_type(z)  # N: Revealed type is \"Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"Union[Literal[__main__.Foo.A], Literal[__main__.Foo.B]]\"\n    reveal_type(z)  # N: Revealed type is \"Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityWithNone]\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 \"Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C], None]\"\nreveal_type(x) # N: Revealed type is \"Union[__main__.Foo, None]\"\n[builtins fixtures/enum.pyi]\n\n[case testEnumReachabilityWithMultipleEnums]\nfrom enum import Enum\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[Literal[__main__.Foo.B], __main__.Bar]\"\nreveal_type(x1) # N: Revealed type is \"Union[__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 \"Union[__main__.Foo, Literal[__main__.Bar.B]]\"\nreveal_type(x2) # N: Revealed type is \"Union[__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 \"Union[Literal[__main__.Foo.A], Literal[__main__.Bar.A]]\"\nelse:\n    reveal_type(x3)  # N: Revealed type is \"Union[Literal[__main__.Foo.B], Literal[__main__.Bar.B]]\"\nreveal_type(x3) # N: Revealed type is \"Union[__main__.Foo, __main__.Bar]\"\n\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityPEP484ExampleWithFinal]\nfrom typing import Union\nfrom typing_extensions import Final\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 \"Union[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]\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]\nfrom typing import Union\nfrom typing_extensions import Final\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 \"Union[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]\nfrom typing import Union\nfrom typing_extensions import Final\nfrom enum import Enum\n\nclass Empty(Enum):\n    token = lambda x: x\n\n    def f(self) -> int:\n        return 1\n\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 \"Union[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]\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_extensions import Literal, Final\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_extensions import Literal, Final\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 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 \"Union[Literal[1]?, Literal[2]?]\"\nreveal_type(a._value_)  # N: Revealed type is \"Union[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 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 Union\nfrom typing_extensions import Literal\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 \"Union[Literal[__main__.Foo.B], Literal[__main__.Foo.C]]\"\n\n[builtins fixtures/bool.pyi]\n\n[case testEnumTypeCompatibleWithLiteralUnion]\nfrom enum import Enum\nfrom typing_extensions 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]\nif bool():\n    a = 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 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[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\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\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):  # E: Cannot extend enum with existing members: \"A\"\n    x = 1    # E: Cannot override writable attribute \"x\" with a final one\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: Cannot assign to final name \"x\"\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 \"Union[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 \"Union[Literal[1]?, Literal[2]?]\"\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 \"Type[Callable[[str], None]]\", 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: \"dict\" expects no type arguments, but 2 given \\\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"
  },
  {
    "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]\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]\ndef f(): # E: Type signature has too many arguments  [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]\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[builtins fixtures/tuple.pyi]\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[builtins fixtures/tuple.pyi]\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 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]\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://kotlinisland.github.io/basedmypy/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]\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://kotlinisland.github.io/basedmypy/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  # N: \"f\" defined here\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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 argument \"x\" (default has type \"int\", argument 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: --python-version 3.8 --disallow-any-generics\nfrom typing import List, TypeVar\nx: List  # E: Missing type parameters for generic type \"List\"  [type-arg]\ny: list  # E: Implicit generic \"Any\". Use \"typing.List\" and specify generic parameters  [type-arg]\nT = TypeVar('T')\nL = List[List[T]]\nz: L  # E: Missing type parameters 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 \"Union[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 arguments  [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 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             # N: \"T\" of \"f\" is a constrained type variable, it is not generic\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] \\\n              # N: \"T\" of \"C\" is a constrained type variable, it is not generic\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              # N: \"T\" of \"C\" is a constrained type variable, it is not generic\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_extensions 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_extensions 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_extensions 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]  # 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 arguments  [syntax]\n    # type: () -> None\n    pass\n\ndef g(x):  # E: Type signature has too many arguments  [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://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\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\nx = f()  # E: \"f\" does not return a value (it only ever returns None)  [func-returns-value]\n\nclass A:\n    def g(self) -> None: pass\n\ny = A().g()  # E: \"g\" of \"A\" does not return a value (it only ever returns None)  [func-returns-value]\n\nc: Callable[[], None]\nz = 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 \"Union[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 \"Union[int, float, complex, 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_extensions 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]\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_extensions.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 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_extensions 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\n[case testTruthyBool]\n# flags: --enable-error-code truthy-bool --nonlocal-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]\nif good_union:\n    pass\nif not good_union:\n    pass\n\nnot good_union\n\nbad_union: Union[Foo, Bar]\nif bad_union:  # E: \"__main__.bad_union\" has type \"Union[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 \"Union[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 \"Union[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\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 testSliceInDict39]\n# flags: --python-version 3.9 --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[case testSliceInDict38]\n# flags: --python-version 3.8 --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_extensions 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] \\\n                          # N: Error code \"syntax\" not covered by \"type: ignore\" comment\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] \\\n                                 # N: Error code \"syntax\" not covered by \"type: ignore\" comment\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\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 \"Union[Literal[False], A]\", variable has type \"bool\")\nif int():\n    b = a and b # E: Incompatible types in assignment (expression has type \"Union[A, bool]\", variable has type \"bool\")\nif int():\n    b = b or a  # E: Incompatible types in assignment (expression has type \"Union[Literal[True], A]\", variable has type \"bool\")\nif int():\n    b = a or b  # E: Incompatible types in assignment (expression has type \"Union[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[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\nfrom typing_extensions import 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, TypeVar, Generic\nfrom typing_extensions import Literal\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 assert_type\nfrom typing_extensions import Literal\ndef f():\n    x = 42\n    assert_type(x, Literal[42])\n[out]\nmain:5: error: Expression is of type \"Any\", not \"Literal[42]\"\nmain:5: 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 assert_type\nfrom typing_extensions import Literal\ndef f():\n    x = 42\n    assert_type(x, Literal[42])\n[out]\nmain:6: 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-- 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 \"Union[Literal[1]?, Literal[2]?]\"\nreveal_type(1 if bool() else '') # N: Revealed type is \"Union[Literal[1]?, Literal['']?]\"\nx: Union[int, str] = reveal_type(1 if bool() else '') # N: Revealed type is \"Union[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 \"Union[__main__.B, __main__.C]\"\nreveal_type(c if bool() else b) # N: Revealed type is \"Union[__main__.C, __main__.B]\"\nreveal_type(c if bool() else a) # N: Revealed type is \"Union[__main__.C, __main__.A]\"\nreveal_type(d if bool() else b) # N: Revealed type is \"Union[__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 \"Union[Any, Literal[1]?]\"\nreveal_type(a if int() else 1)  # N: Revealed type is \"Union[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                                           # 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 \"Union[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]\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 type argument 1 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 type argument 1 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: \"Union[A, B]\", right operand type: \"int\")\n\na is int()\nb is int()  # E: Non-overlapping identity check (left operand type: \"Union[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: \"Union[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: \"Optional[str]\", right operand type: \"Optional[int]\")\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[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_extensions import Literal, Final\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 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"
  },
  {
    "path": "test-data/unit/check-fastparse.test",
    "content": "[case testFastParseSyntaxError]\n\n1 +  # E: invalid syntax\n\n[case testFastParseTypeCommentSyntaxError]\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]\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]\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 \"Union[__main__.B, None]\"\n    reveal_type(args)   # N: Revealed type is \"builtins.tuple[__main__.C, ...]\"\n    reveal_type(d)      # N: Revealed type is \"Union[__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 \"Union[__main__.B, None]\"\n    reveal_type(args)   # N: Revealed type is \"builtins.tuple[__main__.C, ...]\"\n    reveal_type(d)      # N: Revealed type is \"Union[__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]\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 arguments\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 arguments\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]\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 arguments\n    # type: () -> None\n    pass\ndef g():  # E: Type signature has too many arguments\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 f(x, y, z):\n  # type: (int, int, int) -> int\n  pass\n\ndef f(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 f(x,  # type: int\n      y,  # type: int\n      z   # type: int\n    ):\n    # type: (...) -> int\n    pass\n\ndef f(x, y, z):\n  # type: (int, int, int) -> int\n  pass\n\ndef f(x) -> int:  # E: Function has duplicate type signatures\n  # type: (int) -> int\n  pass\n\ndef f(x: int, y: int, z: int):\n  # type: (...) -> int\n  pass\n\ndef f(x: int):  # E: Function has duplicate type signatures\n  # type: (int) -> int\n  pass\n\n[case testFastParserDuplicateNames]\n\ndef f(x, y, z):\n  pass\n\ndef g(x, y, x):  # E: Duplicate argument \"x\" in function definition\n  pass\n\ndef h(x, y, *x):  # E: Duplicate argument \"x\" in function definition\n  pass\n\ndef i(x, y, *z, **z):  # E: Duplicate argument \"z\" in function definition\n  pass\n\ndef j(x: int, y: int, *, x: int = 3):  # E: Duplicate argument \"x\" in function definition\n  pass\n\ndef k(*, y, z, y):  # E: Duplicate argument \"y\" in function definition\n  pass\n\nlambda x, y, x: ...  # E: Duplicate argument \"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"
  },
  {
    "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.int\"\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.int\"\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.int\"\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 \"Literal[1]?\"\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 \"Literal[1]?\"\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_extensions 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_extensions import final, Literal\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 \"Union[__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_extensions import final, Literal\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 \"Union[__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"
  },
  {
    "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 arguments\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-full.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 arguments\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 mypy_extensions 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 mypy_extensions 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 mypy_extensions 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 mypy_extensions 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 mypy_extensions 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 mypy_extensions 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 mypy_extensions 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 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://kotlinisland.github.io/basedmypy/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 arguments\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 arguments\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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 mypy_extensions 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\n[case testDisallowUnimportedAnyTypedDictGeneric]\n# flags: --ignore-missing-imports --disallow-any-unimported\n\nfrom mypy_extensions import TypedDict\nfrom typing import List\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\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[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\"  # 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 its 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  # E: Expression has type \"Any\"\nx = Foo().g  # type: int  # E: Expression has type \"Any\"\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 mypy_extensions 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\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 arguments\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 arguments\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 arguments\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\nfrom mypy_extensions import 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\n\n[case testCheckDisallowAnyGenericsStubOnly]\n# flags: --disallow-any-generics --python-version 3.8\nfrom asyncio import Future\nfrom queue import Queue\nx: Future[str]\ny: Queue[int]\n\np: Future  # E: Missing type parameters for generic type \"Future\" \\\n           # N: Subscripting classes that are not generic at runtime may require escaping, see https://kotlinisland.github.io/basedmypy/runtime_troubles.html#not-generic-runtime\nq: Queue  # E: Missing type parameters for generic type \"Queue\" \\\n          # N: Subscripting classes that are not generic at runtime may require escaping, see https://kotlinisland.github.io/basedmypy/runtime_troubles.html#not-generic-runtime\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 testDisallowAnyGenericsBuiltinTuplePre39]\n# flags: --disallow-any-generics --python-version 3.8\ns = tuple([1, 2, 3])\ndef f(t: tuple) -> None: pass  # E: Implicit generic \"Any\". Use \"typing.Tuple\" and specify generic parameters\n[builtins fixtures/tuple.pyi]\n\n[case testDisallowAnyGenericsBuiltinListPre39]\n# flags: --disallow-any-generics --python-version 3.8\nl = list([1, 2, 3])\ndef f(t: list) -> None: pass  # E: Implicit generic \"Any\". Use \"typing.List\" and specify generic parameters\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyGenericsBuiltinSetPre39]\n# flags: --disallow-any-generics --python-version 3.8\nl = set({1, 2, 3})\ndef f(s: set) -> None: pass  # E: Implicit generic \"Any\". Use \"typing.Set\" and specify generic parameters\n[builtins fixtures/set.pyi]\n\n[case testDisallowAnyGenericsBuiltinDictPre39]\n# flags: --disallow-any-generics --python-version 3.8\nl = dict([('a', 1)])\ndef f(d: dict) -> None: pass  # E: Implicit generic \"Any\". Use \"typing.Dict\" and specify generic parameters\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-- maybe a little useless because theres no strict but w/e\n# flags: --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 parameters for generic type \"C\"\n    pass\n[out]\n\n[case testStrictAnyGeneric]\n-- maybe a little useless because theres no strict but w/e\n# flags: --disallow-any-generics\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 parameters for generic type \"A\"\n    pass\n[out]\n\n[case testStrictInConfigAnyGeneric]\n# flags: --config-file tmp/mypy.ini\n-- maybe a little useless because theres no strict but w/e\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 parameters for generic type \"A\"\n    pass\n[file mypy.ini]\n\\[mypy]\ndisallow_any_generics = True\n[out]\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 parameters for generic type \"A\"\n    pass\n\n[file pyproject.toml]\n\\[tool.mypy]\ndisallow_any_generics = true\n\n[out]\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-- maybe a little useless because theres no strict but w/e\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-- maybe a little useless because theres no strict but w/e\n# flags: --strict-equality\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 parameters for generic type \"A\"\nx: A  # E:4: Missing type parameters 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 mypy_extensions import TypedDict\nfrom typing import Any\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\n[case testDisallowAnyExplicitTypedDictGeneric]\n# flags: --disallow-any-explicit --show-error-codes\nfrom mypy_extensions import TypedDict\nfrom typing import Any, List\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\n[case testDisallowAnyGenericsTupleNoTypeParams]\n# flags: --disallow-any-generics\nfrom typing import Tuple\n\ndef f(s: Tuple) -> None: pass  # E: Missing type parameters for generic type \"Tuple\"\ndef g(s) -> Tuple:  # E: Missing type parameters 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 parameters 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 parameters for generic type \"Tuple\"\ndef g(s: List[Tuple]) -> None: pass  # E: Missing type parameters 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 parameters for generic type \"Type\"\n    return s\ndef h(s) -> Type[str]:  # no error\n    return s\nx: Type = g(0)  # E: Missing type parameters 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 parameters 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 parameters for generic type \"A\"\ndef g(s) -> A:  # E: Missing type parameters 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 parameters 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 parameters for generic type \"List\"\ndef g(l: List[str]) -> None: pass\ndef h(l: List[List]) -> None: pass   # E: Missing type parameters for generic type \"List\"\ndef i(l: List[List[List[List]]]) -> None: pass  # E: Missing type parameters for generic type \"List\"\ndef j() -> List: pass  # E: Missing type parameters for generic type \"List\"\n\nx = []  # E: Need type annotation for \"x\" (hint: \"x: List[<type>] = ...\")\ny: List = []  # E: Missing type parameters 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 parameters for generic type \"Dict\"\ndef g(d: Dict[str, Dict]) -> None: pass  # E: Missing type parameters for generic type \"Dict\"\ndef h(d: List[Dict]) -> None: pass  # E: Missing type parameters for generic type \"Dict\"\n\nd: Dict = {}  # E: Missing type parameters 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 parameters for generic type \"Set\"\ndef g(s: Set[Set]) -> None: pass  # E: Missing type parameters for generic type \"Set\"\n\ns: Set = set()  # E: Missing type parameters 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 parameters for generic type \"G\"\n    return G()\n\nx: G[Any] = G()  # no error\ny: G = x  # E: Missing type parameters 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 parameters for generic type \"A\"\nA.foo()  # E: Missing type parameters 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\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 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] __init__(self) -> List[T] \\\n         # N:     def [T] __init__(self, x: Iterable[T]) -> List[T] \\\n         # N: See https://kotlinisland.github.io/basedmypy/_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] __init__(self) -> List[T] \\\n         # N:     def [T] __init__(self, 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 parameters for generic type \"C\" \\\n                    # E: Missing type parameters for generic type \"List\"\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"
  },
  {
    "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 \"Union[int, float, complex, SupportsInt]\")\n'%d' % t\n'%d' % s  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"Union[int, float, complex, SupportsInt]\")\n'%f' % s  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"Union[int, float, complex, 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 \"Union[int, float, complex, 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\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 \"Union[int, float, complex, 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 \"Union[int, float, complex, SupportsFloat]\")\nmain:4: error: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"Union[int, float, complex, 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/f_string.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]]\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]]\nif bool():\n    c = ('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]\nt2: List[str]\nt3: Tuple[str, ...]\nt4: Tuple[str, str]\nt5: Iterable[str]\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 \"Union[int, float, complex]\")\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')  # E: The type \"__main__.Bad\" doesn't support format-specifiers \\\n                                              # N: Maybe you want to add '!s' to the conversion\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 \"Union[int, float, complex]\")\n'{:g}'.format('no')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"Union[int, float, complex]\")\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: The type \"__main__.C\" doesn't support format-specifiers \\\n                    # N: Maybe you want to add '!s' to the conversion\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: The type \"__main__.Bad\" doesn't support format-specifiers \\\n                  # N: Maybe you want to add '!s' to the conversion\n'{:d}'.format(y)\n'{:d}'.format(z)  # E: The type \"__main__.Bad\" doesn't support format-specifiers \\\n                  # N: Maybe you want to add '!s' to the conversion\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_extensions 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_extensions import Final\nfrom typing import cast\n\nGOOD: Final = 'c'\nBAD: Final = 'no'\nOK: Final[str] = cast(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_extensions 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 \"Union[int, float, complex]\")\n\ndef f() -> str: ...\n'{[f()]}'.format(u)  # E: Invalid index expression in format field accessor \"[f()]\"\n[builtins fixtures/primitives.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: The type \"__main__.S\" doesn't support format-specifiers \\\n                     # N: Maybe you want to add '!s' to the conversion\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://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\nmain:10: error: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\"\nmain:10: note: This violates the Liskov substitution principle\nmain:10: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\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://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides \\\n                                              # E: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str\" \\\n                                              # N: This violates the Liskov substitution principle \\\n                                              # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\n\nclass C(A):\n    def f(self, a: int, b: 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]\n\ndef l(x) -> None: ...\ndef r(__, *, x) -> None: ...\nr = l # E: Incompatible types in assignment (expression has type \"Callable[[Any], None]\", variable has type \"Callable[[Any, NamedArg(Any, 'x')], None]\")\n\n[case testSubtypingFunctionsRequiredLeftArgNotPresent]\n\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 \"Callable[[Arg(int, 'a'), Arg(str, 'b')], None]\")\nif int():\n    ff = f # reset\nif int():\n    gg = ff # E: Incompatible types in assignment (expression has type \"Callable[[Arg(int, 'a'), Arg(str, 'b')], None]\", variable has type \"Callable[[Arg(int, 'a'), DefaultArg(str, 'b')], None]\")\nif int():\n    gg = hh # E: Incompatible types in assignment (expression has type \"Callable[[Arg(int, 'aa'), DefaultArg(str, 'b')], None]\", variable has type \"Callable[[Arg(int, 'a'), DefaultArg(str, 'b')], None]\")\n\n[case testSubtypingFunctionsArgsKwargs]\nfrom typing import Any, Callable\nfrom types import FunctionType\n\ndef everything(*args: Any, **kwargs: Any) -> None: pass\neverywhere: \"FunctionType[..., 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 \"Callable[[Arg(int, 'a'), Arg(str, 'b')], 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 \"Callable[[Arg(int, 'a'), Arg(str, 'b')], None]\")\n\n[case testFunctionTypeCompatibilityWithOtherTypes]\n# flags: --no-strict-optional\nfrom typing import Callable\nf: Callable[[], None]\na: A\no: 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 = A(), B() # 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 \"Optional[A]\"\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 testDefaultArgumentExpressions]\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 testDefaultArgumentExpressions2]\nimport typing\nclass B: pass\nclass A: pass\n\ndef f(x: 'A' = B()) -> None: # E: Incompatible default for argument \"x\" (default has type \"B\", argument 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 testDefaultArgumentExpressionsGeneric]\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 argument \"x\" (default has type \"B\", argument 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 testDefaultArgumentsWithSubtypes]\nimport typing\nclass A: pass\nclass B(A): pass\n\ndef f(x: 'B' = A()) -> None: # E: Incompatible default for argument \"x\" (default has type \"A\", argument has type \"B\")\n    pass\ndef g(x: 'A' = B()) -> None:\n    pass\n[out]\n\n[case testMultipleDefaultArgumentExpressions]\nimport typing\nclass A: pass\nclass B: pass\n\ndef f(x: 'A' = B(), y: 'B' = B()) -> None: # E: Incompatible default for argument \"x\" (default has type \"B\", argument has type \"A\")\n    pass\ndef h(x: 'A' = A(), y: 'B' = B()) -> None:\n    pass\n[out]\n\n[case testMultipleDefaultArgumentExpressions2]\nimport typing\nclass A: pass\nclass B: pass\n\ndef g(x: 'A' = A(), y: 'B' = A()) -> None: # E: Incompatible default for argument \"y\" (default has type \"A\", argument 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\nfrom types import FunctionType\nclass B: pass\nx: Any\nclass A:\n    f = x # type: ClassVar[Callable[[A], None]]\n    g = x # type: ClassVar[Callable[[A, B], None]]\n    f2: ClassVar[\"FunctionType[[A], None]\"] = x\n    g2: ClassVar[\"FunctionType[[A, B], None]\"] = x\na: A\na.f(a)\na.g(a, B())\na.f(a)\na.g()  # E: Too few arguments\n\na.f2()\na.g2(B())\na.f2(a) # E: Too many arguments\na.g2()  # E: Too few arguments\n[builtins fixtures/tuple.pyi]\n\n[case testMethodWithInvalidMethodAsDataAttribute]\nfrom typing import Any, Callable, ClassVar\nfrom types import FunctionType\nclass B: pass\nx: Any\nclass A:\n    f = x # type: ClassVar[Callable[[], None]]\n    g = x # type: ClassVar[Callable[[B], None]]\n\n    f2: ClassVar['FunctionType[[], None]'] = x\n    g2: ClassVar['FunctionType[[B], None]'] = x\na: A\na.f() # E:\na.g() # E: Too few arguments\n\na.f2() # E: Attribute function \"f2\" with type \"Callable[[], None]\" does not accept self argument\na.g2() # E: Invalid self argument \"A\" to attribute function \"g2\" with type \"Callable[[B], None]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testMethodWithDynamicallyTypedMethodAsDataAttribute]\nfrom typing import Any, Callable, ClassVar\nfrom types import FunctionType\nclass B: pass\nx: Any\nclass A:\n    f = x # type: ClassVar[Callable[[Any], Any]]\n    f2 = x # type: ClassVar[\"FunctionType[[Any], Any]\"]\na: A\na.f() # E: Too few arguments\na.f(a)\n\na.f2()\na.f2(a) # E: Too many arguments\n[builtins fixtures/tuple.pyi]\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\nfrom types import FunctionType\nt = TypeVar('t')\nclass B: pass\nclass C: pass\nx: Any\nclass A(Generic[t]):\n    f = x # type: ClassVar[\"FunctionType[[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[builtins fixtures/tuple.pyi]\n\n[case testPartiallyTypedSelfInMethodDataAttribute]\nfrom typing import Any, TypeVar, Generic, Callable, ClassVar\nfrom types import FunctionType\nt = TypeVar('t')\nclass B: pass\nclass C: pass\nx: Any\nclass A(Generic[t]):\n    f = x # type: ClassVar[\"FunctionType[[A], None]\"]\nab: A[B]\nac: A[C]\nab.f()\nac.f()\n[builtins fixtures/tuple.pyi]\n\n[case testCallableDataAttribute]\nfrom typing import Callable, ClassVar\nfrom types import FunctionType\nclass A:\n    g: ClassVar[\"FunctionType[[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[builtins fixtures/tuple.pyi]\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]\nclass A:\n    def f(self):\n        # type: () -> None\n        def g(x):  # E: Type signature has too few arguments\n            # type: () -> None\n            pass\n\n[case testDeepNestedFunctionWithTooFewArgumentsInTypeComment]\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 arguments\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\nfrom types import FunctionType\ndef dec(x) -> \"FunctionType[[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[builtins fixtures/tuple.pyi]\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\n\n[file b.py]\nimport a\nfrom d import dec\n@dec\ndef g(x: str) -> None: pass\na.f('')\n\n[file d.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef dec(f: T) -> T: return f\n\n[out]\ntmp/b.py:5: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:5: error: Argument 1 to \"g\" has incompatible type \"int\"; expected \"str\"\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)()\n\n[file b.py]\nimport a\nfrom d import dec\n@dec\ndef g(x: int) -> str: pass\na.f(1)()\n\n[file d.py]\nfrom typing import Callable\ndef dec(f: Callable[[int], str]) -> Callable[[int], str]: return f\n\n[out]\ntmp/b.py:5: error: \"str\" not callable\ntmp/a.py:5: error: \"str\" not callable\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)()\n\n[file b.py]\nimport a\nfrom d import dec\n@dec()\ndef g(x: int) -> str: pass\na.f(1)()\n\n[file d.py]\nfrom typing import Callable\ndef dec() -> Callable[[Callable[[int], str]], Callable[[int], str]]: pass\n\n[out]\ntmp/b.py:5: error: \"str\" not callable\ntmp/a.py:5: error: \"str\" not callable\n\n[case testDecoratorWithCallAndFixedReturnTypeInImportCycleAndDecoratorArgs]\nimport a\n\n[file a.py]\nimport b\nfrom d import dec\n@dec(1)\ndef f(x: int) -> str: pass\nb.g(1)()\n\n[file b.py]\nimport a\nfrom d import dec\n@dec(1)\ndef g(x: int) -> str: pass\na.f(1)()\n\n[file d.py]\nfrom typing import Callable\ndef dec(x: str) -> Callable[[Callable[[int], str]], Callable[[int], str]]: pass\n\n[out]\ntmp/b.py:3: error: Argument 1 to \"dec\" has incompatible type \"int\"; expected \"str\"\ntmp/b.py:5: error: \"str\" not callable\ntmp/a.py:3: error: Argument 1 to \"dec\" has incompatible type \"int\"; expected \"str\"\ntmp/a.py:5: error: \"str\" not callable\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: Union[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]\nfrom basedtyping import FunctionType\ndef dec(f) -> FunctionType[[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]\ndef bar() -> None:\n    if False:\n        foo = 1\n    else:\n        def foo(obj): ...\n\ndef baz() -> None:\n    if False:\n        foo: int = 1\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 # N: \"f\" defined here\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 basedtyping import FunctionType\n\ndef dec(f: FunctionType[[], None]) -> FunctionType[[], 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]\n# flags: --python-version 3.9\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: \"1\" is a bare literal and cannot be used here, try 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: The type \"Type[Callable]\" is not generic and 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: The type \"Type[Callable]\" is not generic and 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: The type \"Type[Callable]\" is not generic and not indexable \\\n                                              # E: \"Arg\" gets multiple values for keyword argument \"name\"\n\n\n\n\n\n\n\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 argument \"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 \"Callable[[int, Arg(str, 's')], str]\")\nint_opt_str_fun = iosf\nint_str_fun = iosf\nint_opt_str_fun = isf # E: Incompatible types in assignment (expression has type \"Callable[[Arg(int, 'ii'), Arg(str, 'ss')], str]\", variable has type \"Callable[[int, DefaultArg(str)], str]\")\n\nint_named_str_fun = isf # E: Incompatible types in assignment (expression has type \"Callable[[Arg(int, 'ii'), Arg(str, 'ss')], str]\", variable has type \"Callable[[int, Arg(str, 's')], 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 \"Callable[[NamedArg(int, 'y')], 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]\ndef f(x, y, z): # type: (..., int) -> None\n    pass\n[out]\nmain:1: error: Ellipses cannot accompany other argument types in function type signature\n\n[case testEllipsisWithSomethingBeforeItFails]\ndef f(x, y, z): # type: (int, ...) -> None\n    pass\n[out]\nmain:1: error: Ellipses cannot accompany other argument 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: This usage of this covariant type variable is unsafe as an input parameter.\nmain:5: note: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\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: This usage of this covariant type variable is unsafe as an input parameter.\nmain:6: note: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\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: This usage of this covariant type variable is unsafe as an input parameter.\nmain:8: note: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\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: This usage of this contravariant type variable is unsafe as a return type.\nmain:6: note: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\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 \"Callable[[Arg(Any, 'y')], Any]\", variable has type \"Callable[[Arg(Any, 'x')], 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\nfrom types import FunctionType\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]) -> \"FunctionType[[A, int], None]\": pass\n[builtins fixtures/tuple.pyi]\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 \"Union[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]\nmain:1: note: \"f\" defined here\n\n[case testMagicMethodPositionalOnlyArg]\nclass A(object):\n    def __eq__(self, other) -> bool: return True # We are all equal.  # N: \"__eq__\" of \"A\" defined here\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: \"__eq__\" of \"A\" defined here\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[builtins fixtures/tuple.pyi]\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[builtins fixtures/tuple.pyi]\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[Union[str, int]]\") \\\n      # N: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/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[Union[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, Union[str, int]]\") \\\n      # N: \"dict\" is invariant -- see https://kotlinisland.github.io/basedmypy/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, Union[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[Union[str, int], str]\") \\\n# N: Perhaps you need a type annotation for \"x\"? Suggestion: \"Dict[Union[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[Union[int, float]]\") \\\n      # N: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/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[Union[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[Union[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, Union[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[Union[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)): ...  # E: \"X\" does not return a value (it only ever returns None)\n\nxx: Optional[int] = X(x_in)  # E: \"X\" does not return a value (it only ever returns None)\n[out]\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)): ...   # E: \"X\" does not return a value (it only ever returns None)\n\nxx: Optional[int] = X(x_in)  # E: \"X\" does not return a value (it only ever returns None)\n[out]\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 decorator is @f.setter\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[out]\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[out]\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\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    @property\n    @not_a_decorator\n    def foo(self) -> int:  # E: \"not_a_decorator\" not callable \\\n                           # E: Signature of \"foo\" incompatible with supertype \"Base\" \\\n                           # N:      Superclass: \\\n                           # N:          int \\\n                           # N:      Subclass: \\\n                           # N:          not_a_decorator\n        return 42\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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, x: int) -> str: pass\n    @override\n    @overload\n    def f(self, x: str) -> str: pass\n    def f(self, x: 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, x: int) -> str: pass\n    @override\n    @overload\n    def f(self, x: str) -> str: pass\n    @override\n    def f(self, x: 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, x: int) -> str: pass\n\nclass C(A):\n    def f(self, x: 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, x: 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, y: int) -> str: ...\n    @overload\n    def f(self, y: str) -> str: ...\n    def f(self, y): 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, x: int) -> str: pass\n\nclass C(A, B):\n    @override\n    def f(self, x: int) -> str: pass\n\nclass D(A, B):\n    def f(self, x: 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 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) -> Union[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\", variable has type \"T\")\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 \"Union[Callable[[C], None], Callable[[D], None]]\" \\\n                                                   # N: This violates the Liskov substitution principle \\\n                                                   # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\n        ...\n[builtins fixtures/property.pyi]\n\n[case testNoCrashOnUnpackOverride]\nfrom typing import Unpack\nfrom typing_extensions import TypedDict\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        ...\n[builtins fixtures/tuple.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://kotlinisland.github.io/basedmypy/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 () -> Union[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"
  },
  {
    "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\nfrom types import FunctionType\n\n@total_ordering\nclass Ord:\n    __eq__: ClassVar[\"FunctionType[[Any, object], bool]\"] = lambda self, other: False\n    __lt__: ClassVar['FunctionType[[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: \"foo\" defined here\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 \"Callable[[VarArg(Any), KwArg(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]\n# flags: --python-version 3.8\nimport functools\nfrom typing_extensions import TypeGuard\n\ndef is_str_list(val: list[object]) -> TypeGuard[list[str]]: ...  # E: \"list\" is not subscriptable, use \"typing.List\" instead \\\n                                                                 # E: \"list\" is not subscriptable, use \"typing.List\" instead\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: \"A\" defined here\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 \"Union[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 \"Union[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 \"Callable[[VarArg(Any), KwArg(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_extensions import TypedDict, Unpack\nfrom functools import partial\n\nclass D1(TypedDict, total=False):\n    a1: int\n\ndef fn1(a1: int) -> None: ...  # N: \"fn1\" defined here\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: ...  # N: \"fn2\" defined here\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: ...  # N: \"fn3\" defined here\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: ...  # N: \"fn4\" defined here\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\n[builtins fixtures/dict.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]\n# flags: --python-version 3.9\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              # N: \"T\" of \"f\" is a constrained type variable, it is not generic\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"
  },
  {
    "path": "test-data/unit/check-generic-alias.test",
    "content": "-- Test cases for generic aliases\n\n[case testGenericBuiltinWarning]\n# flags: --python-version 3.8\nt1: list\nt2: list[int]  # E: \"list\" is not subscriptable, use \"typing.List\" instead\nt3: list[str]  # E: \"list\" is not subscriptable, use \"typing.List\" instead\n\nt4: tuple\nt5: tuple[int]  # E: \"tuple\" is not subscriptable, use \"typing.Tuple\" instead\nt6: tuple[int, str]  # E: \"tuple\" is not subscriptable, use \"typing.Tuple\" instead\nt7: tuple[int, ...]  # E: Unexpected \"...\" \\\n                     # E: \"tuple\" is not subscriptable, use \"typing.Tuple\" instead\n\nt8: dict = {}\nt9: dict[int, str]  # E: \"dict\" is not subscriptable, use \"typing.Dict\" instead\n\nt10: type\nt11: type[int]  # E: \"type\" expects no type arguments, but 1 given\n[builtins fixtures/dict.pyi]\n\n\n[case testGenericBuiltinSetWarning]\n# flags: --python-version 3.8\nt1: set\nt2: set[int]  # E: \"set\" is not subscriptable, use \"typing.Set\" instead\n[builtins fixtures/set.pyi]\n\n\n[case testGenericCollectionsWarning]\n# flags: --python-version 3.8\nimport collections\n\nt01: collections.deque\nt02: collections.deque[int]  # E: \"deque\" is not subscriptable, use \"typing.Deque\" instead\nt03: collections.defaultdict\nt04: collections.defaultdict[int, str]  # E: \"defaultdict\" is not subscriptable, use \"typing.DefaultDict\" instead\nt05: collections.OrderedDict\nt06: collections.OrderedDict[int, str]\nt07: collections.Counter\nt08: collections.Counter[int]  # E: \"Counter\" is not subscriptable, use \"typing.Counter\" instead\nt09: collections.ChainMap\nt10: collections.ChainMap[int, str]  # E: \"ChainMap\" is not subscriptable, use \"typing.ChainMap\" instead\n\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]\n# flags: --python-version 3.9\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]\n# flags: --python-version 3.9\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]\n# flags: --python-version 3.9\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]\n# flags: --python-version 3.9\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\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]\n# flags: --python-version 3.9\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\nfrom typing import Tuple\nt10: Tuple[int, ...] = t09\n[builtins fixtures/tuple.pyi]\n\n[case testTypeAliasWithBuiltinTuple]\n# flags: --python-version 3.9\n\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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\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 \"Union[U, V, W]\" of type variable \"T\" has no attribute \"a\"\nmain:13: error: Item \"W\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"a\"\nmain:14: error: Item \"U\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"b\"\nmain:14: error: Item \"W\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"b\"\nmain:15: error: Item \"U\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"c\"\nmain:15: error: Item \"V\" of the upper bound \"Union[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 \"Union[U, V, W]\" of type variable \"T\" has no attribute \"a\"\nmain:14: error: Item \"W\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"a\"\nmain:15: error: Item \"U\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"b\"\nmain:15: error: Item \"W\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"b\"\nmain:16: error: Item \"U\" of the upper bound \"Union[U, V, W]\" of type variable \"T\" has no attribute \"c\"\nmain:16: error: Item \"V\" of the upper bound \"Union[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: Keywords must be strings\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 = None # type: 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]\n# flags: --python-version 3.8\nimport types\ntype[int] # this was crashing, see #2302 (comment)  # E: The type \"Type[type]\" is not generic and not indexable\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 type argument 1 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: D[int, str]\nreveal_type(x)\ny: 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 \"Union[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: UNode[int]\n\nx + 1 # E: Unsupported left operand type for + (\"Node[int]\") \\\n      # N: Left operand is of type \"Union[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 \"Union[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 \"Union[str, Node[int]]\")\n\nif not isinstance(s, str):\n    s.x = 1\n\nz: TNode # Same as TNode[Any]\nz.x\nz.foo() # E: Item \"Node[int]\" of \"Union[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 type argument 1 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: \"T\" of \"fun2\" is a constrained type variable, it is not generic\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 type argument 1 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 \"Union[builtins.int, None]\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n\nU[int]  # E: Type application targets a non-generic function or class\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n    x: b\n    reveal_type(x)  # N: Revealed type is \"Union[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 + (\"Type[Callable]\")\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 = None # type: 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:9:8: note: \"T\" of \"A\" is a constrained type variable, it is not generic\nmain:9:10: error: Value of type variable \"T\" of \"A\" cannot be \"str\"\nmain:9:10: note: \"T\" of \"A\" is a constrained type variable, it is not generic\nmain:13:1: error: Value of type variable \"T\" of \"SameA\" cannot be \"str\"\nmain:13:1: note: \"T\" of \"SameA\" is a constrained type variable, it is not generic\n\n[case testGenericTypeAliasesIgnoredPotentialAlias]\nclass A: ...\nBad = A[int] # type: ignore\n\nreveal_type(Bad) # N: Revealed type is \"Any\"\n[out]\n\n[case testNoSubscriptionOfBuiltinAliases]\n# flags: --python-version 3.8\nfrom typing import List, TypeVar\n\nlist[int]() # E: \"list\" is not subscriptable\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]() # E: \"list\" is not subscriptable\n\n#check that error is reported only once, and type is still stored\nT = TypeVar('T')\nBadGenList = list[T] # E: \"list\" is not subscriptable\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]\", variable has type \"Callable[[A], A]\")\n\ny2 = f2\nif int():\n    y2 = f2\nif int():\n    y2 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A], A]\", variable has type \"Callable[[A], B]\")\nif int():\n    y2 = f3 # E: Incompatible types in assignment (expression has type \"Callable[[B], B]\", variable has type \"Callable[[A], B]\")\nif int():\n    y2 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[int], A]\", variable has type \"Callable[[A], 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], A]\", variable has type \"Callable[[int], A]\")\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]\", variable has type \"Callable[[A], A]\")\n        y1 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[A], T]\", variable has type \"Callable[[A], A]\")\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], A]\", variable has type \"Callable[[A], B]\")\n\n    y3 = f3\n    if int():\n        y3 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A], A]\", variable has type \"Callable[[T], A]\")\n        y3 = f2\n        y3 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[A], T]\", variable has type \"Callable[[T], A]\")\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], A]\", variable has type \"Callable[[A], T]\")\n        y4 = f2\n        y4 = f3 # E: Incompatible types in assignment (expression has type \"Callable[[T], A]\", variable has type \"Callable[[A], 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\"  # 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: 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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\nfrom typing import TypeVar, Callable, List\nfrom types import FunctionType\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef mix(fs: List[\"FunctionType[[S], T]\"]) -> \"FunctionType[[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`11) -> builtins.list[S`11]\"\nreveal_type(mix([id, id, id]))  # N: Revealed type is \"def [S] (S`13) -> builtins.list[S`13]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCurry]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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] (Union[T`1, None]) -> Union[T`1, None]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericSplitOrder]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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 testInferenceAgainstGenericEllipsisSelfSpecialCase]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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`12) -> S`12\"\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`20) -> builtins.list[S`20]\"\nreveal_type(dec4(lambda x: x))  # N: Revealed type is \"def [T] (builtins.list[T`24]) -> T`24\"\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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"
  },
  {
    "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]\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]\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\"\ntmp/m.py:2: note: \"f\" defined here\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 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]\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 mod1, 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 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 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 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.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, 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[case testIncrementalWithSilentImportsAndIgnore]\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 c]\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[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]\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 \"Union[builtins.int, builtins.str]\"\ntmp/a.py:5: note: Revealed type is \"Union[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]\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, mod2, mod1]\n[stale mod3, mod2]\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, mod2, mod1]\n[stale 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, mod2, mod1]\n[stale mod4, mod3, mod2]\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 = None  # type: A\nclass Y:\n    attr = None  # type: 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 mypy_extensions import TypedDict\nclass C:\n    def f(self) -> None:\n        A = TypedDict('A', {'x': int, 'y': int})\n[builtins fixtures/dict.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 mypy_extensions 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[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 mypy_extensions 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[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 mypy_extensions import TypedDict\nfrom typing import NewType, NamedTuple\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[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 = None  # type: 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 = None  # type: ClassVar[int]\n[file m.py.2]\nclass A:\n    x = None  # type: 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 = None  # type: 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 mypy_extensions import TypedDict\nA = TypedDict('A', {'x': int, 'y': str})\nx: A\n[builtins fixtures/dict.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[out2]\ntmp/n.py:1: error: Cannot find implementation or library stub for module named \"m\"\ntmp/n.py:1: note: See https://kotlinisland.github.io/basedmypy/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]\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[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: can't read file 'tmp/nonexistent.py': No such file or directory\n-- '\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 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, Dict\nfrom mypy_extensions import TypedDict\n\nNT = NewType('NT', N) # type: ignore\nclass N(TypedDict):\n    x: A\nA = Dict[str, int]\n[builtins fixtures/dict.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 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 m.a, m.b]\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 \"Optional[int]\"\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`1, other: _AT`1) -> builtins.bool\"\nmain:4: note: Revealed type is \"def [_AT] (self: _AT`2, other: _AT`2) -> builtins.bool\"\nmain:5: note: Revealed type is \"def [_AT] (self: _AT`3, other: _AT`3) -> builtins.bool\"\nmain:6: note: Revealed type is \"def [_AT] (self: _AT`4, other: _AT`4) -> 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\nclass A:\n    a: int\n\n[file b.py]\nimport attrs\n@attrs.define\nclass B:\n    b: str\n\n[file c.py]\nfrom a import A\nfrom b import B\nimport attrs\n@attrs.define\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: Union[builtins.int, None]) -> a.a.A\"\n[out2]\nmain:2: note: Revealed type is \"def (x: Union[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 \"Optional[str]\"\ntmp/a.py:6: error: Argument 2 to \"A\" has incompatible type \"int\"; expected \"Optional[str]\"\ntmp/a.py:7: error: Argument 5 to \"B\" has incompatible type \"int\"; expected \"Optional[str]\"\ntmp/a.py:10: error: Argument 2 to \"SubBase\" has incompatible type \"int\"; expected \"Optional[str]\"\ntmp/a.py:13: error: Argument 2 to \"AA\" has incompatible type \"int\"; expected \"Optional[str]\"\ntmp/a.py:14: error: Argument 5 to \"BB\" has incompatible type \"int\"; expected \"Optional[str]\"\ntmp/a.py:17: error: Argument 2 to \"SubAA\" has incompatible type \"int\"; expected \"Optional[str]\"\ntmp/a.py:18: error: Argument 5 to \"SubBB\" has incompatible type \"int\"; expected \"Optional[str]\"\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://kotlinisland.github.io/basedmypy/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 \"Optional[int]\"\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://kotlinisland.github.io/basedmypy/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 mypy_extensions 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[typing fixtures/typing-medium.pyi]\n[builtins fixtures/dict.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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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 mypy_extensions import TypedDict\nfrom lib import A\nB = TypedDict('B', {'x': A})\n[builtins fixtures/dict.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_extensions import Literal\na = 1\n[file mod.py.2]\nfrom typing_extensions 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]\ntmp/a.py:3: error: Cannot determine type of \"foo\"\ntmp/a.py:4: error: Cannot determine type of \"foo\"\n[out2]\ntmp/a.py:3: error: Cannot determine type of \"foo\"\ntmp/a.py:4: error: Cannot determine type of \"foo\"\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.A & 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 \"c.B & 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 \"builtins.tuple[builtins.int, ...] & 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.A & a.B\"\n[out2]\ntmp/c.py:2: note: Revealed type is \"a.A & 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 \"a.A & a.B\"\n[out2]\ntmp/c.py:2: note: Revealed type is \"a.A & 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.A & 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.A & a.B\"\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: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: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\nfrom typing_extensions import TypedDict, 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[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[Union[Tuple[Union[..., None], builtins.int, fallback=b.M], None], builtins.int, fallback=a.N]\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", variable has type \"int\")\ntmp/c.py:7: note: Revealed type is \"Tuple[Union[Tuple[Union[..., 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[Union[Tuple[Union[..., None], builtins.int, fallback=b.M], None], builtins.int, fallback=a.N]\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", 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[Union[Tuple[Union[..., None], builtins.int], None], builtins.int]\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", 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': Union[TypedDict('b.M', {'r': Union[..., None], 'x': builtins.int}), None], 'x': builtins.int})\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", variable has type \"int\")\ntmp/c.py:7: note: Revealed type is \"TypedDict('a.N', {'r': Union[TypedDict('b.M', {'r': Union[..., 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_extensions import Unpack, TypedDict\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[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 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 types1 import C\n\n[file types1.py]\nimport pb1\nC = pb1.C\n[file types1.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 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 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 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_extensions 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[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: --nonlocal-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\nfrom typing_extensions import 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[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_extensions import TypedDict\nCounts = TypedDict(\"Counts\", {k: int for k in \"abc\"})  # type: ignore\n[builtins fixtures/dict.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_extensions import TypedDict\ndef test() -> None:\n    Counts = TypedDict(\"Counts\", {k: int for k in \"abc\"})  # type: ignore\n[builtins fixtures/dict.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_extensions 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[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\n[case testIncrementalFunctoolsPartial]\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 \"Callable[[VarArg(Any), KwArg(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/partial.py:4: note: \"foo\" defined here\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\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, 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, 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"
  },
  {
    "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 \"Optional[A]\"\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: List[List[object]]\naab: List[List[B]]\nab: List[B]\nb: B\no: 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 = None # type: 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]\n# flags: --new-type-inference\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 \"Union[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\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 \"Union[List[A], List[B]]\", variable has type \"List[A]\")\nif int():\n    b = b or c # E: Incompatible types in assignment (expression has type \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[builtins.list[builtins.int], None]\"\n[builtins fixtures/list.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: \"get\" of \"M\" does not return a value (it only ever returns None) \\\n                           # 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 type argument 1 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 \"Union[builtins.list[builtins.str], Any, builtins.list[Union[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 \"Union[typing.Iterable[builtins.str], Any, builtins.list[Union[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 \"Union[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"
  },
  {
    "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]\nB: Type[Union[Foo, Bar]]\nC: Union[Type[Foo], Type[Bar]]\nD: Type[Union[Foo, Baz]]\nE: Type[Union[Foo, Spam]]\nF: Type[Eggs]\nG: Type[Union[Foo, Eggs]]\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 \"Union[builtins.int, builtins.str]\"\n\nfor var3 in [m, n, o, p, q, r]:\n    reveal_type(var3)  # N: Revealed type is \"Union[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 \"Union[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 \"Union[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 type argument 1 of \"f\"\nf(ab, ao) # E: Cannot infer type argument 1 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: A\no: 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]\" \\\n                 # N: \"AnyStr\" of \"f\" is a constrained type variable, it is not generic\nf(1)\nf(1, 'foo')\nf(1, 'foo', b'bar') # E: Value of type variable \"AnyStr\" of \"f\" cannot be \"Sequence[object]\" \\\n                    # N: \"AnyStr\" of \"f\" is a constrained type variable, it is not generic\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 \"Union[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]], List[Union[T, int]]]\", variable has type \"Callable[[S, List[T]], List[Union[T, 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 \"Callable[[NamedArg(int, 'x')], int]\"; expected \"Callable[[NamedArg(int, 'y')], 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 [(None, None)]:\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_extensions 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 \"Union[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\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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 argument \"a\" (default has type \"Callable[[VarArg(Any), KwArg(Any)], int]\", argument 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 \"Union[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) -> Union[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 \"Union[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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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: --nonlocal-partial-types\nmap = {}\ndef add() -> None:\n    map[1] = 2\n[builtins fixtures/dict.pyi]\n\n[case testInferDictInitializedToEmptyAndUpdatedFromMethodUnannotated]\n# flags: --nonlocal-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] __init__(self) -> List[T] \\\n                              # N:     def [T] __init__(self, 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 \"Union[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: --nonlocal-partial-types\nclass C:\n    a = None\n    def __init__(self) -> None:\n        self.a = 1\nreveal_type(C().a)  # N: Revealed type is \"Union[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 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: --nonlocal-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]\na = None\ndef f():\n    global a\n    a = 42\n[out]\n\n[case testGlobalInitializedToNoneSetFromMethod]\na = None\nclass C:\n    def m(self):\n        global a\n        a = 42\n[out]\n\n-- More partial type errors\n-- ------------------------\n\n[case testPartialTypeErrorSpecialCase1]\n# flags: --nonlocal-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: --nonlocal-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\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\nfrom types import FunctionType\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]) -> \"FunctionType[[A, int], T]\": pass\n[out]\n[builtins fixtures/tuple.pyi]\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 \"Union[int, str, Tuple[Any, ...]]\"; expected \"Union[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: \"0\" is a bare literal and cannot be used here, try Literal[0] instead?\n\n[case testNoCrashOnPartialMember]\n# flags: --nonlocal-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[out]\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[out]\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\nif int():\n    (x,) = f()\n[builtins fixtures/tuple.pyi]\n[out]\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[out]\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[out]\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 # E: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\n\ndef f() -> None:\n    global x\n    x = 1\n\n# TODO: \"Any\" could be a better type here to avoid multiple error messages\nreveal_type(x) # N: Revealed type is \"None\"\n\n[case testLocalPartialTypesWithGlobalInitializedToNone2]\n# flags: --local-partial-types\nx = None # E: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\n\ndef f():\n    global x\n    x = 1\n\n# TODO: \"Any\" could be a better type here to avoid multiple error messages\nreveal_type(x) # N: Revealed type is \"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 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nx = ''\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n\n[case testLocalPartialTypesWithGlobalInitializedToNoneStrictOptional]\n# flags: --local-partial-types\nx = None\n\ndef f() -> None:\n    global x\n    x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Optional[str]\")\n\nx = ''\ndef g() -> None:\n    reveal_type(x) # N: Revealed type is \"Union[builtins.str, 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 \"builtins.str\"\n\n# TODO: This should probably be 'builtins.str', since there could be a\n#     call that causes a non-None value to be assigned\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 # E: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\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 \"Union[__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  # E: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\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  # E: Need type annotation for \"a\" (hint: \"a: Optional[<type>] = ...\")\n\n    def f(self, x) -> None:\n        C.a.y  # E: Item \"None\" of \"Optional[Any]\" has no attribute \"y\"\n\n[case testLocalPartialTypesAccessPartialNoneAttribute2]\n# flags: --local-partial-types\nclass C:\n    a = None  # E: Need type annotation for \"a\" (hint: \"a: Optional[<type>] = ...\")\n\n    def f(self, x) -> None:\n        self.a.y  # E: Item \"None\" of \"Optional[Any]\" has no attribute \"y\"\n\n-- Special case for assignment to '_'\n-- ----------------------------------\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 \"Union[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 \"Union[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 testSuggestPep604AnnotationForPartialNone]\n# flags: --local-partial-types --python-version 3.10\nx = None # E: Need type annotation for \"x\" (hint: \"x: <type> | 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[Union[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)\nclass A:\n    x = 42\n[file b.py]\nimport a\nreveal_type(a.A.x)\nclass B:\n    x = 42\n[out]\ntmp/b.py:2: note: Revealed type is \"builtins.int\"\ntmp/a.py:2: note: Revealed type is \"builtins.int\"\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 \"Callable[[NamedArg(Never, 'x')], 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 \"Callable[[NamedArg(str, 'x')], 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 \"Callable[[KwArg(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 \"Callable[[VarArg(str)], None]\"; expected \"Call[Never]\" \\\n                   # N: \"Call[Never].__call__\" has type \"Callable[[NamedArg(Never, 'x')], 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 type argument 1 of \"f\"\nf([\"no\"], empty)  # E: Cannot infer type argument 1 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\nempty: Dict[NoReturn, NoReturn]\ndef bar() -> Union[Dict[str, Any], Dict[int, Any]]:\n    return empty\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[Union[S`1, builtins.str]]\"\nreveal_type(func(42))  # N: Revealed type is \"builtins.list[Union[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) -> Union[S`4, builtins.str]\"\nreveal_type(func2(42))  # N: Revealed type is \"Union[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"
  },
  {
    "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 parameters 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 parameters 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 parameters 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 parameters 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 parameters 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 parameters 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 parameters 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 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"
  },
  {
    "path": "test-data/unit/check-isinstance.test",
    "content": "[case testForcedAssignment]\nx: 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]\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]\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]\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 \"Union[builtins.int, builtins.str]\"\n        x[1]  # E: Value of type \"Union[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 \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n    if isinstance(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.list[Any]]\"\n        x[1]\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testClassAttributeInitialization]\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]\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]\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]\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]\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    x.z          # E: \"A\" has no attribute \"z\"\n    x.y\n\n[case testSingleMultiAssignment]\nx = 'a'\n(x,) = ('a',)\n\n[case testUnionMultiAssignment]\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]\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]\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]\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 \"Union[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]\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]\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]\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()\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]\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]\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]\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]\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]\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]\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\n    x.b\n\n[case testUnionTryFinally6]\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]\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 \"Union[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 \"Union[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 \"Union[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 \"Union[List[int], List[str], int]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionListIsinstance2]\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]\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 \"Union[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]\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]\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]\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]\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 = None  # type: 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 \"Union[int, str]\"\n        z = h.pet.paws + 'a' # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                             # N: Left operand is of type \"Union[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]\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]\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: Union[A, B, C]\n\nif isinstance(v, (B, C)):\n    v.method2(123)\n    v.method3('xyz') # E: Item \"B\" of \"Union[B, C]\" has no attribute \"method3\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceNeverWidens]\nfrom typing import Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\na: A\nassert isinstance(a, (A, B))\nreveal_type(a)  # N: Revealed type is \"__main__.A\"\n\nb: Union[A, B]\nassert isinstance(b, (A, B, C))\nreveal_type(b)  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testMemberAssignmentChanges]\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 \"Union[int, str]\"\npet.paws = 'a'\npet.paws + 'a'\npet.paws = 1\npet.paws + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceSubClassMemberHard]\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 = None  # type: 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 \"Union[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]\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]\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 \"Union[int, str]\"\n\nfoo()\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceThreeUnion]\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 \"Union[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 \"Union[int, str, List[int]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceThreeUnion2]\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 \"Union[int, str, List[int]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceThreeUnion3]\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):\n        x + 'a'\n        break\n    x + [1]           # These lines aren't reached because x was an int\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 \"Union[int, str, List[int]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRemovingTypeRepeatedly]\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 \"Union[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 \"Union[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 \"Union[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 \"Union[int, str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyRepeatedly]\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 \"Union[int, str]\"\nx + 'a'   # E: Unsupported operand types for + (\"int\" and \"str\") \\\n          # N: Left operand is of type \"Union[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 \"Union[int, str]\"\nx + 'a'   # E: Unsupported operand types for + (\"int\" and \"str\") \\\n          # N: Left operand is of type \"Union[int, str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoop]\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 \"Union[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 \"Union[int, str]\"\n      x = 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoop2]\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 \"Union[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 \"Union[int, str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoop3]\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 \"Union[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 \"Union[int, str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoopWhile4]\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 \"Union[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 \"Union[int, str]\"\n    x = 'a'\nx + 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoopFor4]\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 \"Union[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 \"Union[int, str]\"\n    x = 'a'\nx + 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyNestedLoop]\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 \"Union[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 \"Union[int, str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoopLong]\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 \"Union[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 \"Union[str, A]\" has no attribute \"a\"\n          x = 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testWhileExitCondition1]\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]\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 \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testWhileLinkedList]\nfrom typing import Union\nLinkedList = Union['Cons', 'Nil']\nclass Nil: pass\nclass Cons:\n    tail = None  # type: 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]\ndef foo() -> int:\n    return 1 and 2\n    return 'a'\n[case testCastIsinstance]\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]\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\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableCode2]\nx = 1\nwhile bool():\n    try:\n        pass\n    except:\n        continue\n    else:\n        continue\n    x + 'a'\n[builtins fixtures/isinstance.pyi]\n\n[case testUnreachableWhileTrue]\ndef f(x: int) -> None:\n    while True:\n        if x:\n            return\n    1()\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableAssertFalse]\ndef f() -> None:\n    assert False\n    1()\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableAssertFalse2]\ndef f() -> None:\n    # The old parser doesn't understand the syntax below\n    assert False, \"hi\"\n    1()\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableReturnOrAssertFalse]\ndef f(x: int) -> int:\n    if x:\n        return x\n    else:\n        assert False\n    1()\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableTryExcept]\ndef f() -> None:\n    try:\n        f()\n        return\n    except BaseException:\n        return\n    1()\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableTryExceptElse]\ndef f() -> None:\n    try:\n        f()\n    except BaseException:\n        return\n    else:\n        return\n    1()\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableTryReturnFinally1]\ndef f() -> None:\n    try:\n        return\n    finally:\n        pass\n    1()\n\n[case testUnreachableTryReturnFinally2]\ndef f() -> None:\n    try:\n        pass\n    finally:\n        return\n    1()\n\n[case testUnreachableTryReturnExceptRaise]\ndef f() -> None:\n    try:\n        return\n    except:\n        raise\n    1()\n\n[case testUnreachableReturnLambda]\nfrom typing import Callable\ndef g(t: Callable[[int], int]) -> int: pass\ndef f() -> int:\n    return g(lambda x: x)\n    1()\n\n[case testIsinstanceAnd]\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]\nclass A:\n    pass\n\nclass B(A):\n    flag = 1\n\nx: 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]\nclass A:\n    pass\n\nclass B(A):\n    flag = 1\n\nx: 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]\nclass A: pass\n\nclass B(A):\n    flag = 1\n\nclass C(A):\n    glaf = 1\n\nx: A\ny: 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]\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):\n    1() # type checking skipped\nif isinstance(y, int) and isinstance(x, B):\n    1() # type checking skipped\nif isinstance(y, int) and y > 42:\n    1() # type checking skipped\n[builtins fixtures/isinstancelist.pyi]\n\n[case testReturnWithCallExprAndIsinstance]\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]\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]\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]\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 \"Optional[int]\")\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceWithOverlappingUnionType]\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]\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]\nfrom typing import Union\n\nclass FloatLike: pass\nclass IntLike(FloatLike): pass\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\ndef f2(x: Union[FloatLike, IntLike]) -> None:\n    # ...but not regular subtyping relationships\n    if isinstance(x, FloatLike):\n        reveal_type(x)  # N: Revealed type is \"Union[__main__.FloatLike, __main__.IntLike]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOfSuperclass]\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)  # unreachable\n    x = A()\nreveal_type(x)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOfNonoverlapping]\nclass A: pass\nclass B: pass\n\nx = B()\nif isinstance(x, A):\n    reveal_type(x)  # N: Revealed type is \"__main__.B & __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]\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]\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]\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]\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 \"Union[builtins.list[builtins.int], builtins.str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceOrIsinstance]\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 \"Union[__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):\n    reveal_type(x2) # N: Revealed type is \"__main__.A\"\n    f = x2.flag # E: \"A\" has no attribute \"flag\"\nelse:\n    # unreachable\n    1()\nreveal_type(x2) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testComprehensionIsInstance]\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]\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]\nclass A:\n    a = None  # type: 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]\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 \"Union[int, str]\"\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithBoundedType]\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 \"Union[builtins.int, __main__.A]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    reveal_type(x) # N: Revealed type is \"Union[builtins.int, __main__.A]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithEmtpy2ndArg]\nfrom typing import Union\n\ndef f(x: Union[int, str]) -> None:\n    if isinstance(x, ()):\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithTypeObject]\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 \"Union[builtins.int, __main__.A]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclassUnreachable]\nfrom typing import Type, Sequence, Union\n\nx: Type[str]\nif issubclass(x, int):\n    reveal_type(x)  # unreachable block\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 \"Union[Type[__main__.Y], Type[__main__.Z]]\"\nelse:\n    reveal_type(a)  # unreachable block\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclasDestructuringUnions1]\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 \"Union[Type[builtins.int], Type[builtins.str]]\"\n        reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n        x()[1]  # E: Value of type \"Union[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 \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n    if issubclass(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.str], Type[builtins.list[Any]]]\"\n        reveal_type(x())  # N: Revealed type is \"Union[builtins.str, builtins.list[Any]]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclasDestructuringUnions2]\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 \"Union[Type[builtins.int], Type[builtins.str]]\"\n        reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n        x()[1]  # E: Value of type \"Union[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 \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n    if issubclass(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.str], Type[builtins.list[Any]]]\"\n        reveal_type(x())  # N: Revealed type is \"Union[builtins.str, builtins.list[Any]]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclasDestructuringUnions3]\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 \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n    if issubclass(x, (str, (int,))):\n        reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.int], Type[builtins.str]]\"\n        reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n        x()[1]  # E: Value of type \"Union[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 \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n    if issubclass(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.str], Type[builtins.list[Any]]]\"\n        reveal_type(x())  # N: Revealed type is \"Union[builtins.str, builtins.list[Any]]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"Union[Type[builtins.int], Type[builtins.str], Type[builtins.list[Any]]]\"\n    reveal_type(x())  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.list[Any]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclass]\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]\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]\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 \"Union[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]\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 testIsinstanceTypeArgs]\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]\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]\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]\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\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]\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 \"__main__.FooMetaclass & Type[__main__.Bar]\"\nif issubclass(fm, Baz):\n    reveal_type(fm)  # N: Revealed type is \"Never\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndNarrowTypeVariable]\nfrom typing import TypeVar\n\nclass A: pass\nclass B(A): pass\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 \"__main__.B\"\n    else:\n        reveal_type(x) # N: Revealed type is \"T`-1\"\n    reveal_type(x) # N: Revealed type is \"T`-1\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndNegativeNarrowTypeVariableWithUnionBound]\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 \"__main__.A\"\n        x.a\n        x.b                 # E: \"A\" has no attribute \"b\"\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 \"Union[A, B]\" of type variable \"T\" has no attribute \"a\"\n    x.b                     # E: Item \"A\" of the upper bound \"Union[A, B]\" of type variable \"T\" has no attribute \"b\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndTypeType]\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)  # Unreachable\n    reveal_type(x) # N: Revealed type is \"Type[builtins.int]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceVariableSubstitution]\nT = (int, str)\nU = (list, T)\nx: object\n\nif isinstance(x, T):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\nif isinstance(x, U):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.list[Any], builtins.int, builtins.str]\"\n\nif isinstance(x, (set, (list, T))):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.set[Any], builtins.list[Any], builtins.int, builtins.str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTooFewArgs]\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]\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]\nisinstance(1, 1, 1) # E: Too many arguments for \"isinstance\" \\\n         # E: Argument 2 to \"isinstance\" has incompatible type \"int\"; expected \"Union[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 testIsinstanceNarrowAny]\nfrom typing import Any\n\ndef narrow_any_to_str_then_reassign_to_int() -> None:\n    v = 1 # type: Any\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\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowTypeAfterInList]\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 \"Union[builtins.int, None]\"\nif y not in x:\n    reveal_type(y)  # N: Revealed type is \"Union[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]\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 \"Union[builtins.int, None]\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInListNonOverlapping]\nfrom typing import List, Optional\n\nx: List[str]\ny: Optional[int]\n\nif y in x:\n    reveal_type(y)  # N: Revealed type is \"Union[builtins.int, None]\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInListNested]\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) # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInTuple]\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 \"Union[__main__.B, None]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNarrowTypeAfterInNamedTuple]\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 \"Union[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]\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 \"Union[builtins.str, None]\"\nif y not in x:\n    reveal_type(y) # N: Revealed type is \"Union[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]\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 \"Union[builtins.int, None]\"\nelse:\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, None]\"\n\nif y not in z:\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, None]\"\nelse:\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, None]\"\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInUserDefined]\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 \"Union[builtins.int, None]\"\nelse:\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, None]\"\nif y not in C():\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, None]\"\nelse:\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, None]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInSet]\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 \"Union[builtins.str, None]\"\nif y not in s:\n    reveal_type(y) # N: Revealed type is \"Union[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]\nfrom typing import Optional\nfrom mypy_extensions import 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[typing fixtures/typing-typeddict.pyi]\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testIsinstanceWidensWithAnyArg]\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]\nfrom typing import Any, Union\nclass A: ...\nB: Any\nx: Union[A, B]\nreveal_type(x)  # N: Revealed type is \"Union[__main__.A, Any]\"\nassert isinstance(x, B)\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceIgnoredImport]\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 \"Union[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]\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]\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 \"builtins.str & __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\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 \"builtins.str & __main__.A\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNoneCheckDoesNotMakeTypeVarOptional]\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\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\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 \"Union[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 \"Union[builtins.list[builtins.str], builtins.list[builtins.int], None]\"\n    assert isinstance(x, list)\n    reveal_type(x)                  # N: Revealed type is \"Union[builtins.list[builtins.str], builtins.list[builtins.int]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testNoneAndGenericTypesOverlapStrictOptional]\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 \"Union[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 \"Union[builtins.list[builtins.str], builtins.list[builtins.int], None]\"\n    assert isinstance(x, list)\n    reveal_type(x)                  # N: Revealed type is \"Union[builtins.list[builtins.str], builtins.list[builtins.int]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithStarExpression]\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 \"Union[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 \"Union[builtins.list[builtins.str], builtins.str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithStarExpressionAndVariable]\nfrom typing import Union\n\ndef f(var: Union[int, str]) -> None:\n    reveal_type(var)  # N: Revealed type is \"Union[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]\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]\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__.A & __main__.B\"\n    if isinstance(x, C):\n        reveal_type(x)       # N: Revealed type is \"__main__.A & __main__.B & __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: \"A & B & C\" has no attribute \"bad\"\n    else:\n        reveal_type(x)       # N: Revealed type is \"__main__.A & __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__.A & __main__.B\"\n    if isinstance(x, A):\n        reveal_type(x)  # N: Revealed type is \"__main__.A & __main__.B\"\n    if isinstance(x, B):\n        reveal_type(x)  # N: Revealed type is \"__main__.A & __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 & 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__.C & __main__.B\"\n    if isinstance(y, A):  # E: Subclass of \"C & A\" cannot exist: would have incompatible method signatures \\\n                          # E: Subclass of \"B & 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_extensions 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 & 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__.B & __main__.A1\"\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__.B & __main__.A1\"\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 \"Union[__main__.B & __main__.A1, __main__.B & __main__.A2]\"\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] & 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__.A[__main__.Parent] & __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__.A[__main__.Child] & __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__.B & __main__.A\"\n        if isinstance(x, B):\n            reveal_type(x)  # N: Revealed type is \"__main__.A & __main__.B\" \\\n                            # N: Revealed type is \"__main__.B & __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 A and 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 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__.A & __main__.B\"\n    accept_a(var)\n    accept_b(var)\n    accept_concrete(var)  # E: Argument 1 to \"accept_concrete\" has incompatible type \"A & 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__.A & __main__.B\"\n\ny: A\nassert isinstance(y, B)\nreveal_type(y)      # N: Revealed type is \"__main__.A & __main__.B\"\n\nx = y\nreveal_type(x)      # N: Revealed type is \"__main__.A & __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 \"Union[__main__.A & __main__.B, __main__.A & __main__.C]\"\n\nv2: Union[A, B]\nif isinstance(v2, C):\n    reveal_type(v2)  # N: Revealed type is \"Union[__main__.A & __main__.C, __main__.B & __main__.C]\"\n\nv3: Union[A, B]\nif isinstance(v3, (C, D)):\n    reveal_type(v3)  # N: Revealed type is \"Union[__main__.A & __main__.C, __main__.A & __main__.D, __main__.B & __main__.C, __main__.B & __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__.A & 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 & 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__.Concrete & __main__.Ambiguous\"\n    reveal_type(foo.x)  # N: Revealed type is \"builtins.int & Any\"\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__.A] & Type[__main__.B]\"\n    if issubclass(x, C):  # E: Subclass of \"A & C\" cannot exist: would have incompatible method signatures \\\n                          # E: Subclass of \"B & 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__.A] & Type[__main__.B]\"\nelse:\n    reveal_type(x)        # N: Revealed type is \"Type[__main__.A]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeEqualsCheck]\nfrom typing import Any\n\ny: Any\nif type(y) == int:\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n\n\n[case testMultipleTypeEqualsCheck]\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\n[case testTypeEqualsCheckUsingIs]\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 testTypeEqualsNarrowingUnionWithElse]\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 \"Union[builtins.int, builtins.str]\"\n\n[case testTypeEqualsMultipleTypesShouldntNarrow]\n# make sure we don't do any narrowing if there are multiple types being compared\n\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) == int == str:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\n# mypy thinks int isn't defined unless we include this\n[builtins fixtures/primitives.pyi]\n\n[case testTypeNotEqualsCheck]\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) != int:\n    reveal_type(x)  # N: Revealed type is \"Union[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]\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) is not int:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[case testNarrowInElseCaseIfFinal]\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[case testNarrowInIfCaseIfFinalUsingIsNot]\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 testHasAttrExistingAttribute]\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]\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]\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]\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]\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]\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]\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]\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]\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]\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 \"Union[__main__.A, __main__.B]\"\n    reveal_type(xu.x)  # N: Revealed type is \"Union[Any, builtins.int]\"\nelse:\n    reveal_type(xu)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeOuterUnion]\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]\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]\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]\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]\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]\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 testTypeIsntLostAfterNarrowing]\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 \"Union[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 \"Union[builtins.bool, builtins.str]\"\n[builtins fixtures/isinstance.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 \"Optional[A]\"\nf(b=A()) # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"Optional[B]\"\nf(c=B()) # E: Argument \"c\" to \"f\" has incompatible type \"B\"; expected \"Optional[C]\"\nf(b=B(), c=A()) # E: Argument \"c\" to \"f\" has incompatible type \"A\"; expected \"Optional[C]\"\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 # N: \"f\" defined here\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 \"Optional[B]\"\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 \"Optional[B]\"\nf(*a, b=A())  # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"Optional[B]\"\n[builtins fixtures/list.pyi]\n\n[case testCallingDynamicallyTypedFunctionWithKeywordArgs]\nimport typing\nclass A: pass\ndef f(x, y=A()): pass  # N: \"f\" defined here\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: Keywords must be strings\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)\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: Keywords must be strings\nf(**A())       # E: Argument after ** must be a mapping, not \"A\"\nkwargs: Optional[Any]\nf(**kwargs)    # E: Argument after ** must be a mapping, not \"Optional[Any]\"\n\ndef g(a: int) -> None: pass\ng(a=1, **4)  # 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: \"f\" defined here\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: \"f\" of \"A\" defined here\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: Keywords must be strings\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: \"B\" defined here\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]\n-- Note that the messages appear \"out of order\" because the m.py:3\n-- message is really an attachment to the main:2 error and should be\n-- reported with it.\ntmp/m.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\nmain:2: error: Unexpected keyword argument \"x\" for \"A\"\ntmp/m.py:3: note: \"A\" defined here\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: Dict[str, object]\nf(**d)\ng(**d)  # E: Argument 1 to \"g\" has incompatible type \"**Dict[str, object]\"; expected \"int\"\n\nm: 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"
  },
  {
    "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"
  },
  {
    "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_extensions 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: Union[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_extensions 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_extensions 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 testLiteralInsideOtherTypes]\nfrom typing import Tuple\nfrom typing_extensions import Literal\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[Literal[1]]\"\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 Tuple, Optional\nfrom typing_extensions import Literal\n\nx: 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: Optional[Tuple[Literal[2]]]\ndef bar(x):\n    # type: (Tuple[Literal[2]]) -> None\n    pass\nreveal_type(x)                      # N: Revealed type is \"Union[Tuple[Literal[1]], None]\"\nreveal_type(y)                      # N: Revealed type is \"Union[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_extensions 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_extensions 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]\nfrom typing import TypeVar, Generic\nfrom typing_extensions import Literal\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\nfrom typing_extensions import 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_extensions 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_extensions import Literal as Foo\nBar = Foo[4]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralRenamingImportNameConfusion]\nfrom typing_extensions 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://kotlinisland.github.io/basedmypy/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_extensions 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_extensions 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_extensions 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_extensions 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_extensions 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_extensions 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\nfrom typing_extensions import Literal\nfrom missing_module import BadAlias     # E: Cannot find implementation or library stub for module named \"missing_module\" \\\n                                        # N: See https://kotlinisland.github.io/basedmypy/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_extensions 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]\n\nfrom typing_extensions 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/complex_tuple.pyi]\n[out]\n\n[case testLiteralDisallowComplexExpressions]\nfrom typing_extensions 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_extensions 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_extensions 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_extensions 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://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testLiteralDisallowCollectionsTypeAlias2]\nfrom typing_extensions 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://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\nb: bt                           # E: Variable \"__main__.bt\" is not valid as a type \\\n                                # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/set.pyi]\n[out]\n\n[case testLiteralDisallowTypeVar]\nfrom typing import TypeVar, Tuple\nfrom typing_extensions import Literal\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_extensions 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 \"Union[Literal[1], Literal[2], Literal[3]]\"\nreveal_type(b)   # N: Revealed type is \"Union[Literal['a'], Literal['b'], Literal['c']]\"\nreveal_type(c)   # N: Revealed type is \"Union[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 \"Union[Literal[1], Literal[1], Literal[1]]\"\nreveal_type(e)   # N: Revealed type is \"Union[None, None, None]\"\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testLiteralMultipleValuesExplicitTuple]\nfrom typing_extensions 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 \"Union[Literal[1], Literal[2], Literal[3]]\"\nreveal_type(b)  # N: Revealed type is \"Union[Literal[1], Literal[2], Literal[3]]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralNestedUsage]\n\nfrom typing_extensions import Literal\na: Literal[Literal[3], 4, Literal[\"foo\"]]\nreveal_type(a)  # N: Revealed type is \"Union[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 \"Union[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 \"Union[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_extensions 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_extensions 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 \"Union[Literal[5], Literal['Foo']]\"\n\nFoo = Literal[5]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBiasTowardsAssumingForwardReferencesForTypeComments]\nfrom typing_extensions 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_extensions 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_extensions 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_extensions 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, NoReturn\nfrom typing_extensions import Literal\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, NoReturn\nfrom typing_extensions import Literal\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, TypeVar, Any\nfrom typing_extensions import Literal\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, TypeVar\nfrom typing_extensions import Literal\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, Sequence\nfrom typing_extensions import Literal\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://kotlinisland.github.io/basedmypy/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_extensions 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_extensions 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_extensions 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[out]\n\n[case testLiteralInferredOnlyForActualLiterals]\nfrom typing_extensions 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 \"Optional[Literal[1, 'foo', True]]\")\ncombined = b  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"Optional[Literal[1, 'foo', True]]\")\ncombined = c  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"Optional[Literal[1, 'foo', True]]\")\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[out]\n\n[case testLiteralInferredTypeMustMatchExpected]\nfrom typing_extensions 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[out]\n\n[case testLiteralInferredInCall]\nfrom typing_extensions 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[out]\n\n[case testLiteralInferredInReturnContext]\nfrom typing_extensions 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\nfrom typing_extensions import 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[Union[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[Union[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[Union[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 Tuple\nfrom typing_extensions import Literal\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\nfrom typing_extensions import 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 overload\nfrom typing_extensions import Literal\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 overload\nfrom typing_extensions import Literal\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, Union\nfrom typing_extensions import Literal\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 \"Union[__main__.A, __main__.C]\"\nreveal_type(func(b))  # N: Revealed type is \"__main__.B\"\nreveal_type(func(c))  # N: Revealed type is \"Union[__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 overload\nfrom typing_extensions import Literal\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 TypeVar, overload, Union\nfrom typing_extensions import Literal\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 overload\nfrom typing_extensions import Literal\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_extensions 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_extensions 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_extensions 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 \"Union[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 \"Union[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]\n\nfrom typing_extensions import Literal\nfrom typing_extensions import Literal as Renamed\nimport typing_extensions 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_extensions import Literal\nfrom typing_extensions import Literal as Renamed\nimport typing_extensions 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 TypeVar\nfrom typing_extensions import Literal\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 TypeVar, Union\nfrom typing_extensions import Literal\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 \"Union[int, Literal['foo']]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralAndGenericsNoMatch]\nfrom typing import TypeVar, Union, List\nfrom typing_extensions import Literal\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 TypeVar, Generic\nfrom typing_extensions import Literal\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 TypeVar\nfrom typing_extensions import Literal\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 TypeVar\nfrom typing_extensions import Literal\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                  # N: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\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: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\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: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\n                            # N: Revealed type is \"Literal[4]\"\nreveal_type(func1(i))       # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"int\" \\\n                            # N: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\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: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\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: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\n                            # N: Revealed type is \"Literal['bar']\"\nreveal_type(func1(s))       # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"str\" \\\n                            # N: \"TLiteral\" of \"func1\" is a constrained type variable, it is not generic \\\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 TypeVar, overload, Union\nfrom typing_extensions import Literal\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, Callable, Union, Optional\nfrom typing_extensions import Literal\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[typing.Callable]\"\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, Union\nfrom typing_extensions import Literal\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[typing.Callable]\"\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 Tuple, NamedTuple, Optional, Final\nfrom typing_extensions import Literal\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 \"Union[__main__.C, None]\"\nreveal_type(tup1[idx_final])  # N: Revealed type is \"Union[__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[Union[__main__.C, None], __main__.D]\"\nreveal_type(tup1[::idx2])     # N: Revealed type is \"Tuple[__main__.A, Union[__main__.C, None], __main__.E]\"\nif tup1[idx2] is not None:\n    reveal_type(tup1[idx2])   # N: Revealed type is \"Union[__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_extensions import Literal\nfrom mypy_extensions import 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 \"Union[builtins.int, __main__.Unrelated]\"\nreveal_type(d.get(b_key, u))  # N: Revealed type is \"Union[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 Tuple, NamedTuple\nfrom typing_extensions import Literal, Final\nfrom mypy_extensions import 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 \"Union[builtins.int, __main__.Unrelated]\"\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 Tuple, NamedTuple\nfrom typing_extensions import Literal\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 \"Union[__main__.B, __main__.C]\"\nreveal_type(tup1[idx1:idx2])    # N: Revealed type is \"Union[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 \"Union[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 \"Union[__main__.B, __main__.C]\"\nreveal_type(tup2[idx1:idx2])    # N: Revealed type is \"Union[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 \"Union[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_extensions import Literal, Final\nfrom mypy_extensions import 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 \"Union[__main__.A, __main__.B]\"\nreveal_type(test.get(good_keys))                  # N: Revealed type is \"Union[__main__.A, __main__.B, None]\"\nreveal_type(test.get(good_keys, 3))               # N: Revealed type is \"Union[__main__.A, Literal[3]?, __main__.B]\"\nreveal_type(test.pop(optional_keys))              # N: Revealed type is \"Union[__main__.D, __main__.E]\"\nreveal_type(test.pop(optional_keys, 3))           # N: Revealed type is \"Union[__main__.D, __main__.E, Literal[3]?]\"\nreveal_type(test.setdefault(good_keys, AAndB()))  # N: Revealed type is \"Union[__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 Union\nfrom typing_extensions import Literal\nfrom mypy_extensions import TypedDict\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]\nbad_keys: Literal['a', 'b', 'c', 'd']\ngood_keys: Literal['b', 'c']\n\nx[bad_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 \"Union[__main__.B, __main__.C]\"\nreveal_type(x.get(good_keys))       # N: Revealed type is \"Union[__main__.B, __main__.C, None]\"\nreveal_type(x.get(good_keys, 3))    # N: Revealed type is \"Union[__main__.B, Literal[3]?, __main__.C]\"\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_extensions 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_extensions 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 \"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(var1)\nforce2(var2)\nforce3(var3)\nforce4(var4)\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(Foo.classvar1)\nforce2(Foo.classvar2)\nforce3(Foo.classvar3)\nforce4(Foo.classvar4)\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(f.instancevar1)\nforce2(f.instancevar2)\nforce3(f.instancevar3)\nforce4(f.instancevar4)\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testLiteralFinalDirectLiteralTypesForceLiteral]\nfrom typing_extensions 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_extensions import Final\n\nvar1: Final = [0, None]\nvar2: Final = (0, None)\n\nreveal_type(var1)  # N: Revealed type is \"builtins.list[Union[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_extensions 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_extensions 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 Tuple\nfrom typing_extensions import Final, Literal\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 List\nfrom typing_extensions import Final, 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_extensions 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\nfrom typing_extensions import 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]\n\nfrom typing_extensions import Literal, Final\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_extensions 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_extensions 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]\n\nfrom typing_extensions 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_extensions 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_extensions 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_extensions 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_extensions 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_extensions 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_extensions import Literal, Final\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_extensions import Literal, Final\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\n\nfrom typing_extensions 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_extensions 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_extensions import Literal, Final\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_extensions 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 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\n\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[__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 \"Union[__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 \"Union[__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 \"Union[__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 Tuple, Union\nfrom typing_extensions import Literal, Final\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 \"Union[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 \"Union[Tuple[Literal[True], int], Tuple[Literal[False], str]]\")\n    else:\n        return (True, 'oops')  # E: Incompatible return value type (got \"Tuple[bool, str]\", expected \"Union[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 \"Union[Tuple[Literal[True], int], Tuple[Literal[False], str]]\")\n    else:\n        return (bool(), 'oops')  # E: Incompatible return value type (got \"Tuple[bool, str]\", expected \"Union[Tuple[Literal[True], int], Tuple[Literal[False], str]]\")\n[builtins fixtures/bool.pyi]\n\n[case testLiteralSubtypeContext]\nfrom typing_extensions 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\nfrom typing_extensions import 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[Union[Literal['bar'], Literal['spam']]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralSubtypeContextGeneric]\nfrom typing_extensions import Literal\nfrom typing import Generic, List, 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 testLiteralTernaryUnionNarrowing]\nfrom typing_extensions import Literal\nfrom typing import 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 \"Union[Literal['a'], Literal['b']]\"\n        return super().feed_data(sep)\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralInsideAType]\nfrom typing_extensions import Literal\nfrom typing import 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"
  },
  {
    "path": "test-data/unit/check-lowercase.test",
    "content": "\n[case testTupleLowercaseSettingOff]\n# flags: --python-version 3.9 --force-uppercase-builtins\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 testTupleLowercaseSettingOn]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\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 testListLowercaseSettingOff]\n# flags: --python-version 3.9 --force-uppercase-builtins\nx = [3]\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"List[int]\")\n\n[case testListLowercaseSettingOn]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\nx = [3]\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"list[int]\")\n\n[case testDictLowercaseSettingOff]\n# flags: --python-version 3.9 --force-uppercase-builtins\nx = {\"key\": \"value\"}\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Dict[str, str]\")\n\n[case testDictLowercaseSettingOn]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\nx = {\"key\": \"value\"}\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"dict[str, str]\")\n\n[case testSetLowercaseSettingOff]\n# flags: --python-version 3.9 --force-uppercase-builtins\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 testSetLowercaseSettingOn]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\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 testTypeLowercaseSettingOff]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\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 testLowercaseSettingOnTypeAnnotationHint]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\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 testLowercaseSettingOnRevealTypeType]\n# flags: --python-version 3.9 --no-force-uppercase-builtins\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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: Type of __all__ must be \"Sequence[str]\", not \"List[int]\"\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 testEllipsisDefaultArgValueInStub2]\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 argument \"x\" (default has type \"str\", argument has type \"int\")\nmain:2: error: Incompatible default for argument \"x\" (default has type \"ellipsis\", argument has type \"int\")\nmain:3: error: Incompatible default for argument \"x\" (default has type \"str\", argument has type \"int\")\n\n[case testEllipsisDefaultArgValueInNonStub]\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 argument \"x\" (default has type \"ellipsis\", argument has type \"int\")\ndef bad_2(x: int = ...) -> None:     # E: Incompatible default for argument \"x\" (default has type \"ellipsis\", argument has type \"int\")\n    \"\"\"Docstring here\"\"\"\n    ok_1()\ndef bad_3(x: int = ...) -> None:     # E: Incompatible default for argument \"x\" (default has type \"ellipsis\", argument has type \"int\")\n    raise Exception(\"Some other exception\")\n[builtins fixtures/exception.pyi]\n[out]\n\n[case testEllipsisDefaultArgValueInNonStubsOverload]\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 argument \"y\" (default has type \"ellipsis\", argument has type \"Union[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 testEllipsisDefaultArgValueInNonStubsMethods]\nfrom typing import Generic, TypeVar\nfrom typing_extensions import Protocol\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 argument \"x\" (default has type \"ellipsis\", argument 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 argument \"x\" (default has type \"ellipsis\", argument 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 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\na.b.value\n\n[file a/b/__init__.py]\nvalue = \"a\"\nc.value\na.b.c.value\n\n[file a/b/c.py]\nvalue = 3.2\n[out]\ntmp/a/__init__.py:2: error: Name \"b\" is not defined\ntmp/a/__init__.py:3: error: Name \"a\" is not defined\ntmp/a/b/__init__.py:2: error: Name \"c\" is not defined\ntmp/a/b/__init__.py:3: error: Name \"a\" is not defined\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        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: error: Cannot determine type of \"x2\"\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\n[builtins fixtures/module.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\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\n[builtins fixtures/module.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[case testFailedImportFromTwoModules]\nimport c\nimport b\n[file b.py]\nimport c\n\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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\nreveal_type(One)\n[file m/one.py]\nclass One:\n    pass\n[file m/two.py]\nfrom m import One\nreveal_type(One)\nx: One\nreveal_type(x)\n\nclass Two(One):\n    pass\ny: Two\ny = x\nx = y\n[out]\ntmp/m/two.py:2: note: Revealed type is \"def () -> m.one.One\"\ntmp/m/two.py:4: note: Revealed type is \"m.one.One\"\ntmp/m/two.py:9: error: Incompatible types in assignment (expression has type \"One\", variable has type \"Two\")\ntmp/m/__init__.py:3: note: Revealed type is \"def () -> m.one.One\"\nmain:2: note: Revealed type is \"def () -> m.one.One\"\n\n[case testImportReExportInCycleUsingRelativeImport2]\nfrom m import One\nreveal_type(One)\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\nreveal_type(One)\n[file m/one.py]\nclass One:\n    pass\n[file m/two.py]\nimport m\nreveal_type(m.One)\nx: m.One\nreveal_type(x)\nclass Two:\n    pass\n[out]\ntmp/m/two.py:2: note: Revealed type is \"def () -> m.one.One\"\ntmp/m/two.py:4: note: Revealed type is \"m.one.One\"\ntmp/m/__init__.py:3: note: Revealed type is \"def () -> m.one.One\"\nmain:2: note: Revealed type is \"def () -> m.one.One\"\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 \"Union[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[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[builtins fixtures/module.pyi]\n[out]\ntmp/p/b.py:4: note: Revealed type is \"builtins.int\"\ntmp/p/__init__.py:3: note: Revealed type is \"builtins.int\"\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://kotlinisland.github.io/basedmypy/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_extensions 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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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://kotlinisland.github.io/basedmypy/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)\ntmp/a.py:1: error: Module \"b\" has no attribute \"no_such_export\"\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)\ntmp/b.py:1: error: Cannot resolve name \"no_such_export\" (possible cyclic definition)\ntmp/a.py:1: error: Module \"b\" has no attribute \"no_such_export\"\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 \"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 \"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"
  },
  {
    "path": "test-data/unit/check-multiple-inheritance.test",
    "content": "-- Test cases for multiple inheritance.\n--\n-- Related: check-abstract.test\n\n\n-- No name collisions\n-- ------------------\n\n\n[case testSimpleMultipleInheritanceAndMethods]\nimport typing\nclass A:\n    def f(self, x: int) -> None: pass\nclass B:\n    def g(self, x: str) -> None: pass\nclass C(A, B): pass\nc = C()\nc.f(1)\nc.f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nc.g('')\nc.g(1)  # E: Argument 1 to \"g\" of \"B\" has incompatible type \"int\"; expected \"str\"\n\n[case testSimpleMultipleInheritanceAndMethods2]\nimport typing\nclass A:\n    def f(self, x: int) -> None: pass\nclass B:\n    def g(self, x): pass\nclass C(A, B): pass\nc = C()\nc.f(1)\nc.f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nc.g('')\nc.g(1)\n\n[case testSimpleMultipleInheritanceAndInstanceVariables]\nimport typing\nclass A:\n    def f(self) -> None:\n        self.x = 1\nclass B:\n    def g(self) -> None:\n        self.y = ''\nclass C(A, B): pass\nc = C()\nc.x = 1\nc.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nc.y = ''\nc.y = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testSimpleMultipleInheritanceAndInstanceVariableInClassBody]\nimport typing\nclass A:\n    x = 1\nclass B:\n    y = ''\nclass C(A, B): pass\nc = C()\nc.x = 1\nc.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nc.y = ''\nc.y = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testSimpleMultipleInheritanceAndClassVariable]\nimport typing\nclass A:\n    x = 1\nclass B:\n    y = ''\nclass C(A, B): pass\nC.x = 1\nC.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nC.y = ''\nC.y = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n\n-- Name collisions\n-- ---------------\n\n\n[case testMethodNameCollisionInMultipleInheritanceWithValidSigs]\nimport typing\nclass A:\n    def f(self, x: int) -> None: pass\nclass B:\n    def f(self, x: int) -> None: pass\nclass C(A, B): pass\nc = C()\nc.f(1)\nc.f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testInstanceVarNameOverlapInMultipleInheritanceWithCompatibleTypes]\nimport typing\nclass A:\n    def f(self) -> None:\n        self.x = 1\nclass B:\n    def g(self) -> None:\n        self.x = 1\nclass C(A, B): pass\nc = C()\nc.x = 1\nc.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testClassVarNameOverlapInMultipleInheritanceWithCompatibleTypes]\nimport typing\nclass A:\n    x = 1\nclass B:\n    x = 1\nclass C(A, B): pass\nc = C()\nc.x = 1\nc.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nC.x = 1\nC.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testMethodNameCollisionInMultipleInheritanceWithIncompatibleSigs]\nimport typing\nclass A:\n    def f(self, x: int) -> None: pass\nclass B:\n    def f(self, x: str) -> None: pass\nclass C(A, B): pass\n[out]\nmain:6: error: Definition of \"f\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n[case testMethodNameCollisionInMultipleInheritanceWithIncompatibleSigs2]\nimport typing\nclass A:\n    def f(self, x: int) -> None: pass\nclass B:\n    def f(self, x, y): pass\nclass C(A, B): pass\nclass D(B, A): pass\n[out]\nmain:6: error: Definition of \"f\" in base class \"A\" is incompatible with definition in base class \"B\"\nmain:7: error: Definition of \"f\" in base class \"B\" is incompatible with definition in base class \"A\"\n\n\n[case testMethodOverridingWithBothDynamicallyAndStaticallyTypedMethods]\nclass A:\n    def f(self) -> int: pass\nclass B:\n    def f(self): pass\nclass C(B, A): pass\nclass D(A, B): pass\n[out]\n\n[case testInstanceVarNameOverlapInMultipleInheritanceWithInvalidTypes]\nimport typing\nclass A:\n    def f(self) -> None:\n        self.x = 1\nclass B:\n    def g(self) -> None:\n        self.x = ''\nclass C(A, B): pass\n[out]\nmain:8: error: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n[case testClassVarNameOverlapInMultipleInheritanceWithInvalidTypes]\nimport typing\nclass A:\n    x = 1\nclass B:\n    x = ''\nclass C(A, B): pass\n[out]\nmain:6: error: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n[case testMethodOverlapsWithClassVariableInMultipleInheritance]\nfrom typing import Callable\nclass A:\n    def f(self) -> None: pass\nclass B:\n    f = ''\nclass C(A, B): pass\n[out]\nmain:6: error: Definition of \"f\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n[case testMethodOverlapsWithInstanceVariableInMultipleInheritance]\nfrom typing import Callable\nclass A:\n    def f(self) -> None: pass\nclass B:\n    def g(self) -> None:\n        self.f = ''\nclass C(A, B): pass\n[out]\nmain:7: error: Definition of \"f\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n[case testMultipleInheritanceAndInit]\nimport typing\nclass A:\n    def __init__(self, x: int) -> None: pass\nclass B:\n    def __init__(self) -> None: pass\nclass C(A, B): pass\n\n[case testMultipleInheritanceAndDifferentButCompatibleSignatures]\nclass A:\n    def clear(self): pass\n\nclass B:\n    def clear(self, x=None): pass\n\nclass C(B, A): pass\nclass D(A, B): pass\n[out]\nmain:8: error: Definition of \"clear\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n\n-- Special cases\n-- -------------\n\n\n[case testGenericInheritanceAndOverridingWithMultipleInheritance]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass G(Generic[T]):\n    def f(self, s: int) -> 'G[T]': pass\nclass A(G[int]):\n    def f(self, s: int) -> 'A': pass\nclass B(A, int): pass\n\n[case testCannotDetermineTypeInMultipleInheritance]\nfrom typing import Callable, TypeVar\nT = TypeVar('T')\nclass A(B, C):\n    pass\nclass B:\n    @dec\n    def f(self): pass\nclass C:\n    @dec\n    def f(self): pass\ndef dec(f: Callable[..., T]) -> Callable[..., T]:\n    return f\n[out]\nmain:3: error: Cannot determine type of \"f\" in base class \"B\"\nmain:3: error: Cannot determine type of \"f\" in base class \"C\"\n\n[case testMultipleInheritance_NestedClassesWithSameName]\nclass Mixin1:\n    class Meta:\n        pass\nclass Mixin2:\n    class Meta:\n        pass\nclass A(Mixin1, Mixin2):\n    pass\n[out]\nmain:7: error: Definition of \"Meta\" in base class \"Mixin1\" is incompatible with definition in base class \"Mixin2\"\n\n[case testMultipleInheritance_NestedClassesWithSameNameCustomMetaclass]\nclass Metaclass(type):\n    pass\nclass Mixin1:\n    class Meta(metaclass=Metaclass):\n        pass\nclass Mixin2:\n    class Meta(metaclass=Metaclass):\n        pass\nclass A(Mixin1, Mixin2):\n    pass\n[out]\nmain:9: error: Definition of \"Meta\" in base class \"Mixin1\" is incompatible with definition in base class \"Mixin2\"\n\n[case testMultipleInheritance_NestedClassesWithSameNameOverloadedNew]\nfrom mixins import Mixin1, Mixin2\nclass A(Mixin1, Mixin2):\n    pass\n[file mixins.py]\nclass Mixin1:\n    class Meta:\n        pass\nclass Mixin2:\n    class Meta:\n        pass\n[file mixins.pyi]\nfrom typing import overload, Any, Mapping, Dict\nclass Mixin1:\n    class Meta:\n        @overload\n        def __new__(cls, *args, **kwargs: None) -> Mixin1.Meta:\n            pass\n        @overload\n        def __new__(cls, *args, **kwargs: Dict[str, Any]) -> Mixin1.Meta:\n            pass\nclass Mixin2:\n    class Meta:\n        pass\n[builtins fixtures/dict.pyi]\n[out]\nmain:2: error: Definition of \"Meta\" in base class \"Mixin1\" is incompatible with definition in base class \"Mixin2\"\n\n[case testMultipleInheritance_NestedClassAndAttrHaveSameName]\nclass Mixin1:\n    class Nested1:\n        pass\nclass Mixin2:\n    Nested1: str\nclass A(Mixin1, Mixin2):\n    pass\n[out]\nmain:6: error: Definition of \"Nested1\" in base class \"Mixin1\" is incompatible with definition in base class \"Mixin2\"\n\n[case testMultipleInheritance_NestedClassAndFunctionHaveSameName]\nclass Mixin1:\n    class Nested1:\n        pass\nclass Mixin2:\n    def Nested1(self) -> str:\n        pass\nclass A(Mixin1, Mixin2):\n    pass\n[out]\nmain:7: error: Definition of \"Nested1\" in base class \"Mixin1\" is incompatible with definition in base class \"Mixin2\"\n\n[case testMultipleInheritance_NestedClassAndRefToOtherClass]\nclass Outer:\n    pass\nclass Mixin1:\n    class Nested1:\n        pass\nclass Mixin2:\n    Nested1 = Outer\nclass A(Mixin2, Mixin1):\n    pass\n[out]\nmain:8: error: Definition of \"Nested1\" in base class \"Mixin2\" is incompatible with definition in base class \"Mixin1\"\n\n[case testMultipleInheritance_ReferenceToSubclassesFromSameMRO]\nclass A:\n    def __init__(self, arg: str) -> None:\n        pass\nclass B(A):\n    pass\nclass Base1:\n    NestedVar = A\nclass Base2:\n    NestedVar = B\nclass Combo(Base2, Base1): ...\n[out]\n\n[case testMultipleInheritance_ReferenceToSubclassesFromSameMROCustomMetaclass]\nclass Metaclass(type):\n    pass\nclass A(metaclass=Metaclass):\n    pass\nclass B(A):\n    pass\nclass Base1:\n    NestedVar = A\nclass Base2:\n    NestedVar = B\nclass Combo(Base2, Base1): ...\n[out]\n\n[case testMultipleInheritance_ReferenceToSubclassesFromSameMROOverloadedNew]\nfrom mixins import A, B\nclass Base1:\n    NestedVar = A\nclass Base2:\n    NestedVar = B\nclass Combo(Base2, Base1): ...\n[file mixins.py]\nclass A:\n    pass\nclass B(A):\n    pass\n[file mixins.pyi]\nfrom typing import overload, Dict, Any\nclass A:\n    @overload\n    def __new__(cls, *args, **kwargs: None) -> A:\n        pass\n    @overload\n    def __new__(cls, *args, **kwargs: Dict[str, Any]) -> A:\n        pass\nclass B:\n    pass\n[builtins fixtures/dict.pyi]\n[out]\nmain:6: error: Definition of \"NestedVar\" in base class \"Base2\" is incompatible with definition in base class \"Base1\"\n\n[case testMultipleInheritance_ReferenceToGenericClasses]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass Generic1(Generic[T]):\n    pass\nclass Generic2(Generic[T]):\n    pass\nclass Base1:\n    Nested = Generic1\nclass Base2:\n    Nested = Generic2\nclass A(Base1, Base2):\n    pass\n[out]\nmain:11: error: Definition of \"Nested\" in base class \"Base1\" is incompatible with definition in base class \"Base2\"\n\n[case testMultipleInheritance_GenericSubclasses_SuperclassFirst]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass ParentGeneric(Generic[T]):\n    pass\nclass ChildGeneric(ParentGeneric[T]):\n    pass\nclass Base1:\n    Nested = ParentGeneric\nclass Base2:\n    Nested = ChildGeneric\nclass A(Base1, Base2):\n    pass\n[out]\nmain:11: error: Definition of \"Nested\" in base class \"Base1\" is incompatible with definition in base class \"Base2\"\n\n[case testMultipleInheritance_GenericSubclasses_SubclassFirst]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass ParentGeneric(Generic[T]):\n    pass\nclass ChildGeneric(ParentGeneric[T]):\n    pass\nclass Base1:\n    Nested = ParentGeneric\nclass Base2:\n    Nested = ChildGeneric\nclass A(Base2, Base1):\n    pass\n[out]\n\n[case testMultipleInheritance_RefersToNamedTuples]\nfrom typing import NamedTuple\nclass NamedTuple1:\n    attr1: int\nclass NamedTuple2:\n    attr2: int\nclass Base1:\n    Nested = NamedTuple1\nclass Base2:\n    Nested = NamedTuple2\nclass A(Base1, Base2):\n    pass\n[out]\nmain:10: error: Definition of \"Nested\" in base class \"Base1\" is incompatible with definition in base class \"Base2\"\n\n[case testMultipleInheritance_NestedVariableRefersToSuperlassUnderSubclass]\nclass A:\n    def __init__(self, arg: str) -> None:\n        pass\nclass B(A):\n    pass\nclass Base1:\n    NestedVar = B\nclass Base2:\n    NestedVar = A\nclass Combo(Base2, Base1): ...\n[out]\nmain:10: error: Definition of \"NestedVar\" in base class \"Base2\" is incompatible with definition in base class \"Base1\"\n\n[case testMultipleInheritance_NestedVariableOverriddenWithCompatibleType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', covariant=True)\nclass GenericBase(Generic[T]):\n    pass\nclass Base1:\n    Nested: GenericBase['Base1']\nclass Base2:\n    Nested: GenericBase['Base2']\nclass A(Base1, Base2):\n    Nested: GenericBase['A']\n[out]\n\n[case testMultipleInheritance_NestedVariableOverriddenWithIncompatibleType1]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', covariant=True)\nclass GenericBase(Generic[T]):\n    pass\nclass Base1:\n    Nested: GenericBase['Base1']\nclass Base2:\n    Nested: GenericBase['Base2']\nclass A(Base1, Base2):\n    Nested: GenericBase['Base1']\n[out]\nmain:10: error: Incompatible types in assignment (expression has type \"GenericBase[Base1]\", base class \"Base2\" defined the type as \"GenericBase[Base2]\")\n\n[case testMultipleInheritance_NestedVariableOverriddenWithIncompatibleType2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', covariant=True)\nclass GenericBase(Generic[T]):\n    pass\nclass Base1:\n    Nested: GenericBase['Base1']\nclass Base2:\n    Nested: GenericBase['Base2']\nclass A(Base1, Base2):\n    Nested: GenericBase['Base2']\n[out]\nmain:10: error: Incompatible types in assignment (expression has type \"GenericBase[Base2]\", base class \"Base1\" defined the type as \"GenericBase[Base1]\")\n\n[case testMultipleInheritance_NestedVariableOverriddenWithCompatibleType2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', covariant=True)\nclass GenericBase(Generic[T]):\n    pass\nclass Base1:\n    Nested: GenericBase['Base1']\nclass Base2:\n    Nested: GenericBase['Base1']\nclass A(Base1, Base2):\n    Nested: GenericBase['Base1']\n[out]\n\n[case testMultipleInheritance_MethodDefinitionsCompatibleWithOverride]\nfrom typing import TypeVar, Union\n_T = TypeVar('_T')\n\nclass Flag:\n    def __or__(self: _T, other: _T) -> _T: ...\n\n# int defines __or__ as:\n#     def __or__(self, n: int) -> int: ...\nclass IntFlag(int, Flag):\n    def __or__(self: _T, other: Union[int, _T]) -> _T: ...\n[out]\n\n[case testMultipleInheritance_MethodDefinitionsIncompatibleOverride]\nfrom typing import TypeVar, Union\n_T = TypeVar('_T')\n\nclass Flag:\n    def __or__(self: _T, other: _T) -> _T: ...\n\nclass IntFlag(int, Flag):\n    def __or__(self: _T, other: str) -> _T: ...\n[out]\nmain:8: error: Argument 1 of \"__or__\" is incompatible with supertype \"Flag\"; supertype defines the argument type as \"IntFlag\"\nmain:8: note: This violates the Liskov substitution principle\nmain:8: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\n\n[case testMultipleInheritance_MethodDefinitionsCompatibleNoOverride]\nfrom typing import TypeVar, Union\n_T = TypeVar('_T')\n\nclass Flag:\n    def __or__(self: _T, other: _T) -> _T: ...\n\nclass IntFlag(int, Flag):\n    pass\n[out]\n\n[case testMultipleInheritance_MethodsReturningSelfCompatible]\nclass A(object):\n    def x(self) -> 'A':\n        return self\n\nclass B(object):\n    def x(self) -> 'B':\n        return self\n\nclass C(A, B):\n    def x(self) -> 'C':\n        return self\n\n[case testMultipleInheritance_MethodsReturningSelfIncompatible]\nclass A(object):\n    def x(self) -> 'A':\n        return self\n\nclass B(object):\n    def x(self) -> 'B':\n        return self\n\nclass C(A, B): # E: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\n    pass\n\n[case testNestedVariableRefersToSubclassOfAnotherNestedClass]\nclass Mixin1:\n    class Meta:\n        pass\nclass Outer(Mixin1.Meta):\n    pass\nclass Mixin2:\n    NestedVar = Outer\nclass Combo(Mixin2, Mixin1): ...\n[out]\n\n[case testNestedVariableRefersToCompletelyDifferentClasses]\nclass A:\n    pass\nclass B:\n    pass\nclass Base1:\n    NestedVar = A\nclass Base2:\n    NestedVar = B\nclass Combo(Base2, Base1): ...\n[out]\nmain:9: error: Definition of \"NestedVar\" in base class \"Base2\" is incompatible with definition in base class \"Base1\"\n\n[case testDoNotFailIfBothNestedClassesInheritFromAny]\nfrom typing import Any\nclass Mixin1:\n    class Meta(Any):\n        pass\nclass Mixin2:\n    class Meta(Any):\n        pass\nclass A(Mixin1, Mixin2):\n    pass\n[out]\n\n[case testDoNotFailIfOneOfNestedClassesIsOuterInheritedFromAny]\nfrom typing import Any\nclass Outer(Any):\n    pass\nclass Mixin1:\n    Meta = Outer\nclass Mixin2:\n    class Meta(Any):\n        pass\nclass A(Mixin1, Mixin2):\n    pass\n[out]\n\n[case testGenericMultipleOverrideRemap]\nfrom typing import TypeVar, Generic, Tuple\n\nK = TypeVar('K')\nV = TypeVar('V')\nT = TypeVar('T')\n\nclass ItemsView(Generic[K, V]):\n    def __iter__(self) -> Tuple[K, V]: ...\n\nclass Sequence(Generic[T]):\n    def __iter__(self) -> T: ...\n\n# Override compatible between bases.\nclass OrderedItemsView(ItemsView[K, V], Sequence[Tuple[K, V]]):\n    def __iter__(self) -> Tuple[K, V]: ...\n\nclass OrderedItemsViewDirect(ItemsView[K, V], Sequence[Tuple[K, V]]):\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testGenericMultipleOverrideReplace]\nfrom typing import TypeVar, Generic, Union\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    def foo(self, x: T) -> None: ...\n\nclass B(A[T]): ...\n\nclass C1:\n    def foo(self, x: str) -> None: ...\n\nclass C2:\n    def foo(self, x: Union[str, int]) -> None: ...\n\nclass D1(B[str], C1): ...\nclass D2(B[Union[int, str]], C2): ...\nclass D3(C2, B[str]): ...\nclass D4(B[str], C2): ...  # E: Definition of \"foo\" in base class \"A\" is incompatible with definition in base class \"C2\"\n\n\n[case testMultipleInheritanceOverridingOfFunctionsWithCallableInstances]\nfrom typing import Any, Callable\n\ndef dec1(f: Callable[[Any, int], None]) -> Callable[[Any, int], None]: ...\n\nclass F:\n    def __call__(self, x: int) -> None: ...\n\ndef dec2(f: Callable[[Any, int], None]) -> F: ...\n\nclass B1:\n    def f(self, x: int) -> None: ...\n\nclass B2:\n    @dec1\n    def f(self, x: int) -> None: ...\n\nclass B3:\n    @dec2\n    def f(self, x: int) -> None: ...\n\nclass B4:\n    f = F()\n\nclass C12(B1, B2): ...\nclass C13(B1, B3): ...  # E: Definition of \"f\" in base class \"B1\" is incompatible with definition in base class \"B3\"\nclass C14(B1, B4): ...  # E: Definition of \"f\" in base class \"B1\" is incompatible with definition in base class \"B4\"\nclass C21(B2, B1): ...  # E: Definition of \"f\" in base class \"B2\" is incompatible with definition in base class \"B1\"\nclass C23(B2, B3): ...  # E: Definition of \"f\" in base class \"B2\" is incompatible with definition in base class \"B3\"\nclass C24(B2, B4): ...  # E: Definition of \"f\" in base class \"B2\" is incompatible with definition in base class \"B4\"\nclass C31(B3, B1): ...\nclass C32(B3, B2): ...\nclass C34(B3, B4): ...\nclass C41(B4, B1): ...\nclass C42(B4, B2): ...\nclass C43(B4, B3): ...\n\n[case testMultipleInheritanceExplicitDiamondResolution]\n# Adapted from #14279\nclass A:\n    class M:\n        pass\n\nclass B0(A):\n    class M(A.M):\n        pass\n\nclass B1(A):\n    class M(A.M):\n        pass\n\nclass C(B0,B1):\n    class M(B0.M, B1.M):\n        pass\n\nclass D0(B0):\n    pass\nclass D1(B1):\n    pass\n\nclass D(D0,D1,C):\n    pass\n"
  },
  {
    "path": "test-data/unit/check-namedtuple.test",
    "content": "[case testNamedTupleUsedAsTuple]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x y')\nx: X\na, b = x\nb = x[0]\na = x[1]\na, b, c = x # E: Need more than 2 values to unpack (3 expected)\nx[2] # E: Tuple index out of range\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleWithTupleFieldNamesUsedAsTuple]\nfrom collections import namedtuple\n\nX = namedtuple('X', ('x', 'y'))\nx: X\na, b = x\nb = x[0]\na = x[1]\na, b, c = x # E: Need more than 2 values to unpack (3 expected)\nx[2] # E: Tuple index out of range\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleInvalidFields]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x, _y')  # E: \"namedtuple()\" field name \"_y\" starts with an underscore\nY = namedtuple('Y', ['x', '1'])  # E: \"namedtuple()\" field name \"1\" is not a valid identifier\nZ = namedtuple('Z', ['x', 'def'])  # E: \"namedtuple()\" field name \"def\" is a keyword\nA = namedtuple('A', ['x', 'x'])  # E: \"namedtuple()\" has duplicate field name \"x\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleAccessingAttributes]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x y')\nx: X\nx.x\nx.y\nx.z # E: \"X\" has no attribute \"z\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleClassInStub]\nimport foo\n\n[file foo.pyi]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    x: int\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleAttributesAreReadOnly]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x y')\nx: X\nx.x = 5 # E: Property \"x\" defined in \"X\" is read-only\nx.y = 5 # E: Property \"y\" defined in \"X\" is read-only\nx.z = 5 # E: \"X\" has no attribute \"z\"\n\nclass A(X): pass\na: A\na.x = 5 # E: Property \"x\" defined in \"X\" is read-only\na.y = 5 # E: Property \"y\" defined in \"X\" is read-only\n-- a.z = 5 # not supported yet\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypingNamedTupleAttributesAreReadOnly]\nfrom typing import NamedTuple\nfrom typing_extensions import Protocol\n\nclass HasX(Protocol):\n    x: str\n\nclass A(NamedTuple):\n    x: str\n\na: HasX = A(\"foo\")\na.x = \"bar\"\n[builtins fixtures/tuple.pyi]\n[out]\nmain:10: error: Incompatible types in assignment (expression has type \"A\", variable has type \"HasX\")\nmain:10: note: Protocol member HasX.x expected settable variable, got read-only attribute\n\n\n[case testNamedTupleCreateWithPositionalArguments]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x y')\nx = X(1, 'x')\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 testCreateNamedTupleWithKeywordArguments]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x y')\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=1) # E: Missing positional argument \"x\" in call to \"X\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleCreateAndUseAsTuple]\nfrom collections import namedtuple\n\nX = namedtuple('X', 'x y')\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 testNamedTupleAdditionalArgs]\nfrom collections import namedtuple\n\nA = namedtuple('A', 'a b')\nB = namedtuple('B', 'a b', rename=1)\nC = namedtuple('C', 'a b', rename='not a bool')\nD = namedtuple('D', 'a b', unrecognized_arg=False)\nE = namedtuple('E', 'a b', 0)\n\n[builtins fixtures/bool.pyi]\n\n[out]\nmain:4: error: Boolean literal expected as the \"rename\" argument to namedtuple()\nmain:5: error: Boolean literal expected as the \"rename\" argument to namedtuple()\nmain:5: error: Argument \"rename\" to \"namedtuple\" has incompatible type \"str\"; expected \"int\"\nmain:6: error: Unexpected keyword argument \"unrecognized_arg\" for \"namedtuple\"\n<ROOT>/test-data/unit/lib-stub/collections.pyi:3: note: \"namedtuple\" defined here\nmain:7: error: Too many positional arguments for \"namedtuple\"\n\n[case testNamedTupleDefaults]\nfrom collections import namedtuple\n\nX = namedtuple('X', ['x', 'y'], defaults=(1,))\n\nX()  # E: Missing positional argument \"x\" in call to \"X\"\nX(0)  # ok\nX(0, 1)  # ok\nX(0, 1, 2)  # E: Too many arguments for \"X\"\n\nY = namedtuple('Y', ['x', 'y'], defaults=(1, 2, 3))  # E: Too many defaults given in call to \"namedtuple()\"\nZ = namedtuple('Z', ['x', 'y'], defaults='not a tuple')  # E: List or tuple literal expected as the defaults argument to namedtuple()  # E: Argument \"defaults\" to \"namedtuple\" has incompatible type \"str\"; expected \"Optional[Iterable[Any]]\"\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleRename]\nfrom collections import namedtuple\n\nX = namedtuple('X', ['abc', 'def'], rename=False)  # E: \"namedtuple()\" field name \"def\" is a keyword\nY = namedtuple('Y', ['x', 'x', 'def', '42', '_x'], rename=True)\ny = Y(x=0, _1=1, _2=2, _3=3, _4=4)\nreveal_type(y.x)  # N: Revealed type is \"Any\"\nreveal_type(y._1)  # N: Revealed type is \"Any\"\nreveal_type(y._2)  # N: Revealed type is \"Any\"\nreveal_type(y._3)  # N: Revealed type is \"Any\"\nreveal_type(y._4)  # N: Revealed type is \"Any\"\ny._0  # E: \"Y\" has no attribute \"_0\"\ny._5  # E: \"Y\" has no attribute \"_5\"\ny._x  # E: \"Y\" has no attribute \"_x\"\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleWithItemTypes]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('a', int),\n                     ('b', str)])\nn = N(1, 'x')\ns = n.a # type: str  # E: Incompatible types in assignment (expression has type \"int\", \\\n                          variable has type \"str\")\ni = n.b # type: int  # 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[targets __main__, __main__.N.__new__, __main__.N._asdict, __main__.N._make, __main__.N._replace]\n[builtins fixtures/tuple.pyi]\n\n\n[case testNamedTupleWithTupleFieldNamesWithItemTypes]\nfrom typing import NamedTuple\nN = NamedTuple('N', (('a', int),\n                     ('b', str)))\nn = N(1, 'x')\ns = n.a # type: str  # E: Incompatible types in assignment (expression has type \"int\", \\\n                          variable has type \"str\")\ni = n.b # type: int  # 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\n[case testNamedTupleConstructorArgumentTypes]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('a', int),\n                     ('b', str)])\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 testNamedTupleAsBaseClass]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('a', int),\n                     ('b', str)])\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 testNamedTupleAsBaseClass2]\nfrom typing import NamedTuple\nclass X(NamedTuple('N', [('a', int),\n                         ('b', str)])):\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\n[case testNamedTuplesTwoAsBaseClasses]\nfrom typing import NamedTuple\nA = NamedTuple('A', [('a', int)])\nB = NamedTuple('B', [('a', int)])\nclass X(A, B):  # E: Class has two incompatible bases derived from tuple\n    pass\n[builtins fixtures/tuple.pyi]\n\n\n[case testNamedTuplesTwoAsBaseClasses2]\nfrom typing import NamedTuple\nA = NamedTuple('A', [('a', int)])\nclass X(A, NamedTuple('B', [('a', int)])): # E: Class has two incompatible bases derived from tuple\n    pass\n[builtins fixtures/tuple.pyi]\n\n\n[case testNamedTupleSelfTypeWithNamedTupleAsBase]\nfrom typing import NamedTuple\nA = NamedTuple('A', [('a', int), ('b', str)])\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\n\n[out]\n\n[case testNamedTupleTypeReferenceToClassDerivedFrom]\nfrom typing import NamedTuple\nA = NamedTuple('A', [('a', int), ('b', str)])\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[out]\n\n[case testNamedTupleSubtyping]\nfrom typing import NamedTuple, Tuple\nA = NamedTuple('A', [('a', int), ('b', str)])\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\n[case testNamedTupleSimpleTypeInference]\nfrom typing import NamedTuple, Tuple\nA = NamedTuple('A', [('a', int)])\nl = [A(1), A(2)]\na = A(1)\nif int():\n    a = l[0]\n(i,) = l[0]\nif int():\n    i, i = l[0]  # E: Need more than 1 value to unpack (2 expected)\nif int():\n    l = [A(1)]\nif int():\n    a = (1,)  # E: Incompatible types in assignment (expression has type \"Tuple[int]\", \\\n                   variable has type \"A\")\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleMissingClassAttribute]\nimport collections\nMyNamedTuple = collections.namedtuple('MyNamedTuple', ['spam', 'eggs'])\nMyNamedTuple.x # E: \"Type[MyNamedTuple]\" has no attribute \"x\"\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleEmptyItems]\nfrom typing import NamedTuple\nA = NamedTuple('A', [])\n[builtins fixtures/tuple.pyi]\n\n\n[case testNamedTupleProperty]\nfrom typing import NamedTuple\nA = NamedTuple('A', [('a', int)])\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 testNamedTupleAsDict]\nfrom collections import namedtuple\n\nX = namedtuple('X', ['x', 'y'])\nx: X\nreveal_type(x._asdict())  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testNamedTupleReplace]\nfrom collections import namedtuple\n\nX = namedtuple('X', ['x', 'y'])\nx: X\nreveal_type(x._replace())  # N: Revealed type is \"Tuple[Any, Any, fallback=__main__.X]\"\nx._replace(y=5)\nx._replace(x=3)\nx._replace(x=3, y=5)\nx._replace(z=5)  # E: Unexpected keyword argument \"z\" for \"_replace\" of \"X\"\nx._replace(5)  # E: Too many positional arguments for \"_replace\" of \"X\"\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleReplaceAsClass]\n# flags: --no-strict-optional\nfrom collections import namedtuple\n\nX = namedtuple('X', ['x', 'y'])\nx = None  # type: X\nX._replace(x, x=1, y=2)\nX._replace(x=1, y=2)  # E: Missing positional argument \"_self\" in call to \"_replace\" of \"X\"\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleReplaceTyped]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\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 testNamedTupleMake]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\nreveal_type(X._make([5, 'a']))  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.X]\"\nX._make('a b')  # E: Argument 1 to \"_make\" of \"X\" has incompatible type \"str\"; expected \"Iterable[Any]\"\n\n-- # FIX: not a proper class method\n-- x: X\n-- reveal_type(x._make([5, 'a']))  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.X]\"\n-- x._make('a b')  # E: Argument 1 to \"_make\" of \"X\" has incompatible type \"str\"; expected Iterable[Any]\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleFields]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\nreveal_type(X._fields)  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleSource]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\nreveal_type(X._source)  # N: Revealed type is \"builtins.str\"\nx: X\nreveal_type(x._source)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleUnit]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [])\nx = X()  # type: X\nx._replace()\nx._fields[0]  # E: Tuple index out of range\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleJoinNamedTuple]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\nY = NamedTuple('Y', [('x', int), ('y', str)])\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 testNamedTupleJoinTuple]\nfrom typing import NamedTuple, Tuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\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 testNamedTupleFieldTypes]\nfrom typing import NamedTuple\n\nX = NamedTuple('X', [('x', int), ('y', str)])\nreveal_type(X._field_types)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\nx: X\nreveal_type(x._field_types)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testNamedTupleAndOtherSuperclass]\nfrom typing import NamedTuple\n\nclass A: pass\ndef f(x: A) -> None: pass\n\nclass B(NamedTuple('B', []), A): pass\nf(B())\nx: A\nif int():\n    x = B()\n\n# Sanity check: fail if baseclass does not match\nclass C: pass\ndef g(x: C) -> None: pass\nclass D(NamedTuple('D', []), A): pass\n\ng(D())  # E: Argument 1 to \"g\" has incompatible type \"D\"; expected \"C\"\ny: C\nif int():\n    y = D()  # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleSelfTypeMethod]\nfrom typing import TypeVar, NamedTuple\n\nT = TypeVar('T', bound='A')\n\nclass A(NamedTuple('A', [('x', str)])):\n    def member(self: T) -> T:\n        return self\n\nclass B(A):\n    pass\n\na: A\na = A('').member()\nb: B\nb = B('').member()\na = B('')\na = B('').member()\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleSelfTypeReplace]\nfrom typing import NamedTuple, TypeVar\nA = NamedTuple('A', [('x', str)])\nreveal_type(A('hello')._replace(x=''))  # N: Revealed type is \"Tuple[builtins.str, fallback=__main__.A]\"\na: A\na = A('hello')._replace(x='')\n\nclass B(A):\n    pass\n\nreveal_type(B('hello')._replace(x=''))  # N: Revealed type is \"Tuple[builtins.str, fallback=__main__.B]\"\nb: B\nb = B('hello')._replace(x='')\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleSelfTypeMake]\nfrom typing import NamedTuple, TypeVar\nA = NamedTuple('A', [('x', str)])\nreveal_type(A._make(['']))  # N: Revealed type is \"Tuple[builtins.str, fallback=__main__.A]\"\na = A._make([''])  # type: A\n\nclass B(A):\n    pass\n\nreveal_type(B._make(['']))  # N: Revealed type is \"Tuple[builtins.str, fallback=__main__.B]\"\nb = B._make([''])  # type: B\n\n[builtins fixtures/list.pyi]\n\n[case testNamedTupleIncompatibleRedefinition]\nfrom typing import NamedTuple\nclass Crash(NamedTuple):\n    count: int  # E: Incompatible types in assignment (expression has type \"int\", base class \"tuple\" defined the type as \"Callable[[Tuple[int, ...], object], int]\")\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleInClassNamespace]\n# https://github.com/python/mypy/pull/2553#issuecomment-266474341\nfrom typing import NamedTuple\nclass C:\n    def f(self):\n        A = NamedTuple('A', [('x', int)])\n    def g(self):\n        A = NamedTuple('A', [('y', int)])\nC.A  # E: \"Type[C]\" has no attribute \"A\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleInFunction]\nfrom typing import NamedTuple\ndef f() -> None:\n    A = NamedTuple('A', [('x', int)])\nA  # E: Name \"A\" is not defined\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleForwardAsUpperBound]\n# flags: --disable-error-code=used-before-def\nfrom typing import NamedTuple, TypeVar, Generic\nT = TypeVar('T', bound='M')\nclass G(Generic[T]):\n    x: T\n\nyb: G[int] # E: Type argument \"int\" of \"G\" must be a subtype of \"M\"\nyg: G[M]\nreveal_type(G[M]().x.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(G[M]().x[0])  # N: Revealed type is \"builtins.int\"\n\nM = NamedTuple('M', [('x', int)])\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNamedTupleWithImportCycle]\nimport a\n[file a.py]\nfrom collections import namedtuple\nfrom b import f\n\nN = namedtuple('N', 'a')\n\nclass X(N): pass\n[file b.py]\nimport a\n\ndef f(x: a.X) -> None:\n    reveal_type(x)\n    x = a.X(1)\n    reveal_type(x)\n[builtins fixtures/tuple.pyi]\n[out]\ntmp/b.py:4: note: Revealed type is \"Tuple[Any, fallback=a.X]\"\ntmp/b.py:6: note: Revealed type is \"Tuple[Any, fallback=a.X]\"\n\n[case testNamedTupleWithImportCycle2]\nimport a\n[file a.py]\nfrom collections import namedtuple\nfrom b import f\n\nN = namedtuple('N', 'a')\n[file b.py]\nimport a\n\ndef f(x: a.N) -> None:\n    reveal_type(x)\n    if int():\n        x = a.N(1)\n        reveal_type(x)\n[builtins fixtures/tuple.pyi]\n[out]\ntmp/b.py:4: note: Revealed type is \"Tuple[Any, fallback=a.N]\"\ntmp/b.py:7: note: Revealed type is \"Tuple[Any, fallback=a.N]\"\n\n[case testSimpleSelfReferentialNamedTuple]\nfrom typing import NamedTuple\n\ndef test() -> None:\n    class MyNamedTuple(NamedTuple):\n        parent: 'MyNamedTuple'  # E: Cannot resolve name \"MyNamedTuple\" (possible cyclic definition) \\\n                                # N: Recursive types are not allowed at function scope\n\n    def bar(nt: MyNamedTuple) -> MyNamedTuple:\n        return nt\n\n    x: MyNamedTuple\n    reveal_type(x.parent) # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n-- Some crazy self-referential named tuples and types dicts\n-- to be sure that everything works\n\n[case testCrossFileNamedTupleForwardRefs]\nimport a\n[file a.py]\nimport b\nfrom typing import Any, NamedTuple\n\nclass A:\n    def a(self, b: 'b.B') -> str:\n        return 'a'\nATuple = NamedTuple('ATuple', [('a', Any)])\n\n[file b.py]\nimport a\n\nclass B:\n    def b(self, a: 'a.A') -> str:\n        return 'b'\n    def aWithTuple(self, atuple: 'a.ATuple') -> str:\n        return 'a'\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testSelfRefNT1]\nfrom typing import Tuple, NamedTuple\n\ndef test() -> None:\n    Node = NamedTuple('Node', [\n            ('name', str),\n            ('children', Tuple['Node', ...]),  # E: Cannot resolve name \"Node\" (possible cyclic definition) \\\n                                               # N: Recursive types are not allowed at function scope\n        ])\n    n: Node\n    reveal_type(n) # N: Revealed type is \"Tuple[builtins.str, builtins.tuple[Any, ...], fallback=__main__.Node@4]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNT2]\nfrom typing import Tuple, NamedTuple\n\ndef test() -> None:\n    A = NamedTuple('A', [\n            ('x', str),\n            ('y', Tuple['B', ...]),  # E: Cannot resolve name \"B\" (possible cyclic definition) \\\n                                     # N: Recursive types are not allowed at function scope\n        ])\n    class B(NamedTuple):\n        x: A\n        y: int\n\n    n: A\n    reveal_type(n) # N: Revealed type is \"Tuple[builtins.str, builtins.tuple[Any, ...], fallback=__main__.A@4]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNT3]\nfrom typing import NamedTuple, Tuple\n\ndef test() -> None:\n    class B(NamedTuple):\n        x: Tuple[A, int]  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                          # N: Recursive types are not allowed at function scope\n        y: int\n\n    A = NamedTuple('A', [\n            ('x', str),\n            ('y', 'B'),\n        ])\n    n: B\n    m: A\n    reveal_type(n.x) # N: Revealed type is \"Tuple[Any, builtins.int]\"\n    reveal_type(m[0]) # N: Revealed type is \"builtins.str\"\n    lst = [m, n]\n    reveal_type(lst[0]) # N: Revealed type is \"Tuple[builtins.object, builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNT4]\nfrom typing import NamedTuple\n\ndef test() -> None:\n    class B(NamedTuple):\n        x: A  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n              # N: Recursive types are not allowed at function scope\n        y: int\n\n    class A(NamedTuple):\n        x: str\n        y: B\n\n    n: A\n    reveal_type(n.y[0]) # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNT5]\nfrom typing import NamedTuple\n\ndef test() -> None:\n    B = NamedTuple('B', [\n            ('x', A),  # E: Cannot resolve name \"A\" (possible cyclic definition)  \\\n                       # N: Recursive types are not allowed at function scope \\\n                       # E: Name \"A\" is used before definition\n            ('y', int),\n        ])\n    A = NamedTuple('A', [\n            ('x', str),\n            ('y', 'B'),\n        ])\n    n: A\n    def f(m: B) -> None: pass\n    reveal_type(n) # N: Revealed type is \"Tuple[builtins.str, Tuple[Any, builtins.int, fallback=__main__.B@4], fallback=__main__.A@8]\"\n    reveal_type(f) # N: Revealed type is \"def (m: Tuple[Any, builtins.int, fallback=__main__.B@4])\"\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveNamedTupleInBases]\nfrom typing import List, NamedTuple, Union\n\ndef test() -> None:\n    Exp = Union['A', 'B']  # E: Cannot resolve name \"Exp\" (possible cyclic definition) \\\n                           # N: Recursive types are not allowed at function scope \\\n                           # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                           # N: Recursive types are not allowed at function scope\n    class A(NamedTuple('A', [('attr', List[Exp])])): pass\n    class B(NamedTuple('B', [('val', object)])): pass\n\n    exp: Exp\n    reveal_type(exp)  # N: Revealed type is \"Union[Any, Tuple[builtins.object, fallback=__main__.B@6]]\"\n    if isinstance(exp, A):\n        reveal_type(exp[0][0])  # N: Revealed type is \"Union[Any, Tuple[builtins.object, fallback=__main__.B@6]]\"\n        reveal_type(exp.attr[0])  # N: Revealed type is \"Union[Any, Tuple[builtins.object, fallback=__main__.B@6]]\"\n    if isinstance(exp, B):\n        reveal_type(exp.val)  # N: Revealed type is \"builtins.object\"\n    reveal_type(A([B(1), B(2)]))  # N: Revealed type is \"Tuple[builtins.list[Union[Any, Tuple[builtins.object, fallback=__main__.B@6]]], fallback=__main__.A@5]\"\n[builtins fixtures/isinstancelist.pyi]\n[out]\n\n[case testNamedTupleImportCycle]\n\nimport b\n[file a.py]\nclass C:\n    pass\n\nfrom b import tp\nx: tp\nreveal_type(x.x)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(tp)  # N: Revealed type is \"def (x: builtins.int) -> Tuple[builtins.int, fallback=b.tp]\"\ntp('x')  # E: Argument 1 to \"tp\" has incompatible type \"str\"; expected \"int\"\n\n[file b.py]\nfrom a import C\nfrom typing import NamedTuple\n\ntp = NamedTuple('tp', [('x', int)])\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testSubclassOfRecursiveNamedTuple]\nfrom typing import List, NamedTuple\n\ndef test() -> None:\n    class Command(NamedTuple):\n        subcommands: List['Command']  # E: Cannot resolve name \"Command\" (possible cyclic definition) \\\n                                      # N: Recursive types are not allowed at function scope\n\n    class HelpCommand(Command):\n        pass\n\n    hc = HelpCommand(subcommands=[])\n    reveal_type(hc)  # N: Revealed type is \"Tuple[builtins.list[Any], fallback=__main__.HelpCommand@7]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testUnsafeOverlappingNamedTuple]\nfrom typing import NamedTuple\n\nclass Real(NamedTuple):\n    def __sub__(self, other: Real) -> str: return \"\"\nclass Fraction(Real):\n    def __rsub__(self, other: Real) -> Real: return other  # E: Signatures of \"__rsub__\" of \"Fraction\" and \"__sub__\" of \"Real\" are unsafely overlapping\n[builtins fixtures/tuple.pyi]\n\n[case testForwardReferenceInNamedTuple]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    b: 'B'\n    x: int\n\nclass B:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeNamedTupleClassmethod]\nfrom typing import Type, NamedTuple\nclass D(NamedTuple):\n    @classmethod\n    def f(cls) -> None: pass\n\nd: Type[D]\nd.g()  # E: \"Type[D]\" has no attribute \"g\"\nd.f()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeNamedTupleCall]\n\nfrom typing import NamedTuple\n\nThing = NamedTuple('Thing', [('s', str), ('n', int)])\n\nclass CallableTuple(Thing):\n    def __call__(self) -> None:\n        pass\n\no = CallableTuple('hello ', 12)\no()\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleSubclassMulti]\nfrom typing import NamedTuple\n\nclass Base:\n    pass\nclass BaseTuple(NamedTuple):\n    value: float\nclass MyTuple(BaseTuple, Base):\n    pass\n\ndef f(o: Base) -> None:\n    if isinstance(o, MyTuple):\n        reveal_type(o.value)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testNamedTupleNew]\nfrom typing import NamedTuple\n\nBase = NamedTuple('Base', [('param', int)])\n\nclass Child(Base):\n    def __new__(cls, param: int = 1) -> 'Child':\n        return Base.__new__(cls, param)\n\nBase(param=10)\nChild(param=10)\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleClassMethodWithGenericReturnValue]\nfrom typing import TypeVar, Type, NamedTuple\n\nT = TypeVar('T', bound='Parent')\n\nclass Parent(NamedTuple):\n    x: str\n\n    @classmethod\n    def class_method(cls: Type[T]) -> T:\n        return cls(x='text')\n\nclass Child(Parent):\n    pass\n\nreveal_type(Child.class_method())  # N: Revealed type is \"Tuple[builtins.str, fallback=__main__.Child]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testNamedTupleAsConditionalStrictOptionalDisabled]\n# flags: --no-strict-optional --warn-unreachable\nfrom typing import NamedTuple\n\nclass C(NamedTuple):\n    a: int\n    b: str\n\na: C\nif not a:\n    1()  # E: \"int\" not callable\nb = (1, 2)\nif not b:\n    ''()  # E: \"str\" not callable\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleDoubleForward]\n# flags: --disable-error-code=used-before-def\nfrom typing import Union, Mapping, NamedTuple\n\nclass MyBaseTuple(NamedTuple):\n    base_field_1: int\n    base_field_2: int\n\nMyBaseTupleMapping = Mapping[MyBaseTuple, int]\nMyTupleUnion = Union[MyTupleA, MyTupleB]\n\nclass MyTupleA(NamedTuple):\n    field_1: MyBaseTupleMapping\n    field_2: MyBaseTuple\n\n\nclass MyTupleB(NamedTuple):\n    field_1: MyBaseTupleMapping\n    field_2: MyBaseTuple\n\nu: MyTupleUnion\nreveal_type(u.field_1)  # N: Revealed type is \"typing.Mapping[Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple], builtins.int]\"\nreveal_type(u.field_2)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple]\"\nreveal_type(u[0])  # N: Revealed type is \"typing.Mapping[Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple], builtins.int]\"\nreveal_type(u[1])  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAssignNamedTupleAsAttribute]\nfrom typing import NamedTuple\n\nclass A:\n    def __init__(self) -> None:\n        self.b = NamedTuple('x', [('s', str), ('n', int)])  # E: NamedTuple type as an attribute is not supported\n\nreveal_type(A().b)  # N: Revealed type is \"typing.NamedTuple\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n\n[case testEmptyNamedTupleTypeRepr]\nfrom typing import NamedTuple\n\nN = NamedTuple('N', [])\nn: N\nreveal_type(N)  # N: Revealed type is \"def () -> Tuple[(), fallback=__main__.N]\"\nreveal_type(n)  # N: Revealed type is \"Tuple[(), fallback=__main__.N]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleWrongfile]\nfrom typing import NamedTuple\nfrom b import Type1\nType2 = NamedTuple('Type2', [('x', Type1)])\n[file b.py]\nfrom typing import NamedTuple\n\ndef foo():\n    pass\n\nType1 = NamedTuple('Type1', [('foo', foo)])  # E: Function \"b.foo\" is not valid as a type  # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleTypeNameMatchesVariableName]\nfrom typing import NamedTuple\nfrom collections import namedtuple\n\nA = NamedTuple('X', [('a', int)])  # E: First argument to namedtuple() should be \"A\", not \"X\"\nB = namedtuple('X', ['a'])         # E: First argument to namedtuple() should be \"B\", not \"X\"\n\nC = NamedTuple('X', [('a', 'Y')])  # E: First argument to namedtuple() should be \"C\", not \"X\"\nclass Y: ...\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleTypeIsASuperTypeOfOtherNamedTuples]\nfrom typing import Tuple, NamedTuple\n\nclass Bar(NamedTuple):\n    name: str = \"Bar\"\n\nclass Baz(NamedTuple):\n    a: str\n    b: str\n\nclass Biz(Baz): ...\nclass Other: ...\nclass Both1(Bar, Other): ...\nclass Both2(Other, Bar): ...\nclass Both3(Biz, Other): ...\n\ndef print_namedtuple(obj: NamedTuple) -> None:\n    reveal_type(obj._fields)  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n\nb1: Bar\nb2: Baz\nb3: Biz\nb4: Both1\nb5: Both2\nb6: Both3\nprint_namedtuple(b1)  # ok\nprint_namedtuple(b2)  # ok\nprint_namedtuple(b3)  # ok\nprint_namedtuple(b4)  # ok\nprint_namedtuple(b5)  # ok\nprint_namedtuple(b6)  # ok\n\nprint_namedtuple(1)  # E: Argument 1 to \"print_namedtuple\" has incompatible type \"int\"; expected \"NamedTuple\"\nprint_namedtuple(('bar',))  # E: Argument 1 to \"print_namedtuple\" has incompatible type \"Tuple[str]\"; expected \"NamedTuple\"\nprint_namedtuple((1, 2))  # E: Argument 1 to \"print_namedtuple\" has incompatible type \"Tuple[int, int]\"; expected \"NamedTuple\"\nprint_namedtuple((b1,))  # E: Argument 1 to \"print_namedtuple\" has incompatible type \"Tuple[Bar]\"; expected \"NamedTuple\"\nt: Tuple[str, ...]\nprint_namedtuple(t)  # E: Argument 1 to \"print_namedtuple\" has incompatible type \"Tuple[str, ...]\"; expected \"NamedTuple\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNamedTupleTypeIsASuperTypeOfOtherNamedTuplesReturns]\nfrom typing import Tuple, NamedTuple\n\nclass Bar(NamedTuple):\n    n: int\n\nclass Baz(NamedTuple):\n    a: str\n    b: str\n\nclass Biz(Bar): ...\nclass Other: ...\nclass Both1(Bar, Other): ...\nclass Both2(Other, Bar): ...\nclass Both3(Biz, Other): ...\n\ndef good1() -> NamedTuple:\n    b: Bar\n    return b\ndef good2() -> NamedTuple:\n    b: Baz\n    return b\ndef good3() -> NamedTuple:\n    b: Biz\n    return b\ndef good4() -> NamedTuple:\n    b: Both1\n    return b\ndef good5() -> NamedTuple:\n    b: Both2\n    return b\ndef good6() -> NamedTuple:\n    b: Both3\n    return b\n\ndef bad1() -> NamedTuple:\n    return 1  # E: Incompatible return value type (got \"int\", expected \"NamedTuple\")\ndef bad2() -> NamedTuple:\n    return ()  # E: Incompatible return value type (got \"Tuple[()]\", expected \"NamedTuple\")\ndef bad3() -> NamedTuple:\n    return (1, 2)  # E: Incompatible return value type (got \"Tuple[int, int]\", expected \"NamedTuple\")\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testBoolInTuplesRegression]\n# https://github.com/python/mypy/issues/11701\nfrom typing import NamedTuple, Literal, List, Tuple\n\nC = NamedTuple(\"C\", [(\"x\", Literal[True, False])])\n\nT = Tuple[Literal[True, False]]\n\n# Was error here:\n# Incompatible types in assignment (expression has type \"List[C]\", variable has type \"List[C]\")\nx: List[C] = [C(True)]\n\nt: T\n\n# Was error here:\n# Incompatible types in assignment (expression has type \"List[Tuple[bool]]\",\n# variable has type \"List[Tuple[Union[Literal[True], Literal[False]]]]\")\ny: List[T] = [t]\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNamedTupleWithBoolNarrowsToBool]\n# flags: --warn-unreachable\nfrom typing import NamedTuple\n\nclass C(NamedTuple):\n    x: int\n\n    def __bool__(self) -> bool:\n        pass\n\ndef foo(c: C) -> None:\n    if c:\n        reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.C]\"\n    else:\n        reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.C]\"\n\ndef bar(c: C) -> None:\n    if not c:\n        reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.C]\"\n    else:\n        reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.C]\"\n\nclass C1(NamedTuple):\n    x: int\n\ndef foo1(c: C1) -> None:\n    if c:\n        reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.C1]\"\n    else:\n        c  # E: Statement is unreachable\n\ndef bar1(c: C1) -> None:\n    if not c:\n        c  # E: Statement is unreachable\n    else:\n        reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.C1]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testInvalidNamedTupleWithinFunction]\nfrom collections import namedtuple\n\ndef f(fields) -> None:\n    TupleType = namedtuple(\"TupleType\", fields) \\\n        # E: List or tuple literal expected as the second argument to \"namedtuple()\"\n    class InheritFromTuple(TupleType):\n        pass\n    t: TupleType\n    it: InheritFromTuple\n    NT2 = namedtuple(\"bad\", \"x\") # E: First argument to namedtuple() should be \"NT2\", not \"bad\"\n    nt2: NT2 = NT2(x=1)\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleHasMatchArgs]\n# flags: --python-version 3.10\nfrom typing import NamedTuple\nclass One(NamedTuple):\n    bar: int\n    baz: str\no: One\nreveal_type(o.__match_args__)  # N: Revealed type is \"Tuple[Literal['bar'], Literal['baz']]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNamedTupleHasNoMatchArgsOldVersion]\n# flags: --python-version 3.9\nfrom typing import NamedTuple\nclass One(NamedTuple):\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/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNamedTupleNoBytes]\nfrom collections import namedtuple\nfrom typing import NamedTuple\n\nNT1 = namedtuple('NT1', b'x y z')  # E: List or tuple literal expected as the second argument to \"namedtuple()\"\nNT2 = namedtuple(b'NT2', 'x y z')  # E: \"namedtuple()\" expects a string literal as the first argument \\\n                                   # E: Argument 1 to \"namedtuple\" has incompatible type \"bytes\"; expected \"str\"\nNT3 = namedtuple('NT3', [b'x', 'y'])  # E: String literal expected as \"namedtuple()\" item\n\nNT4 = NamedTuple('NT4', [('x', int), (b'y', int)])  # E: Invalid \"NamedTuple()\" field name\nNT5 = NamedTuple(b'NT5', [('x', int), ('y', int)])  # E: \"NamedTuple()\" expects a string literal as the first argument\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleCreation]\nfrom typing import Generic, NamedTuple, TypeVar\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\n\nnts: NT[str]\nreveal_type(nts)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.NT[builtins.str]]\"\nreveal_type(nts.value)  # N: Revealed type is \"builtins.str\"\n\nnti = NT(key=0, value=0)\nreveal_type(nti)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]\"\nreveal_type(nti.value)  # N: Revealed type is \"builtins.int\"\n\nNT[str](key=0, value=0)  # E: Argument \"value\" to \"NT\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleAlias]\nfrom typing import NamedTuple, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\n\nAlias = NT[List[T]]\n\nan: Alias[str]\nreveal_type(an)  # N: Revealed type is \"Tuple[builtins.int, builtins.list[builtins.str], fallback=__main__.NT[builtins.list[builtins.str]]]\"\nAlias[str](key=0, value=0)  # E: Argument \"value\" to \"NT\" has incompatible type \"int\"; expected \"List[str]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleMethods]\nfrom typing import Generic, NamedTuple, TypeVar\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\nx: int\n\nnti: NT[int]\nreveal_type(nti * x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nnts: NT[str]\nreveal_type(nts * x)  # N: Revealed type is \"builtins.tuple[Union[builtins.int, builtins.str], ...]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleCustomMethods]\nfrom typing import Generic, NamedTuple, TypeVar\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\n    def foo(self) -> T: ...\n    @classmethod\n    def from_value(cls, value: T) -> NT[T]: ...\n\nnts: NT[str]\nreveal_type(nts.foo())  # N: Revealed type is \"builtins.str\"\n\nnti = NT.from_value(1)\nreveal_type(nti)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]\"\nNT[str].from_value(1)  # E: Argument 1 to \"from_value\" of \"NT\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleSubtyping]\nfrom typing import Generic, NamedTuple, TypeVar, Tuple\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\n\nnts: NT[str]\nnti: NT[int]\n\ndef foo(x: Tuple[int, ...]) -> None: ...\nfoo(nti)\nfoo(nts)  # E: Argument 1 to \"foo\" has incompatible type \"NT[str]\"; expected \"Tuple[int, ...]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleJoin]\nfrom typing import Generic, NamedTuple, TypeVar, Tuple\n\nT = TypeVar(\"T\", covariant=True)\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\n\nnts: NT[str]\nnti: NT[int]\nx: Tuple[int, ...]\n\nS = TypeVar(\"S\")\ndef foo(x: S, y: S) -> S: ...\nreveal_type(foo(nti, nti))  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]\"\n\nreveal_type(foo(nti, nts))  # N: Revealed type is \"Tuple[builtins.int, builtins.object, fallback=__main__.NT[builtins.object]]\"\nreveal_type(foo(nts, nti))  # N: Revealed type is \"Tuple[builtins.int, builtins.object, fallback=__main__.NT[builtins.object]]\"\n\nreveal_type(foo(nti, x))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(foo(nts, x))  # N: Revealed type is \"builtins.tuple[Union[builtins.int, builtins.str], ...]\"\nreveal_type(foo(x, nti))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(foo(x, nts))  # N: Revealed type is \"builtins.tuple[Union[builtins.int, builtins.str], ...]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleCallSyntax]\nfrom typing import NamedTuple, TypeVar\n\nT = TypeVar(\"T\")\nNT = NamedTuple(\"NT\", [(\"key\", int), (\"value\", T)])\nreveal_type(NT)  # N: Revealed type is \"def [T] (key: builtins.int, value: T`1) -> Tuple[builtins.int, T`1, fallback=__main__.NT[T`1]]\"\n\nnts: NT[str]\nreveal_type(nts)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.NT[builtins.str]]\"\n\nnti = NT(key=0, value=0)\nreveal_type(nti)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]\"\nNT[str](key=0, value=0)  # E: Argument \"value\" to \"NT\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleNoLegacySyntax]\nfrom typing import TypeVar, NamedTuple\n\nT = TypeVar(\"T\")\nclass C(\n    NamedTuple(\"_C\", [(\"x\", int), (\"y\", T)])  # E: Generic named tuples are not supported for legacy class syntax \\\n                                              # N: Use either Python 3 class syntax, or the assignment syntax\n): ...\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNamedTupleSelfItemNotAllowed]\nfrom typing import Self, NamedTuple, Optional\n\nclass NT(NamedTuple):\n    val: int\n    next: Optional[Self]  # E: Self type cannot be used in NamedTuple item type\nNTC = NamedTuple(\"NTC\", [(\"val\", int), (\"next\", Optional[Self])])  # E: Self type cannot be used in NamedTuple item type\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNamedTupleTypingSelfMethod]\nfrom typing import Self, NamedTuple, TypeVar, Generic\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: str\n    val: T\n    def meth(self) -> Self:\n        nt: NT[int]\n        if bool():\n            return nt._replace()  # E: Incompatible return value type (got \"NT[int]\", expected \"Self\")\n        else:\n            return self._replace()\n\nclass SNT(NT[int]): ...\nreveal_type(SNT(\"test\", 42).meth())  # N: Revealed type is \"Tuple[builtins.str, builtins.int, fallback=__main__.SNT]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNoCrashUnsupportedNamedTuple]\nfrom typing import NamedTuple\nclass Test:\n    def __init__(self, field) -> None:\n        self.Item = NamedTuple(\"x\", [(field, str)])  # E: NamedTuple type as an attribute is not supported\n        self.item: self.Item  # E: Name \"self.Item\" is not defined\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNoClassKeywordsForNamedTuple]\nfrom typing import NamedTuple\nclass Test1(NamedTuple, x=1, y=2):  # E: Unexpected keyword argument \"x\" for \"__init_subclass__\" of \"NamedTuple\" \\\n                                    # E: Unexpected keyword argument \"y\" for \"__init_subclass__\" of \"NamedTuple\"\n    ...\n\nclass Meta(type): ...\n\nclass Test2(NamedTuple, metaclass=Meta):  # E: Unexpected keyword argument \"metaclass\" for \"__init_subclass__\" of \"NamedTuple\"\n    ...\n\n# Technically this would work, but it is just easier for the implementation:\nclass Test3(NamedTuple, metaclass=type):  # E: Unexpected keyword argument \"metaclass\" for \"__init_subclass__\" of \"NamedTuple\"\n    ...\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n\n[case testNamedTupleDunderReplace]\n# flags: --python-version 3.13\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    x: int\n\nA(x=0).__replace__(x=1)\nA(x=0).__replace__(x=\"asdf\")  # E: Argument \"x\" to \"__replace__\" of \"A\" has incompatible type \"str\"; expected \"int\"\nA(x=0).__replace__(y=1)  # E: Unexpected keyword argument \"y\" for \"__replace__\" of \"A\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testUnpackSelfNamedTuple]\nimport typing\n\nclass Foo(typing.NamedTuple):\n    bar: int\n    def baz(self: typing.Self) -> None:\n        x, = self\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNameErrorInNamedTupleNestedInFunction1]\nfrom typing import NamedTuple\n\ndef bar() -> None:\n    class MyNamedTuple(NamedTuple):\n        a: int\n        def foo(self) -> None:\n            ...\n    int_set: Set[int]  # E: Name \"Set\" is not defined \\\n                       # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Set\")\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testNameErrorInNamedTupleNestedInFunction2]\nfrom typing import NamedTuple\n\ndef bar() -> None:\n    class MyNamedTuple(NamedTuple):\n        a: int\n        def foo(self) -> None:\n            misspelled_var_name  # E: Name \"misspelled_var_name\" is not defined\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n\n[case testNamedTupleFinalAndClassVar]\nfrom typing import NamedTuple, Final, ClassVar\n\nclass My(NamedTuple):\n    a: Final      # E: Final[...] can't be used inside a NamedTuple\n    b: Final[int] # E: Final[...] can't be used inside a NamedTuple\n    c: ClassVar       # E: ClassVar[...] can't be used inside a NamedTuple\n    d: ClassVar[int]  # E: ClassVar[...] can't be used inside a NamedTuple\n\nFunc = NamedTuple('Func', [\n    ('a', Final),         # E: Final[...] can't be used inside a NamedTuple\n    ('b', Final[int]),    # E: Final[...] can't be used inside a NamedTuple\n    ('c', ClassVar),      # E: ClassVar[...] can't be used inside a NamedTuple\n    ('d', ClassVar[int]), # E: ClassVar[...] can't be used inside a NamedTuple\n])\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n\n[case testGenericNamedTupleRecursiveBound]\nfrom typing import Generic, NamedTuple, TypeVar\nT = TypeVar(\"T\", bound=\"NT\")\nclass NT(NamedTuple, Generic[T]):\n    parent: T\n    item: int\n\ndef main(n: NT[T]) -> None:\n    reveal_type(n.parent)  # N: Revealed type is \"T`-1\"\n    reveal_type(n.item)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-namedtuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-narrowing.test",
    "content": "[case testNarrowingParentWithStrsBasic]\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, Tuple, Union\nfrom typing_extensions import Literal, TypedDict\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\n[case testNarrowingParentWithEnumsBasic]\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, Tuple, Union\nfrom typing_extensions import Literal, TypedDict\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/narrowing.pyi]\n\n[case testNarrowingParentWithIsInstanceBasic]\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, Tuple, Union\nfrom typing_extensions import TypedDict\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/narrowing.pyi]\n\n[case testNarrowingParentMultipleKeys]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[__main__.Object1, __main__.Object2]\"\n\nif x.key is Key.C:\n    reveal_type(x)  # N: Revealed type is \"Union[__main__.Object1, __main__.Object2]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[__main__.Object1, __main__.Object2]\"\n\nif x.key is Key.D:\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[__main__.Object1, __main__.Object2]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingTypedDictParentMultipleKeys]\n# flags: --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import Literal, TypedDict\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': Union[Literal['A'], Literal['C']]})\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key': Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key': Union[Literal['B'], Literal['C']]})]\"\n\nif x['key'] == 'C':\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key': Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key': Union[Literal['B'], Literal['C']]})]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key': Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key': Union[Literal['B'], Literal['C']]})]\"\n\nif x['key'] == 'D':\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key': Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key': Union[Literal['B'], Literal['C']]})]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingPartialTypedDictParentMultipleKeys]\n# flags: --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import Literal, TypedDict\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'?: Union[Literal['A'], Literal['C']]})\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key'?: Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key'?: Union[Literal['B'], Literal['C']]})]\"\n\nif x['key'] == 'C':\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key'?: Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key'?: Union[Literal['B'], Literal['C']]})]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key'?: Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key'?: Union[Literal['B'], Literal['C']]})]\"\n\nif x['key'] == 'D':\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[TypedDict('__main__.TypedDict1', {'key'?: Union[Literal['A'], Literal['C']]}), TypedDict('__main__.TypedDict2', {'key'?: Union[Literal['B'], Literal['C']]})]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingNestedTypedDicts]\nfrom typing import Union\nfrom typing_extensions import TypedDict, Literal\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': Union[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 \"Union[TypedDict('__main__.X', {'inner': Union[TypedDict('__main__.A', {'key': Literal['A']}), TypedDict('__main__.B', {'key': Literal['B']})]}), TypedDict('__main__.Y', {'inner': Union[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': Union[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\n[case testNarrowingParentWithMultipleParents]\nfrom enum import Enum\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[__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 \"Union[__main__.Object1, __main__.Object2, __main__.Object3]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingParentsWithGenerics]\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]\nfrom enum import Enum\nfrom typing import Union, NamedTuple\nfrom typing_extensions import Literal, 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 \"Union[KeyedObject, KeyedTypedDict]\" has no attribute \"key\"\n    reveal_type(impossible_mixture)     # N: Revealed type is \"Union[__main__.KeyedObject, TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})]\"\nelse:\n    reveal_type(impossible_mixture)     # N: Revealed type is \"Union[__main__.KeyedObject, TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})]\"\n\nif impossible_mixture[\"key\"] is Key.A:  # E: Value of type \"Union[KeyedObject, KeyedTypedDict]\" is not indexable\n    reveal_type(impossible_mixture)     # N: Revealed type is \"Union[__main__.KeyedObject, TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})]\"\nelse:\n    reveal_type(impossible_mixture)     # N: Revealed type is \"Union[__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 \"Union[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 \"Union[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 \"Union[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 \"Union[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]\nfrom enum import Enum\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[__main__.Object1, __main__.Object2]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object3\"\n[builtins fixtures/property.pyi]\n\n[case testNarrowingParentWithAny]\nfrom enum import Enum\nfrom typing import Union, Any\nfrom typing_extensions import Literal\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 \"Union[__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 \"Union[Any, Literal[__main__.Key.B]]\"\n    reveal_type(x)      # N: Revealed type is \"Union[__main__.Object1, __main__.Object2, Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingParentsHierarchy]\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[__main__.Parent1, __main__.Parent3]\"\n    reveal_type(x.child)    # N: Revealed type is \"__main__.Child1\"\nelse:\n    reveal_type(x)          # N: Revealed type is \"Union[__main__.Parent1, __main__.Parent2, __main__.Parent3]\"\n    reveal_type(x.child)    # N: Revealed type is \"Union[__main__.Child2, __main__.Child3]\"\n\nif x.child.same_for_1_and_2 is Key.A:\n    reveal_type(x)          # N: Revealed type is \"Union[__main__.Parent1, __main__.Parent2, __main__.Parent3]\"\n    reveal_type(x.child)    # N: Revealed type is \"Union[__main__.Child1, __main__.Child2]\"\nelse:\n    reveal_type(x)          # N: Revealed type is \"Union[__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 \"Union[__main__.Parent1, __main__.Parent2]\"\n    reveal_type(y.child)    # N: Revealed type is \"Union[__main__.Child2, __main__.Child3]\"\n\nif y.child.same_for_1_and_2 is Key.A:\n    reveal_type(y)          # N: Revealed type is \"Union[__main__.Parent1, __main__.Parent2]\"\n    reveal_type(y.child)    # N: Revealed type is \"Union[__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]\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: --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import TypedDict, Literal\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:\n    reveal_type(y)              # E: Statement is unreachable\n    reveal_type(y[\"model\"])\nelse:\n    reveal_type(y)              # N: Revealed type is \"Union[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 \"Union[TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}), TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]})]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingParentsHierarchyTypedDictWithStr]\n# flags: --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import TypedDict, Literal\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':\n    reveal_type(y)              # E: Statement is unreachable\n    reveal_type(y[\"model\"])\nelse:\n    reveal_type(y)              # N: Revealed type is \"Union[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 \"Union[TypedDict('__main__.Model1', {'key': Literal['A']}), TypedDict('__main__.Model2', {'key': Literal['B']})]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingExprPropagation]\nfrom typing import Union\nfrom typing_extensions import Literal\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: --warn-unreachable --strict-equality\nfrom typing_extensions import Literal, Final\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]\nfrom typing_extensions import Literal, Final\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 \"Union[Literal['B'], None]\"\nreveal_type(x_union)      # N: Revealed type is \"Union[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 \"Union[Literal['B'], None]\"\nreveal_type(x_union)      # N: Revealed type is \"Union[Literal['A'], Literal['B'], None]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityRequiresExplicitEnumLiteral]\nfrom typing import Union\nfrom typing_extensions import Literal, Final\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 testNarrowingEqualityDisabledForCustomEquality]\nfrom typing import Union\nfrom typing_extensions import Literal\nfrom enum import Enum\n\nclass Custom:\n    def __eq__(self, other: object) -> bool: return True\n\nclass Default: pass\n\nx1: Union[Custom, Literal[1], Literal[2]]\nif x1 == 1:\n    reveal_type(x1)  # N: Revealed type is \"Union[__main__.Custom, Literal[1], Literal[2]]\"\nelse:\n    reveal_type(x1)  # N: Revealed type is \"Union[__main__.Custom, Literal[1], Literal[2]]\"\n\nx2: Union[Default, Literal[1], Literal[2]]\nif x2 == 1:\n    reveal_type(x2)  # N: Revealed type is \"Literal[1]\"\nelse:\n    reveal_type(x2)  # N: Revealed type is \"Union[__main__.Default, Literal[2]]\"\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 \"__main__.CustomEnum\"\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 testNarrowingEqualityDisabledForCustomEqualityChain]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import Literal\n\nclass Custom:\n    def __eq__(self, other: object) -> bool: return True\n\nclass Default: pass\n\nx: Literal[1, 2, None]\ny: Custom\nz: Default\n\n# We could maybe try doing something clever, but for simplicity we\n# treat the whole chain as contaminated and mostly disable narrowing.\n#\n# The only exception is that we do at least strip away the 'None'. We\n# (perhaps optimistically) assume no custom class would be pathological\n# enough to declare itself to be equal to None and so permit this narrowing,\n# since it's often convenient in practice.\nif 1 == x == y:\n    reveal_type(x)   # N: Revealed type is \"Union[Literal[1], Literal[2]]\"\n    reveal_type(y)   # N: Revealed type is \"__main__.Custom\"\nelse:\n    reveal_type(x)   # N: Revealed type is \"Union[Literal[1], Literal[2], None]\"\n    reveal_type(y)   # N: Revealed type is \"__main__.Custom\"\n\n# No contamination here\nif 1 == x == z:      # E: Non-overlapping equality check (left operand type: \"Optional[Literal[1, 2]]\", right operand type: \"Default\")\n    reveal_type(x)   # E: Statement is unreachable\n    reveal_type(z)\nelse:\n    reveal_type(x)   # N: Revealed type is \"Union[Literal[1], Literal[2], None]\"\n    reveal_type(z)   # N: Revealed type is \"__main__.Default\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingUnreachableCases]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[Literal[1], Literal[2]]\"\n    reveal_type(c)  # N: Revealed type is \"Union[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 \"Union[Literal[1], Literal[2]]\"\n    reveal_type(c)  # N: Revealed type is \"Union[Literal[2], Literal[3]]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingUnreachableCases2]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[Literal[1], Literal[2], Literal[3], Literal[4]]\"\n    reveal_type(b)  # N: Revealed type is \"Union[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]\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[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]\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 \"Union[Literal[''], Literal[b''], Literal[0]]\"\n\n[case testNarrowingIsInstanceFinalSubclass]\n# flags: --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 & 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 & 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 & F2\" cannot exist: \"F1\" is final \\\n                        # E: Subclass of \"F1 & 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: --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 & F1\" cannot exist: \"F1\" is final \\\n                          # E: Subclass of \"F2 & F1\" cannot exist: \"F2\" is final \\\n                          # E: Subclass of \"F2 & 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 \"Union[__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: --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]\nfrom typing import Union\nfrom typing_extensions import Literal\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 \"Union[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]\nfrom typing import Optional\nfrom typing_extensions import Literal\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 \"Union[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]\nfrom typing import Optional\nfrom typing_extensions import Literal\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 \"Union[Literal[False], None]\"\nreveal_type(opt_bool_val)   # N: Revealed type is \"Union[builtins.bool, None]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingBooleanBoolOp]\nfrom typing import Optional\nfrom typing_extensions import Literal\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]\nfrom typing import Union\nfrom typing_extensions import TypedDict, Literal\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\n[case testNarrowingUsingMetaclass]\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]\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 \"Never\"\n    else:\n        reveal_type(b)  # N: Revealed type is \"__main__.B\"\n\n[case testNarrowingNestedUnionOfTypedDicts]\nfrom typing import Union\nfrom typing_extensions import Literal, TypedDict\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\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowingRuntimeCover]\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\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 \"Union[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 \"Union[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]\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]\nfrom typing import Optional\n\nclass A: ...\n\nval: Optional[A]\n\nif val == None:\n    reveal_type(val)  # N: Revealed type is \"Union[__main__.A, 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 \"Union[__main__.A, None]\"\n\nif val in (None,):\n    reveal_type(val)  # N: Revealed type is \"Union[__main__.A, None]\"\nelse:\n    reveal_type(val)  # N: Revealed type is \"Union[__main__.A, None]\"\nif val not in (None,):\n    reveal_type(val)  # N: Revealed type is \"Union[__main__.A, None]\"\nelse:\n    reveal_type(val)  # N: Revealed type is \"Union[__main__.A, None]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingWithTupleOfTypes]\nfrom typing import Tuple, Type\n\nclass Base: ...\n\nclass Impl1(Base): ...\nclass Impl2(Base): ...\n\nimpls: Tuple[Type[Base], ...]\nif bool():\n    impls = (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\nclass Base: ...\n\nclass Impl1(Base): ...\nclass Impl2(Base): ...\n\nsome: int | Base\n\nimpls: tuple[type[Base], ...]\nif bool():\n    impls = (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 \"Union[builtins.int, __main__.Base]\"\n\nraw: tuple[type, ...]\nif isinstance(some, raw):\n    reveal_type(some)  # N: Revealed type is \"Union[builtins.int, __main__.Base]\"\nelse:\n    reveal_type(some)  # N: Revealed type is \"Union[builtins.int, __main__.Base]\"\n[builtins fixtures/dict.pyi]\n\n[case testNarrowingWithAnyOps]\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 \"Union[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 \"Union[__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 testNarrowingLenItemAndLenCompare]\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]\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]\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]\nfrom typing import Union, List\n\nx: Union[str, List[int]]\nif len(x) == 3:\n    reveal_type(x) # N: Revealed type is \"Union[builtins.str, builtins.list[builtins.int]]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"Union[builtins.str, builtins.list[builtins.int]]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenAnyListElseNotAffected]\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]\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]\nfrom typing import Tuple, Union\nfrom typing_extensions import Final\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]\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 \"Union[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 \"Union[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 \"Union[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 \"Union[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]\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 \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"Union[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\nfrom typing import Tuple\n\nVarTuple = Tuple[int, ...]\n\nx: VarTuple\nif len(x) < 3:\n    reveal_type(x) # N: Revealed type is \"Union[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\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\nfrom typing import Tuple\n\nx: Tuple[int, ...]\nif 1 < len(x) < 4:\n    reveal_type(x) # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"Union[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: --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 \"Union[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 \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenMixedTypes]\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 \"Union[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 \"Union[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 \"Union[Tuple[builtins.int, builtins.int], builtins.list[builtins.int]]\"\n    a, b = x\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[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]\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]\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: --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]\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]\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 \"Union[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: --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\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]\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\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 \"Union[Tuple[()], None]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBareExpressionWithNoneImprecise]\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 \"Union[builtins.tuple[builtins.int, ...], None]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenMixWithAnyPrecise]\n# flags: --enable-incomplete-feature=PreciseTupleTypes\nfrom typing import Any\n\nx: Any\nif isinstance(x, (list, tuple)) and len(x) == 0:\n    reveal_type(x)  # N: Revealed type is \"Union[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 \"Union[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]\nfrom typing import Any\n\nx: Any\nif isinstance(x, (list, tuple)) and len(x) == 0:\n    reveal_type(x)  # N: Revealed type is \"Union[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 \"Union[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]\nfrom typing import Tuple, Union\nfrom typing_extensions import Literal\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 \"Union[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 \"Union[Tuple[builtins.int], Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[Tuple[builtins.int], Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionOfVariadicTuples]\nfrom typing import Tuple, Union\n\nx: Union[Tuple[int, ...], Tuple[str, ...]]\nif len(x) == 2:\n    reveal_type(x)  # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.str, builtins.str]]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.tuple[builtins.int, ...], builtins.tuple[builtins.str, ...]]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionOfNamedTuples]\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]\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]\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\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]\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 \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[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 \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.int, builtins.int, builtins.int]]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionWithUnreachable]\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]\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]\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]\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\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\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__.X & __main__.Y\"\nif isinstance(x, (Y, NoneType)):\n    reveal_type(x)  # N: Revealed type is \"__main__.X & __main__.Y\"\nif isinstance(x, (Y, Z, NoneType)):\n    reveal_type(x)  # N: Revealed type is \"__main__.X & __main__.Y\"\nif isinstance(x, (Z, NoneType)):  # E: Subclass of \"X & 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: --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]\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# mypy: strict-equality\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 \"Union[builtins.int, Any]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Union[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# mypy: strict-equality\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 \"Union[__main__.IE, __main__.MyDecimal]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Union[__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 \"Union[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 \"Union[__main__.IE, __main__.IE2]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Union[__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 \"Union[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 \"Union[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 \"Union[__main__.IE, Any]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Union[__main__.IE, 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 \"Union[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# 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 testConsistentNarrowingEqAndIn]\n# flags: --python-version 3.10\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 \"Union[builtins.str, builtins.int]\"\n        y = x\n\n    if x in [\"x\"]:\n        # TODO: we should fix this reveal https://github.com/python/mypy/issues/3229\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n        y = x\n        z = x\n    z = y\n[builtins fixtures/primitives.pyi]\n\n[case testConsistentNarrowingInWithCustomEq]\n# flags: --python-version 3.10\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 f(x: C) -> None:\n    if x in [D(5)]:\n        reveal_type(x)  # D  # N: Revealed type is \"__main__.C\"\n\nf(C(5))\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingTypeVarNone]\n# flags: --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: --nonlocal-partial-types\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 \"Union[builtins.int, None]\"\n\ndef f() -> bool: ...\n\ny = None\nwhile f():\n    reveal_type(y)  # N: Revealed type is \"None\" \\\n                    # N: Revealed type is \"Union[builtins.int, None]\"\n    y = 1\nreveal_type(y)  # N: Revealed type is \"Union[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\n[builtins fixtures/primitives.pyi]\n\n[case testAvoidFalseUnreachableInLoop]\n# flags: --warn-unreachable --python-version 3.11\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\n[builtins fixtures/bool.pyi]\n\n[case testAvoidFalseRedundantExprInLoop]\n# flags: --enable-error-code redundant-expr --python-version 3.11\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\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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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()\n[file b.py]\nfrom a import A\nclass B: pass\nx: A\nx()\n[out]\ntmp/b.py:4: error: \"A\" not callable\ntmp/a.py:4: error: \"B\" 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 mypy_extensions 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 mypy_extensions 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/tuple.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 mypy_extensions 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/tuple.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 \"Union[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 \"Union[__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 \"Union[__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 \"Union[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 \"Union[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\" \\\n           # N: \"XY\" of \"D\" is a constrained type variable, it is not generic\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\" \\\n           # N: \"XY\" of \"D\" is a constrained type variable, it is not generic\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\" \\\n           # N: \"XY\" of \"D\" is a constrained type variable, it is not generic\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  # 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__.D\"\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__.E\"\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 \"Union[builtins.int, builtins.list[builtins.int]]\"\nreveal_type(y[0])  # N: Revealed type is \"Union[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:6: note: Recursive types are not allowed at function scope\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 \"Union[__main__.B, __main__.C]\"\nreveal_type(x[0])  # N: Revealed type is \"Union[__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\" \\\n        # N: \"T\" of \"C\" is a constrained type variable, it is not generic\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]\nfrom typing import TypeVar, Generic, NamedTuple, NewType, Union, Any, cast, overload\nfrom mypy_extensions import TypedDict\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/tuple.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]\ny: List[str]\n\nreveal_type(x)  # N: Revealed type is \"Union[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 basedtyping import FunctionType\n\ndef dec(f: FunctionType[[int], None]) -> FunctionType[[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[Union[__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 \"Union[def () -> typing.Iterator[builtins.int], def () -> typing.Iterator[builtins.str]]\"\nfor nx in nt:\n    reveal_type(nx) # N: Revealed type is \"Union[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 \"Union[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:8: note: Recursive types are not allowed at function scope\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)\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]\ny: B[B[Any]]\nreveal_type(y.x)\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\ntmp/b.py:8: error: Type argument \"int\" of \"B\" must be a subtype of \"B[Any]\"\ntmp/b.py:10: note: Revealed type is \"b.B[Any]\"\ntmp/a.py:5: error: Cannot redefine \"T\" as a type variable\ntmp/a.py:5: error: Invalid assignment target\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)\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]\ny: B[B[Any]]\nreveal_type(y.x)\n[out]\ntmp/b.py:9: error: Type argument \"int\" of \"B\" must be a subtype of \"B[Any]\"\ntmp/b.py:11: note: Revealed type is \"b.B[Any]\"\ntmp/a.py:5: error: Cannot redefine \"T\" as a type variable\ntmp/a.py:5: error: Invalid assignment target\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 testNewAnalyzerAddedSubStarImport_incremental]\n# TODO: This can be removed once testAddedSubStarImport is enabled in check-incremental.test.\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 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 NewType\nfrom typing_extensions import Final, Literal\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_extensions 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\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: 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: 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 # 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 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 Union, Any\nfrom typing_extensions import TypedDict\n\nclass T(TypedDict):\n    b: b.T\n\nclass b:\n    T: Union[Any]\n[builtins fixtures/tuple.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"
  },
  {
    "path": "test-data/unit/check-newsyntax.test",
    "content": "[case testNewSyntaxSyntaxError]\nx: int: int  # E: invalid syntax\n[out]\n\n[case testNewSyntaxBasics]\nx: int\nx = 5\ny: int = 5\n\na: str\na = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nb: str = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nzzz: int\nzzz: str  # E: Name \"zzz\" already defined on line 9\n[out]\n\n[case testNewSyntaxWithDict]\nfrom typing import Dict, Any\n\nd: Dict[int, str] = {}\nd[42] = 'ab'\nd[42] = 42  # E: Incompatible types in assignment (expression has type \"int\", target has type \"str\")\nd['ab'] = 'ab'  # E: Invalid index type \"str\" for \"Dict[int, str]\"; expected type \"int\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testNewSyntaxWithRevealType]\nfrom typing import Dict\n\ndef tst_local(dct: Dict[int, T]) -> Dict[T, int]:\n    ret: Dict[T, int] = {}\n    return ret\n\nreveal_type(tst_local({1: 'a'}))  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testNewSyntaxWithInstanceVars]\nclass TstInstance:\n    a: str\n    def __init__(self) -> None:\n        self.x: int\n\nTstInstance().x = 5\nTstInstance().x = 'ab'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nTstInstance().a = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nTstInstance().a = 'ab'\n[out]\n\n[case testNewSyntaxWithClassVars]\nclass CCC:\n    a: str = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"str\")\n[out]\n\n[case testNewSyntaxWithStrictOptional]\nstrict: int\nstrict = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\nstrict2: int = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n[out]\n\n[case testNewSyntaxWithStrictOptionalFunctions]\ndef f() -> None:\n    x: int\n    if int():\n        x = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n[out]\n\n[case testNewSyntaxWithStrictOptionalClasses]\nclass C:\n    def meth(self) -> None:\n        x: int = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n        self.x: int = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n[out]\n\n[case testNewSyntaxSpecialAssign]\nclass X:\n    x: str\n    x[0]: int\n    x.x: int\n\n[out]\nmain:3: error: Unexpected type declaration\nmain:3: error: Unsupported target for indexed assignment (\"str\")\nmain:4: error: Type cannot be declared in assignment to non-self attribute\nmain:4: error: \"str\" has no attribute \"x\"\n\n[case testNewSyntaxFStringBasics]\nf'foobar'\nf'{\"foobar\"}'\nf'foo{\"bar\"}'\nf'.{1}.'\nf'{type(1)}'\na: str\na = f'foobar'\na = f'{\"foobar\"}'\n[builtins fixtures/f_string.pyi]\n\n[case testNewSyntaxFStringExpressionsOk]\nf'.{1 + 1}.'\nf'.{1 + 1}.{\"foo\" + \"bar\"}'\n[builtins fixtures/f_string.pyi]\n\n[case testNewSyntaxFStringExpressionsErrors]\nf'{1 + \"\"}'\nf'.{1 + \"\"}'\n[builtins fixtures/f_string.pyi]\n[out]\nmain:1: error: Unsupported operand types for + (\"int\" and \"str\")\nmain:2: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testNewSyntaxFStringParseFormatOptions]\nvalue = 10.5142\nwidth = 10\nprecision = 4\nf'result: {value:{width}.{precision}}'\n[builtins fixtures/f_string.pyi]\n\n[case testNewSyntaxFStringSingleField]\nv = 1\nreveal_type(f'{v}') # N: Revealed type is \"builtins.str\"\nreveal_type(f'{1}') # N: Revealed type is \"builtins.str\"\n[builtins fixtures/f_string.pyi]\n\n[case testFeatureVersionSuggestion]\n# flags: --python-version 3.99\nx *** x this is what future python looks like public static void main String[] args await goto exit\n[out]\nmain:2: error: invalid syntax; you likely need to run mypy using Python 3.99 or newer\n"
  },
  {
    "path": "test-data/unit/check-newtype.test",
    "content": "-- Checks NewType(...)\n\n-- Checks for basic functionality\n\n[case testNewTypePEP484Example1]\nfrom typing import NewType\n\nUserId = NewType('UserId', int)\n\ndef name_by_id(user_id: UserId) -> str:\n    return \"foo\"\n\nUserId('user')  # E: Argument 1 to \"UserId\" has incompatible type \"str\"; expected \"int\"\nname_by_id(42)  # E: Argument 1 to \"name_by_id\" has incompatible type \"int\"; expected \"UserId\"\nname_by_id(UserId(42))\n\nid = UserId(5)\nnum = id + 1\n\nreveal_type(id)  # N: Revealed type is \"__main__.UserId\"\nreveal_type(num)  # N: Revealed type is \"builtins.int\"\n\n[targets __main__, __main__.UserId.__init__, __main__.name_by_id]\n\n[case testNewTypePEP484Example2]\nfrom typing import NewType\n\nclass PacketId:\n    def __init__(self, major: int, minor: int) -> None:\n        self._major = major\n        self._minor = minor\n\nTcpPacketId = NewType('TcpPacketId', PacketId)\n\npacket = PacketId(100, 100)\ntcp_packet = TcpPacketId(packet)\ntcp_packet = TcpPacketId(127, 0)\n\n[out]\nmain:12: error: Too many arguments for \"TcpPacketId\"\nmain:12: error: Argument 1 to \"TcpPacketId\" has incompatible type \"int\"; expected \"PacketId\"\n\n[case testNewTypeWithTuples]\nfrom typing import NewType, Tuple\nTwoTuple = NewType('TwoTuple', Tuple[int, str])\na = TwoTuple((3, \"a\"))\nb = TwoTuple((\"a\", 3))  # E: Argument 1 to \"TwoTuple\" has incompatible type \"Tuple[str, int]\"; expected \"Tuple[int, str]\"\n\nreveal_type(a[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(a[1])  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNewTypeWithLists]\nfrom typing import NewType, List\nUserId = NewType('UserId', int)\nIdList = NewType('IdList', List[UserId])\n\nbad1 = IdList([1])  # E: List item 0 has incompatible type \"int\"; expected \"UserId\"\n\nfoo = IdList([])\nfoo.append(3)  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"UserId\"\nfoo.append(UserId(3))\nfoo.extend([UserId(1), UserId(2), UserId(3)])\nfoo.extend(IdList([UserId(1), UserId(2), UserId(3)]))\nbar = IdList([UserId(2)])\n\nbaz = foo + bar\nreveal_type(foo)  # N: Revealed type is \"__main__.IdList\"\nreveal_type(bar)  # N: Revealed type is \"__main__.IdList\"\nreveal_type(baz)  # N: Revealed type is \"builtins.list[__main__.UserId]\"\n\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNewTypeWithGenerics]\nfrom typing import TypeVar, Generic, NewType, Any\n\nT = TypeVar('T')\n\nclass Base(Generic[T]):\n    def __init__(self, item: T) -> None:\n        self.item = item\n\n    def getter(self) -> T:\n        return self.item\n\nDerived1 = NewType('Derived1', Base[str])\nDerived2 = NewType('Derived2', Base)       # Implicit 'Any'\nDerived3 = NewType('Derived3', Base[Any])  # Explicit 'Any'\n\nDerived1(Base(1))  # E: Argument 1 to \"Base\" has incompatible type \"int\"; expected \"str\"\nDerived1(Base('a'))\nDerived2(Base(1))\nDerived2(Base('a'))\nDerived3(Base(1))\nDerived3(Base('a'))\n\nreveal_type(Derived1(Base('a')).getter())  # N: Revealed type is \"builtins.str\"\nreveal_type(Derived3(Base('a')).getter())  # N: Revealed type is \"Any\"\n[out]\n\n[case testNewTypeWithNamedTuple]\nfrom collections import namedtuple\nfrom typing import NewType, NamedTuple\n\nVector1 = namedtuple('Vector1', ['x', 'y'])\nPoint1 = NewType('Point1', Vector1)\np1 = Point1(Vector1(1, 2))\nreveal_type(p1.x)  # N: Revealed type is \"Any\"\nreveal_type(p1.y)  # N: Revealed type is \"Any\"\n\nVector2 = NamedTuple('Vector2', [('x', int), ('y', int)])\nPoint2 = NewType('Point2', Vector2)\np2 = Point2(Vector2(1, 2))\nreveal_type(p2.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(p2.y)  # N: Revealed type is \"builtins.int\"\n\nclass Vector3:\n    def __init__(self, x: int, y: int) -> None:\n        self.x = x\n        self.y = y\nPoint3 = NewType('Point3', Vector3)\np3 = Point3(Vector3(1, 3))\nreveal_type(p3.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(p3.y)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/list.pyi]\n\n[out]\n\n[case testNewTypeWithCasts]\nfrom typing import NewType, cast\nUserId = NewType('UserId', int)\nfoo = UserId(3)\nfoo = cast(UserId, 3)\nfoo = cast(UserId, \"foo\")\nfoo = cast(UserId, UserId(4))\n[out]\n\n[case testNewTypeWithTypeAliases]\nfrom typing import NewType\nFoo = int\nBar = NewType('Bar', Foo)\nBar2 = Bar\n\ndef func1(x: Foo) -> Bar:\n    return Bar(x)\n\ndef func2(x: int) -> Bar:\n    return Bar(x)\n\ndef func3(x: Bar2) -> Bar:\n    return x\n\nx = Bar(42)\ny = Bar2(42)\n\ny = func3(x)\n[out]\n\n[case testNewTypeWithNewType]\nfrom typing import NewType\nA = NewType('A', int)\nB = NewType('B', A)\nC = A\nD = C\nE = NewType('E', D)\n\na = A(1)\nb = B(a)\ne = E(a)\n\ndef funca(a: A) -> None: ...\ndef funcb(b: B) -> None: ...\n\nfunca(a)\nfunca(b)\nfunca(e)\nfuncb(a)  # E: Argument 1 to \"funcb\" has incompatible type \"A\"; expected \"B\"\nfuncb(b)\nfuncb(e)  # E: Argument 1 to \"funcb\" has incompatible type \"E\"; expected \"B\"\n\n[out]\n\n-- Make sure NewType works as expected in a variety of different scopes/across files\n\n[case testNewTypeInLocalScope]\nfrom typing import NewType\nA = NewType('A', int)\na = A(3)\n\ndef func() -> None:\n    A = NewType('A', str)\n    B = NewType('B', str)\n\n    a = A(3)  # E: Argument 1 to \"A@6\" has incompatible type \"int\"; expected \"str\"\n    a = A('xyz')\n    b = B('xyz')\n\nclass MyClass:\n    C = NewType('C', float)\n\n    def foo(self) -> 'MyClass.C':\n        return MyClass.C(3.2)\n\nb = A(3)\nc = MyClass.C(3.5)\n[out]\n\n[case testNewTypeInMultipleFiles]\nimport a\nimport b\nlist1 = [a.UserId(1), a.UserId(2)]\nlist1.append(b.UserId(3))  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"b.UserId\"; expected \"a.UserId\"\n\n[file a.py]\nfrom typing import NewType\nUserId = NewType('UserId', int)\n\n[file b.py]\nfrom typing import NewType\nUserId = NewType('UserId', int)\n\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNewTypeWithIncremental]\nimport m\n\n[file m.py]\nfrom typing import NewType\n\nUserId = NewType('UserId', int)\n\ndef name_by_id(user_id: UserId) -> str:\n    return \"foo\"\n\nname_by_id(UserId(42))\n\nid = UserId(5)\nnum = id + 1\n\n[file m.py.2]\nfrom typing import NewType\n\nUserId = NewType('UserId', int)\n\ndef name_by_id(user_id: UserId) -> str:\n    return \"foo\"\n\nname_by_id(UserId(42))\n\nid = UserId(5)\nnum = id + 1\n\nreveal_type(id)\nreveal_type(num)\n[rechecked m]\n[stale]\n[out1]\n[out2]\ntmp/m.py:13: note: Revealed type is \"m.UserId\"\ntmp/m.py:14: note: Revealed type is \"builtins.int\"\n\n\n-- Check misuses of NewType fail\n\n[case testNewTypeBadInitializationFails]\nfrom typing import NewType\n\na = NewType('b', int)  # E: String argument 1 \"b\" to NewType(...) does not match variable name \"a\"\nb = NewType('b', 3)    # E: \"3\" is a bare literal and cannot be used here, try Literal[3] instead?\nc = NewType(2, int)    # E: Argument 1 to NewType(...) must be a string literal\nd = NewType(b'f', int) # E: Argument 1 to NewType(...) must be a string literal\nfoo = \"d\"\ne = NewType(foo, int)  # E: Argument 1 to NewType(...) must be a string literal\nf = NewType(name='e', tp=int)   # E: NewType(...) expects exactly two positional arguments\ng = NewType('f', tp=int)        # E: NewType(...) expects exactly two positional arguments\n[out]\n\n[case testNewTypeWithAnyFails]\nfrom typing import NewType, Any\nA = NewType('A', Any)  # E: Argument 2 to NewType(...) must be subclassable (got \"Any\")\n[out]\n\n[case testNewTypeWithUnionsFails]\nfrom typing import NewType, Union\nFoo = NewType('Foo', Union[int, float])  # E: Argument 2 to NewType(...) must be subclassable (got \"Union[int, float]\")\n[out]\n\n[case testNewTypeWithTypeTypeFails]\nfrom typing import NewType, Type\nFoo = NewType('Foo', Type[int])  # E: Argument 2 to NewType(...) must be subclassable (got \"Type[int]\")\na = Foo(type(3))\n[builtins fixtures/args.pyi]\n[out]\n\n[case testNewTypeWithTypeVarsFails]\n\nfrom typing import NewType, TypeVar, List\nT = TypeVar('T')\nA = NewType('A', T)\nB = NewType('B', List[T])\n[builtins fixtures/list.pyi]\n[out]\nmain:4: error: Argument 2 to NewType(...) must be subclassable (got T?)\nmain:4: error: Type variable \"__main__.T\" is unbound\nmain:4: note: (Hint: Use \"Generic[T]\" or \"Protocol[T]\" base class to bind \"T\" inside a class)\nmain:4: note: (Hint: Use \"T\" in function signature to bind \"T\" inside a function)\nmain:5: error: Type variable \"__main__.T\" is unbound\nmain:5: note: (Hint: Use \"Generic[T]\" or \"Protocol[T]\" base class to bind \"T\" inside a class)\nmain:5: note: (Hint: Use \"T\" in function signature to bind \"T\" inside a function)\n\n[case testNewTypeRedefiningVariablesFails]\n\nfrom typing import NewType\n\na = 3\ndef f(): a\na = NewType('a', int) # E: Cannot redefine \"a\" as a NewType \\\n                      # E: Name \"a\" already defined on line 4\n\nb = NewType('b', int)\ndef g(): b\nb = NewType('b', float)  # E: Cannot redefine \"b\" as a NewType \\\n                         # E: Name \"b\" already defined on line 8\n\nc = NewType('c', str)  # type: str  # E: Cannot declare the type of a NewType declaration\n\n[case testNewTypeAddingExplicitTypesFails]\nfrom typing import NewType\nUserId = NewType('UserId', int)\n\na = 3  # type: UserId  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"UserId\")\n[out]\n\n[case testNewTypeTestSubclassingFails]\nfrom typing import NewType\nclass A: pass\nB = NewType('B', A)\nclass C(B): pass  # E: Cannot subclass \"NewType\"\n[out]\n\n[case testCannotUseNewTypeWithProtocols]\nfrom typing import Protocol, NewType\n\nclass P(Protocol):\n    attr: int = 0\nclass D:\n    attr: int\n\nC = NewType('C', P)  # E: NewType cannot be used with protocol classes\n\nx: C = C(D())  # We still accept this, treating 'C' as non-protocol subclass.\nreveal_type(x.attr)  # N: Revealed type is \"builtins.int\"\nx.bad_attr  # E: \"C\" has no attribute \"bad_attr\"\nC(1)  # E: Argument 1 to \"C\" has incompatible type \"int\"; expected \"P\"\n[out]\n\n[case testNewTypeAny]\nfrom typing import NewType\nAny = NewType('Any', int)\nAny(5)\n\n[case testNewTypeWithIsInstanceAndIsSubclass]\nfrom typing import NewType\nT = NewType('T', int)\nd: object\nif isinstance(d, T):   # E: Cannot use isinstance() with NewType type\n    reveal_type(d)     # N: Revealed type is \"__main__.T\"\nissubclass(object, T)  # E: Cannot use issubclass() with NewType type\n[builtins fixtures/isinstancelist.pyi]\n\n[case testInvalidNewTypeCrash]\n\nfrom typing import List, NewType, Union\nN = NewType('N', XXX)  # E: Argument 2 to NewType(...) must be subclassable (got \"Any\") \\\n                       # E: Name \"XXX\" is not defined\nx: List[Union[N, int]]\n[builtins fixtures/list.pyi]\n\n[case testTypingExtensionsNewType]\nfrom typing_extensions import NewType\nN = NewType(\"N\", int)\nx: N\n[builtins fixtures/tuple.pyi]\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:  Optional[int]\nf(x)  # E: Argument 1 to \"f\" has incompatible type \"Optional[int]\"; expected \"int\"\n\n[case testIsinstanceCases]\nfrom typing import Optional\nx:  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: Optional[int]\nif x:\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"Union[Literal[0], None]\"\n[builtins fixtures/bool.pyi]\n\n[case testIfNotCases]\nfrom typing import Optional\nx:  Optional[int]\nif not x:\n  reveal_type(x)  # N: Revealed type is \"Union[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:  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:  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 \"Union[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: 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 \"Union[builtins.str, builtins.int]\"\nz1 = 'a' or x\nreveal_type(z1)  # N: Revealed type is \"Union[builtins.str, None]\"\nz2 = int() or x\nreveal_type(z2)  # N: Revealed type is \"Union[builtins.int, builtins.str, None]\"\n\n[case testAndCases]\nfrom typing import Optional\nx: Optional[str]\ny1 = x and 'b'\nreveal_type(y1)  # N: Revealed type is \"Union[Literal[''], None, builtins.str]\"\ny2 = x and 1  # x could be '', so...\nreveal_type(y2)  # N: Revealed type is \"Union[Literal[''], None, builtins.int]\"\nz1 = 'b' and x\nreveal_type(z1)  # N: Revealed type is \"Union[builtins.str, None]\"\nz2 = int() and x\nreveal_type(z2)  # N: Revealed type is \"Union[Literal[0], builtins.str, None]\"\n\n[case testLambdaReturningNone]\nf = lambda: None\nx = f()  # E: Function does not return a value (it only ever returns None)\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 \"Optional[int]\"\nf(None)\n[out]\n\n[case testNoInferOptionalFromDefaultNone]\n# flags: --no-implicit-optional\ndef f(x: int = None) -> None:  # E: Incompatible default for argument \"x\" (default has type \"None\", argument 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 \"Optional[int]\"\nf(None)\n[out]\n\n[case testNoInferOptionalFromDefaultNoneComment]\n# flags: --no-implicit-optional\ndef f(x=None):  # E: Incompatible default for argument \"x\" (default has type \"None\", argument 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 \"Union[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 \"Union[Any, None]\"\n[builtins fixtures/bool.pyi]\n\n[case testInferOptionalTypeFromOptional]\nfrom typing import Optional\ny: Optional[int]\nx = None\nx = y\nreveal_type(x)  # N: Revealed type is \"Union[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 = None  # type: int\n    def __init__(self) -> None:\n        self.x = 0\n\n[case testNoneClassVariableInInit]\nfrom typing import Optional\nclass C:\n    x = None  # type: 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 = 1, \"\"  # 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[builtins fixtures/tuple.pyi]\n[out]\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 \"Union[builtins.int, None]\"\nmain:5: note: Revealed type is \"Union[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 \"Union[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 \"Optional[int]\", 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 \"Optional[T]\", 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 \"Union[None, Literal[0]?]\"\n[builtins fixtures/bool.pyi]\n\n[case testListWithNone]\nreveal_type([0, None, 0])    # N: Revealed type is \"builtins.list[Union[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]\nx = [None] if \"\" else [1]  # E: List item 0 has incompatible type \"int\"; expected \"None\"\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\nx: Optional[str]\nif x == '<string>':\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, None]\"\nif x is '<string>':\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsNotOptionalWithUnion]\nfrom typing import Union\nx: Union[str, int, None]\nif x == '<string>':\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\nif x is '<string>':\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsNotOptionalWithOverlap]\nfrom typing import Union\nx: Union[str, int, None]\nif x == object():\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\nif x is object():\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsStillOptionalWithNoOverlap]\nfrom typing import Optional\nx: Optional[str]\nif x == 0:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, None]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, None]\"\nif x is 0:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, None]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsStillOptionalWithBothOptional]\nfrom typing import Union\nx: Union[str, int, None]\ny: Union[str, None]\nif x == y:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\nif x is y:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.int, None]\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsNotOptionalWithMultipleArgs]\nfrom typing import Optional\nx: Optional[int]\ny: Optional[int]\nif x == y == 1:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, None]\"\n    reveal_type(y)  # N: Revealed type is \"Union[builtins.int, None]\"\n\nclass A: pass\na: Optional[A]\nb: Optional[A]\nif a == b == object():\n    reveal_type(a)  # N: Revealed type is \"__main__.A\"\n    reveal_type(b)  # N: Revealed type is \"__main__.A\"\nelse:\n    reveal_type(a)  # N: Revealed type is \"Union[__main__.A, None]\"\n    reveal_type(b)  # N: Revealed type is \"Union[__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 \"Optional[Node[int]]\" 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]\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 \"Union[None, __main__.C]\"\nreveal_type(u(None, C()))  # N: Revealed type is \"Union[__main__.C, None]\"\n\nreveal_type(u(a, None))  # N: Revealed type is \"Union[None, Any]\"\nreveal_type(u(None, a))  # N: Revealed type is \"Union[Any, None]\"\n\nreveal_type(u(1, None))  # N: Revealed type is \"Union[None, builtins.int]\"\nreveal_type(u(None, 1))  # N: Revealed type is \"Union[builtins.int, None]\"\n\n[case testOptionalAndAnyBaseClass]\nfrom typing import Any, Optional\nA: Any\nclass C(A):\n    pass\nx: Optional[C]\nx.foo()  # E: Item \"None\" of \"Optional[C]\" 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 \"Union[__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 \"Union[__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 \"Union[builtins.int, builtins.str, None]\"\ny: Optional[Union[int, None]]\nreveal_type(y) # N: Revealed type is \"Union[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 \"Union[builtins.str, None]\"\nx: Optional[int]\nreveal_type(f(x)) # N: Revealed type is \"Union[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 \"Union[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 \"Union[builtins.int, Any]\"\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, Any]\"\n    return x\n\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        # Since we've assigned to x, the special case None behavior shouldn't happen\n        x = f()\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, None]\"\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, None]\"\n    return x  # E: Incompatible return value type (got \"Optional[int]\", expected \"int\")\n\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    if 1:\n        x = f()\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, Any]\"\n        return x\n\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[Optional[str]]\"\nmain:4: note: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/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 \"Union[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 \"Optional[int]\", 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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Union[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 \"Optional[str]\", 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 \"Optional[str]\", expected \"str\")\n    return x  # E: Incompatible return value type (got \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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-overloading.test",
    "content": "-- Test cases for function overloading\n[case testOverloadNotImportedNoCrash]\n\n@overload\ndef f(a): pass\n@overload\ndef f(a): pass\ndef f(a): pass\nf(0)\n\n@overload  # E: Name \"overload\" is not defined\ndef g(a:int): pass\ndef g(a): pass  # E: Name \"g\" already defined on line 9\ng(0)\n\n@something  # E: Name \"something\" is not defined\ndef r(a:int): pass\ndef r(a): pass  # E: Name \"r\" already defined on line 14\nr(0)\n[out]\nmain:2: error: Name \"overload\" is not defined\nmain:4: error: Name \"f\" already defined on line 2\nmain:4: error: Name \"overload\" is not defined\nmain:6: error: Name \"f\" already defined on line 2\n\n[case testTypeCheckOverloadWithImplementation]\nfrom typing import overload, Any\nclass A: pass\nclass B: pass\n\n@overload\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\ndef f(x: Any) -> Any:\n    pass\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testTypingExtensionsOverload]\nfrom typing import Any\nfrom typing_extensions import overload\nclass A: pass\nclass B: pass\n\n@overload\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\ndef f(x: Any) -> Any:\n    pass\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testOverloadNeedsImplementation]\nfrom typing import overload, Any\n\nclass A: pass\nclass B: pass\n\n@overload  # E: An overloaded function outside a stub file must have an implementation\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testSingleOverloadNoImplementation]\nfrom typing import overload, Any\n@overload  # E: Single overload definition, multiple required\ndef f(x: 'A') -> 'B': ...\n\nclass A: pass\nclass B: pass\n[builtins fixtures/isinstance.pyi]\n\n[case testOverloadByAnyOtherName]\nfrom typing import overload as rose\nfrom typing import Any\nclass A: pass\nclass B: pass\n\n@rose\ndef f(x: 'A') -> 'B': ...\n@rose\ndef f(x: 'B') -> 'A': ...\n\ndef f(x: Any) -> Any:\n    pass\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadWithDecoratedImplementation]\nfrom typing import overload, Any\n\nclass A: pass\nclass B: pass\n\ndef deco(fun): ...\n\n@overload\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\n@deco\ndef f(x: Any) -> Any:\n    pass\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testOverloadDecoratedImplementationNotLast]\nfrom typing import overload, Any\n\ndef deco(fun): ...\n\n@overload\ndef f(x: 'A') -> 'B': ...\n\n@deco  # E: The implementation for an overloaded function must come last\ndef f(x: Any) -> Any:\n    pass\n\n@overload\ndef f(x: 'B') -> 'A': ...\n\nclass A: pass\nclass B: pass\n[builtins fixtures/isinstance.pyi]\n\n[case testOverloadImplementationNotLast]\nfrom typing import overload, Any\n\n@overload\ndef f(x: 'A') -> 'B': ...\n\ndef f(x: Any) -> Any:  # E: The implementation for an overloaded function must come last\n    pass\n\n@overload\ndef f(x: 'B') -> 'A': ...\n\nclass A: pass\nclass B: pass\n[builtins fixtures/isinstance.pyi]\n\n[case testDecoratedRedefinitionIsNotOverload]\nfrom typing import overload, Any\n\ndef deco(fun): ...\n\n@deco\ndef f(x: 'A') -> 'B': ...\n@deco  # E: Name \"f\" already defined on line 5\ndef f(x: 'B') -> 'A': ...\n@deco  # E: Name \"f\" already defined on line 5\ndef f(x: Any) -> Any: ...\n\nclass A: pass\nclass B: pass\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadWithImplementationError]\nfrom typing import overload, Any\n\nclass A: pass\nclass B: pass\n\n@overload\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\ndef f(x: Any) -> Any:\n    foo = 1\n    if int():\n        foo = \"bar\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    return foo\n\n@overload\ndef g(x: 'A') -> 'B': ...\n@overload\ndef g(x: 'B') -> 'A': ...\n\ndef g(x):\n    foo = 1\n    if int():\n        foo = \"bar\"\n\nreveal_type(f(A()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f(B()))  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadWithUntypedImplAndMultipleVariants]\nfrom typing import overload\n\n@overload\ndef f(x: int) -> str: ...\n@overload\ndef f(x: str) -> int: ...  # E: Overloaded function signatures 2 and 3 overlap with incompatible return types\n@overload\ndef f(x: object) -> str: ...\ndef f(x): ...\n\n[case testTypeCheckOverloadWithImplTooSpecificArg]\nfrom typing import overload, Any\n\nclass A: pass\nclass B: pass\n\na = A()\n\n@overload\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\ndef f(x: 'A') -> Any: # E: Overloaded function implementation does not accept all possible arguments of signature 2\n    pass\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadWithImplTooSpecificRetType]\nfrom typing import overload, Any\n\nclass A: pass\nclass B: pass\n\na = A()\n\n@overload\ndef f(x: 'A') -> 'B': ...\n@overload\ndef f(x: 'B') -> 'A': ...\n\ndef f(x: Any) -> 'B': # E: Overloaded function implementation cannot produce return type of signature 2\n    return B()\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.B\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.A\"\n\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadWithImplTypeVar]\nfrom typing import overload, Any, TypeVar\n\nT = TypeVar('T')\n\nclass A: pass\nclass B: pass\n\na = A()\n\n@overload\ndef f(x: 'A') -> 'A': ...\n@overload\ndef f(x: 'B') -> 'B': ...\n\ndef f(x: T) -> T:\n    ...\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.A\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.B\"\n\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadWithImplTypeVarProblems]\nfrom typing import overload, Any, TypeVar, Union\n\nT = TypeVar('T', bound='A')\n\nclass A: pass\nclass B: pass\n\na = A()\n\n@overload\ndef f(x: 'A') -> 'A': ...\n@overload\ndef f(x: 'B') -> 'B': ...\n\ndef f(x: Union[T, B]) -> T:  # E: Overloaded function implementation cannot satisfy signature 2 due to inconsistencies in how they use type variables\n    ...\n\nreveal_type(f(A())) # N: Revealed type is \"__main__.A\"\nreveal_type(f(B())) # N: Revealed type is \"__main__.B\"\n\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeCheckOverloadImplementationTypeVarWithValueRestriction]\nfrom typing import overload, TypeVar, Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nT = TypeVar('T', A, B)\n\n@overload\ndef foo(x: T) -> T: ...\n@overload\ndef foo(x: C) -> int: ...\ndef foo(x: Union[A, B, C]) -> Union[A, B, int]:\n    if isinstance(x, C):\n        return 3\n    else:\n        return x\n\n@overload\ndef bar(x: T) -> T: ...\n@overload\ndef bar(x: C) -> int: ...\ndef bar(x: Union[T, C]) -> Union[T, int]:\n    if isinstance(x, C):\n        return 3\n    else:\n        return x\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testTypeCheckOverloadImplementationTypeVarDifferingUsage1]\nfrom typing import overload, Union, List, TypeVar, Generic\n\nT = TypeVar('T')\n\n@overload\ndef foo(t: List[T]) -> T: ...\n@overload\ndef foo(t: T) -> T: ...\ndef foo(t: Union[List[T], T]) -> T:\n    if isinstance(t, list):\n        return t[0]\n    else:\n        return t\n\nclass Wrapper(Generic[T]):\n    @overload\n    def foo(self, t: List[T]) -> T: ...\n    @overload\n    def foo(self, t: T) -> T: ...\n    def foo(self, t: Union[List[T], T]) -> T:\n        if isinstance(t, list):\n            return t[0]\n        else:\n            return t\n[builtins fixtures/isinstancelist.pyi]\n\n[case testTypeCheckOverloadImplementationTypeVarDifferingUsage2]\nfrom typing import overload, Union, List, TypeVar, Generic\n\nT = TypeVar('T')\n\n# Note: this is unsafe when T = object\n@overload\ndef foo(t: List[T], s: T) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef foo(t: T, s: T) -> str: ...\ndef foo(t, s): pass\n\nclass Wrapper(Generic[T]):\n    @overload\n    def foo(self, t: List[T], s: T) -> int: ...  # 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\n    def foo(self, t: T, s: T) -> str: ...\n    def foo(self, t, s): pass\n\nclass Dummy(Generic[T]): pass\n\n# Same root issue: why does the additional constraint bound T <: T\n# cause the constraint solver to not infer T = object like it did in the\n# first example?\n@overload\ndef bar(d: Dummy[T], t: List[T], s: T) -> int: ...  # 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 bar(d: Dummy[T], t: T, s: T) -> str: ...\ndef bar(d: Dummy[T], t, s): pass\n[builtins fixtures/isinstancelist.pyi]\n\n[case testTypeCheckOverloadedFunctionBody]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: 'A'):\n    if int():\n        x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        x = A()\n@overload\ndef f(x: 'B'):\n    if int():\n        x = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        x = B()\nclass A: pass\nclass B: pass\n[out]\n\n[case testTypeCheckOverloadedMethodBody]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def f(self, x: 'A'):\n        if int():\n            x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n            x = A()\n    @overload\n    def f(self, x: 'B'):\n        if int():\n            x = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n            x = B()\nclass B: pass\n[out]\n\n[case testCallToOverloadedFunction]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nf(C()) # E: No overload variant of \"f\" matches argument type \"C\" \\\n       # N: Possible overload variants: \\\n       # N:     def f(x: A) -> None \\\n       # N:     def f(x: B) -> None\nf(A())\nf(B())\n\n@overload\ndef f(x: 'A') -> None: pass\n@overload\ndef f(x: 'B') -> None: pass\n\nclass A: pass\nclass B: pass\nclass C: pass\n\n[case testOverloadedFunctionReturnValue]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na: A\nb: B\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    a = f(a)\nif int():\n    b = f(b)\n\n@overload\ndef f(x: 'A') -> 'A': pass\n@overload\ndef f(x: 'B') -> 'B': pass\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testCallToOverloadedMethod]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nA().f(C()) # E: No overload variant of \"f\" of \"A\" matches argument type \"C\" \\\n           # N: Possible overload variants: \\\n           # N:     def f(self, x: A) -> None \\\n           # N:     def f(self, x: B) -> None\nA().f(A())\nA().f(B())\n\nclass A:\n  @overload\n  def f(self, x: 'A') -> None: pass\n  @overload\n  def f(self, x: 'B') -> None: pass\n\nclass B: pass\nclass C: pass\n\n[case testOverloadedMethodReturnValue]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na: A\nb: B\nif int():\n    b = a.f(a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = a.f(b) # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    a = a.f(a)\nif int():\n    b = a.f(b)\n\nclass A:\n  @overload\n  def f(self, x: 'A') -> 'A': pass\n  @overload\n  def f(self, x: 'B') -> 'B': pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadsWithDifferentArgumentCounts]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na: A\nb: B\nif int():\n    a = f(a)\nif int():\n    b = f(a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nf(b)     # E: No overload variant of \"f\" matches argument type \"B\" \\\n         # N: Possible overload variants: \\\n         # N:     def f(x: A) -> A \\\n         # N:     def f(x: B, y: A) -> B\nif int():\n    b = f(b, a)\nif int():\n    a = f(b, a) # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nf(a, a)     # E: No overload variant of \"f\" matches argument types \"A\", \"A\" \\\n            # N: Possible overload variants: \\\n            # N:     def f(x: A) -> A \\\n            # N:     def f(x: B, y: A) -> B\nf(b, b)     # E: No overload variant of \"f\" matches argument types \"B\", \"B\" \\\n            # N: Possible overload variants: \\\n            # N:     def f(x: A) -> A \\\n            # N:     def f(x: B, y: A) -> B\n\n@overload\ndef f(x: 'A') -> 'A': pass\n@overload\ndef f(x: 'B', y: 'A') -> 'B': pass\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testGenericOverloadVariant]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar, Generic\nt = TypeVar('t')\nab: A[B]\nac: A[C]\nb: B\nc: C\nif int():\n    b = f(ab)\n    c = f(ac)\n    b = f(ac) # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n    b = f(b)\n    c = f(b)  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\n@overload\ndef f(x: 'A[t]') -> t: pass\n@overload\ndef f(x: 'B') -> 'B': pass\nclass A(Generic[t]): pass\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadedInit]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na: A\nb: B\na = A(a)\na = A(b)\na = A(object()) # E: No overload variant of \"A\" matches argument type \"object\" \\\n                # N: Possible overload variants: \\\n                # N:     def __init__(self, a: A) -> A \\\n                # N:     def __init__(self, b: B) -> A\n\nclass A:\n  @overload\n  def __init__(self, a: 'A') -> None: pass\n  @overload\n  def __init__(self, b: 'B') -> None: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testIntersectionTypeCompatibility]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Callable\no: object\na: A\n\nif int():\n    a = f # E: Incompatible types in assignment (expression has type overloaded function, variable has type \"A\")\nif int():\n    o = f\n\n@overload\ndef f(a: 'A') -> None: pass\n@overload\ndef f(a: Callable[[], None]) -> None: pass\nclass A: pass\n\n[case testCompatibilityOfIntersectionTypeObjectWithStdType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nt: type\na: A\n\nif int():\n    a = A # E: Incompatible types in assignment (expression has type \"Type[A]\", variable has type \"A\")\n    t = A\n\nclass A:\n    @overload\n    def __init__(self, a: 'A') -> None: pass\n    @overload\n    def __init__(self, a: 'B') -> None: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadedGetitem]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na: int\nb: str\nif int():\n    a = A()[a]\nif int():\n    b = A()[a] # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    b = A()[b]\nif int():\n    a = A()[b] # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\nclass A:\n    @overload\n    def __getitem__(self, a: int) -> int: pass\n    @overload\n    def __getitem__(self, b: str) -> str: pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadedGetitemWithGenerics]\nfrom foo import *\n[file foo.pyi]\nfrom typing import TypeVar, Generic, overload\nt = TypeVar('t')\na: A\nb: B\nc: C[A]\nif int():\n    a = c[a]\n    b = c[a] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = c[b]\n    b = c[b] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nclass C(Generic[t]):\n    @overload\n    def __getitem__(self, a: 'A') -> t: pass\n    @overload\n    def __getitem__(self, b: 'B') -> t: pass\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testImplementingOverloadedMethod]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nfrom abc import abstractmethod, ABCMeta\n\nclass I(metaclass=ABCMeta):\n    @overload\n    @abstractmethod\n    def f(self) -> None: pass\n    @overload\n    @abstractmethod\n    def f(self, a: 'A') -> None: pass\nclass A(I):\n    @overload\n    def f(self) -> None: pass\n    @overload\n    def f(self, a: 'A') -> None: pass\n\n[case testOverloadWithFunctionType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Callable\nclass A: pass\n@overload\ndef f(x: A) -> None: pass\n@overload\ndef f(x: Callable[[], None]) -> None: pass\n\nf(A())\n[builtins fixtures/function.pyi]\n\n[case testVarArgsOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\n@overload\ndef f(x: 'A', *more: Any) -> 'A': pass\n@overload\ndef f(x: 'B', *more: Any) -> 'A': pass\nf(A())\nf(A(), A, A)\nf(B())\nf(B(), B)\nf(B(), B, B)\nf(object()) # E: No overload variant of \"f\" matches argument type \"object\" \\\n            # N: Possible overload variants: \\\n            # N:     def f(x: A, *more: Any) -> A \\\n            # N:     def f(x: B, *more: Any) -> A\nclass A: pass\nclass B: pass\n[builtins fixtures/list.pyi]\n\n[case testVarArgsOverload2]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: 'A', *more: 'B') -> 'A': pass\n@overload\ndef f(x: 'B', *more: 'A') -> 'A': pass\nf(A(), B())\nf(A(), B(), B())\nf(A(), A(), B()) # E: No overload variant of \"f\" matches argument types \"A\", \"A\", \"B\" \\\n                 # N: Possible overload variants: \\\n                 # N:     def f(x: A, *more: B) -> A \\\n                 # N:     def f(x: B, *more: A) -> A\nf(A(), B(), A()) # E: No overload variant of \"f\" matches argument types \"A\", \"B\", \"A\" \\\n                 # N: Possible overload variants: \\\n                 # N:     def f(x: A, *more: B) -> A \\\n                 # N:     def f(x: B, *more: A) -> A\nclass A: pass\nclass B: pass\n[builtins fixtures/list.pyi]\n\n[case testOverloadWithTypeObject]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(a: 'A', t: type) -> None: pass\n@overload\ndef f(a: 'B', t: type) -> None: pass\nf(A(), B)\nf(B(), A)\nclass A: pass\nclass B: pass\n[builtins fixtures/function.pyi]\n\n[case testOverloadedInitAndTypeObjectInOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(t: type) -> 'A': pass\n@overload\ndef f(t: 'A') -> 'B': pass\na: A\nb: B\nif int():\n    a = f(A)\nif int():\n    b = f(a)\nif int():\n    b = f(A) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = f(a) # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nclass A:\n   @overload\n   def __init__(self) -> None: pass\n   @overload\n   def __init__(self, a: 'A') -> None: pass\nclass B:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverlappingErasedSignatures]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, List\n@overload\ndef f(a: List[int]) -> int: pass\n@overload\ndef f(a: List[str]) -> int: pass\nlist_int = [] # type: List[int]\nlist_str = [] # type: List[str]\nlist_object = [] # type: List[object]\nn = f(list_int)\nm = f(list_str)\ndef p(): n, m # Prevent redefinition\nn = 1\nm = 1\nn = 'x' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nm = 'x' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nf(list_object) # E: Argument 1 to \"f\" has incompatible type \"List[object]\"; expected \"List[int]\"\n[builtins fixtures/list.pyi]\n\n[case testOverlappingOverloadSignatures]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef f(x: B) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: A) -> str: pass\n\n[case testContravariantOverlappingOverloadSignatures]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: B) -> B: pass   # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n[case testPartiallyCovariantOverlappingOverloadSignatures]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef f(x: B) -> A: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: A) -> B: pass\n\n[case testPartiallyContravariantOverloadSignatures]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef g(x: A) -> int: pass\n@overload\ndef g(x: B) -> str: pass  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n[case testCovariantOverlappingOverloadSignatures]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef g(x: B) -> B: pass\n@overload\ndef g(x: A) -> A: pass\n\n[case testCovariantOverlappingOverloadSignaturesWithSomeSameArgTypes]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef g(x: int, y: B) -> B: pass\n@overload\ndef g(x: int, y: A) -> A: pass\n\n[case testCovariantOverlappingOverloadSignaturesWithAnyType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Any, overload\n@overload\ndef g(x: int) -> int: pass\n@overload\ndef g(x: Any) -> Any: pass\n\n[case testContravariantOverlappingOverloadSignaturesWithAnyType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Any, overload\n@overload\ndef g(x: Any) -> Any: pass\n@overload\ndef g(x: int) -> int: pass  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n[case testOverloadedLtAndGtMethods]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    def __lt__(self, x: A) -> int: pass\n    def __gt__(self, x: A) -> int: pass\nclass B:\n    @overload\n    def __lt__(self, x: B) -> int: pass\n    @overload\n    def __lt__(self, x: A) -> int: pass\n    @overload\n    def __gt__(self, x: B) -> int: pass\n    @overload\n    def __gt__(self, x: A) -> int: pass\nA() < A()\nA() < B()\nB() < A()\nB() < B()\nA() < object() # E: Unsupported operand types for < (\"A\" and \"object\")\nB() < object() # E: No overload variant of \"__lt__\" of \"B\" matches argument type \"object\" \\\n               # N: Possible overload variants: \\\n               # N:     def __lt__(self, B, /) -> int \\\n               # N:     def __lt__(self, A, /) -> int\n\n[case testOverloadedForwardMethodAndCallingReverseMethod]\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: int) -> int: pass\nclass B:\n    def __radd__(self, x: A) -> int: pass\nA() + A()\nA() + 1\nA() + B()\nA() + '' # E: No overload variant of \"__add__\" of \"A\" matches argument type \"str\" \\\n         # N: Possible overload variants: \\\n         # N:     def __add__(self, A, /) -> int \\\n         # N:     def __add__(self, int, /) -> int\n\n[case testOverrideOverloadSwapped]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\nclass Parent:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\nclass Child(Parent):\n    @overload                           # E: Signature of \"f\" incompatible with supertype \"Parent\" \\\n                                        # N: Overload variants must be defined in the same order as they are in \"Parent\"\n    def f(self, x: str) -> str: ...\n    @overload\n    def f(self, x: int) -> int: ...\n\n[case testOverrideOverloadSwappedWithExtraVariants]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\nclass bool: pass\n\nclass Parent:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\nclass Child1(Parent):\n    @overload                           # E: Signature of \"f\" incompatible with supertype \"Parent\" \\\n                                        # N: Overload variants must be defined in the same order as they are in \"Parent\"\n    def f(self, x: bool) -> bool: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    @overload\n    def f(self, x: int) -> int: ...\nclass Child2(Parent):\n    @overload                           # E: Signature of \"f\" incompatible with supertype \"Parent\" \\\n                                        # N: Overload variants must be defined in the same order as they are in \"Parent\"\n    def f(self, x: str) -> str: ...\n    @overload\n    def f(self, x: bool) -> bool: ...\n    @overload\n    def f(self, x: int) -> int: ...\nclass Child3(Parent):\n    @overload                           # E: Signature of \"f\" incompatible with supertype \"Parent\" \\\n                                        # N: Overload variants must be defined in the same order as they are in \"Parent\"\n    def f(self, x: str) -> str: ...\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: bool) -> bool: ...\n\n[case testOverrideOverloadSwappedWithAdjustedVariants]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\nclass Parent:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: B) -> B: ...\nclass Child1(Parent):\n    @overload                           # Fail\n    def f(self, x: A) -> B: ...\n    @overload\n    def f(self, x: int) -> int: ...\nclass Child2(Parent):\n    @overload                           # Fail\n    def f(self, x: B) -> C: ...\n    @overload\n    def f(self, x: int) -> int: ...\nclass Child3(Parent):\n    @overload                           # Fail\n    def f(self, x: B) -> A: ...\n    @overload\n    def f(self, x: int) -> int: ...\n[out]\ntmp/foo.pyi:13: error: Signature of \"f\" incompatible with supertype \"Parent\"\ntmp/foo.pyi:13: note: Overload variants must be defined in the same order as they are in \"Parent\"\ntmp/foo.pyi:18: error: Signature of \"f\" incompatible with supertype \"Parent\"\ntmp/foo.pyi:18: note: Overload variants must be defined in the same order as they are in \"Parent\"\ntmp/foo.pyi:23: error: Signature of \"f\" incompatible with supertype \"Parent\"\ntmp/foo.pyi:23: note:      Superclass:\ntmp/foo.pyi:23: note:          @overload\ntmp/foo.pyi:23: note:          def f(self, x: int) -> int\ntmp/foo.pyi:23: note:          @overload\ntmp/foo.pyi:23: note:          def f(self, x: B) -> B\ntmp/foo.pyi:23: note:      Subclass:\ntmp/foo.pyi:23: note:          @overload\ntmp/foo.pyi:23: note:          def f(self, x: B) -> A\ntmp/foo.pyi:23: note:          @overload\ntmp/foo.pyi:23: note:          def f(self, x: int) -> int\n\n[case testOverrideOverloadedMethodWithMoreGeneralArgumentTypes]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\nclass IntSub(int): pass\n\nclass StrSub(str): pass\nclass A:\n    @overload\n    def f(self, x: IntSub) -> int: return 0\n    @overload\n    def f(self, x: StrSub) -> str: return ''\nclass B(A):\n    @overload\n    def f(self, x: int) -> int: return 0\n    @overload\n    def f(self, x: str) -> str: return ''\n[out]\n\n[case testOverrideOverloadedMethodWithMoreSpecificArgumentTypes]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\nclass IntSub(int): pass\n\nclass StrSub(str): pass\nclass A:\n    @overload\n    def f(self, x: int) -> int: return 0\n    @overload\n    def f(self, x: str) -> str: return ''\nclass B(A):\n    @overload  # Fail\n    def f(self, x: IntSub) -> int: return 0\n    @overload\n    def f(self, x: str) -> str: return ''\nclass C(A):\n    @overload  # Fail\n    def f(self, x: int) -> int: return 0\n    @overload\n    def f(self, x: StrSub) -> str: return ''\nclass D(A):\n    @overload\n    def f(self, x: int) -> int: return 0\n    @overload\n    def f(self, x: str) -> str: return ''\n[out]\ntmp/foo.pyi:12: error: Signature of \"f\" incompatible with supertype \"A\"\ntmp/foo.pyi:12: note:      Superclass:\ntmp/foo.pyi:12: note:          @overload\ntmp/foo.pyi:12: note:          def f(self, x: int) -> int\ntmp/foo.pyi:12: note:          @overload\ntmp/foo.pyi:12: note:          def f(self, x: str) -> str\ntmp/foo.pyi:12: note:      Subclass:\ntmp/foo.pyi:12: note:          @overload\ntmp/foo.pyi:12: note:          def f(self, x: IntSub) -> int\ntmp/foo.pyi:12: note:          @overload\ntmp/foo.pyi:12: note:          def f(self, x: str) -> str\ntmp/foo.pyi:17: error: Signature of \"f\" incompatible with supertype \"A\"\ntmp/foo.pyi:17: note:      Superclass:\ntmp/foo.pyi:17: note:          @overload\ntmp/foo.pyi:17: note:          def f(self, x: int) -> int\ntmp/foo.pyi:17: note:          @overload\ntmp/foo.pyi:17: note:          def f(self, x: str) -> str\ntmp/foo.pyi:17: note:      Subclass:\ntmp/foo.pyi:17: note:          @overload\ntmp/foo.pyi:17: note:          def f(self, x: int) -> int\ntmp/foo.pyi:17: note:          @overload\ntmp/foo.pyi:17: note:          def f(self, x: StrSub) -> str\n\n[case testOverloadingAndDucktypeCompatibility]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, _promote\n\nclass A: pass\n\n@_promote(A)\nclass B: pass\n\n@overload\ndef f(n: B) -> B:\n    return n\n@overload\ndef f(n: A) -> A:\n    return n\n\nf(B()) + 'x'  # E: Unsupported left operand type for + (\"B\")\nf(A()) + 'x'  # E: Unsupported left operand type for + (\"A\")\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadingAndIntFloatSubtyping]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: float) -> None: pass\n@overload\ndef f(x: str) -> None: pass\nf(1.1)\nf('')\nf(1)\nf(()) # E: No overload variant of \"f\" matches argument type \"Tuple[()]\" \\\n      # N: Possible overload variants: \\\n      # N:     def f(x: float) -> None \\\n      # N:     def f(x: str) -> None\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testOverloadingVariableInputs]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: int, y: int) -> None: pass\n@overload\ndef f(x: int) -> None: pass\nf(1)\nf(1, 2)\nz = (1, 2)\nf(*z)\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testTypeInferenceSpecialCaseWithOverloading]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\nclass A:\n    def __add__(self, x: A) -> A: pass\nclass B:\n    def __radd__(self, x: A) -> B: pass\n\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: B) -> B: pass\n\nf(A() + B())() # E: \"B\" not callable\n\n[case testKeywordArgOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: int, y: str) -> int: pass\n@overload\ndef f(x: str, y: int) -> str: pass\nf(x=1, y='')() # E: \"int\" not callable\nf(y=1, x='')() # E: \"str\" not callable\n\n[case testIgnoreOverloadVariantBasedOnKeywordArg]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: int) -> int: pass\n@overload\ndef f(y: int) -> str: pass\nf(x=1)() # E: \"int\" not callable\nf(y=1)() # E: \"str\" not callable\n\n[case testOverloadWithTupleVarArg]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: int, y: str) -> int: pass\n@overload\ndef f(*x: str) -> str: pass\nf(*(1,))() # E: No overload variant of \"f\" matches argument type \"Tuple[int]\" \\\n           # N: Possible overload variants: \\\n           # N:     def f(x: int, y: str) -> int \\\n           # N:     def f(*x: str) -> str\nf(*('',))() # E: \"str\" not callable\nf(*(1, ''))() # E: \"int\" not callable\nf(*(1, '', 1))() # E: No overload variant of \"f\" matches argument type \"Tuple[int, str, int]\" \\\n                 # N: Possible overload variants: \\\n                 # N:     def f(x: int, y: str) -> int \\\n                 # N:     def f(*x: str) -> str\n[builtins fixtures/tuple.pyi]\n\n[case testPreferExactSignatureMatchInOverload]\n# flags: --no-strict-optional\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, List\n@overload\ndef f(x: int, y: List[int] = None) -> int: pass\n@overload\ndef f(x: int, y: List[str] = None) -> int: pass\nf(y=[1], x=0)() # E: \"int\" not callable\nf(y=[''], x=0)() # E: \"int\" not callable\na = f(y=[['']], x=0) # E: List item 0 has incompatible type \"List[str]\"; expected \"int\"\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadWithDerivedFromAny]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Any, overload\nBase = None  # type: Any\n\nclass C:\n    @overload\n    def __init__(self, a: str) -> None: pass\n    @overload\n    def __init__(self, a: int) -> None: pass\n\nclass Derived(Base):\n    def to_dict(self) -> C:\n        return C(self)  # fails without the fix for #1363\nC(Derived())  # fails without the hack\nC(Base())  # Always ok\n\n[case testOverloadWithBoundedTypeVar]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar\nT = TypeVar('T', bound=str)\n@overload\ndef f(x: T) -> T: pass\n@overload\ndef f(x: int) -> bool: pass\nclass mystr(str): pass\n\nf('x')() # E: \"str\" not callable\nf(1)() # E: \"bool\" not callable\nf(1.1) # E: No overload variant of \"f\" matches argument type \"float\" \\\n       # N: Possible overload variants: \\\n       # N:     def [T: str] f(x: T) -> T \\\n       # N:     def f(x: int) -> bool\nf(mystr())() # E: \"mystr\" not callable\n[builtins fixtures/primitives.pyi]\n\n[case testOverloadedCallWithVariableTypes]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar, List\nT = TypeVar('T', bound=str)\n@overload\ndef f(x: T) -> T: pass\n@overload\ndef f(x: List[T]) -> None: pass\nclass mystr(str): pass\n\nU = TypeVar('U', bound=mystr)\nV = TypeVar('V')\ndef g(x: U, y: V) -> None:\n    f(x)() # E: \"mystr\" not callable\n    f(y) # E: No overload variant of \"f\" matches argument type \"V\" \\\n         # N: Possible overload variants: \\\n         # N:     def [T: str] f(x: T) -> T \\\n         # N:     def [T: str] f(x: List[T]) -> None\n    a = f([x])  # E: \"f\" does not return a value (it only ever returns None)\n    reveal_type(a)  # N: Revealed type is \"None\"\n    f([y]) # E: Value of type variable \"T\" of \"f\" cannot be \"V\"\n    f([x, y]) # E: Value of type variable \"T\" of \"f\" cannot be \"object\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testOverloadOverlapWithTypeVars]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar, Sequence, List\nT = TypeVar('T', bound=str)\n@overload\ndef f(x: Sequence[T]) -> None: pass\n@overload\ndef f(x: Sequence[int]) -> int: pass\n\n@overload\ndef g(x: Sequence[T]) -> None: pass\n@overload\ndef g(x: Sequence[str]) -> int: pass  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n@overload\ndef h(x: Sequence[str]) -> int: pass\n@overload\ndef h(x: Sequence[T]) -> None: pass  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n# Safety of this highly depends on the implementation, so we lean towards being silent.\n@overload\ndef i(x: List[str]) -> int: pass\n@overload\ndef i(x: List[T]) -> None: pass\n[builtins fixtures/list.pyi]\n\n[case testOverloadOverlapWithTypeVarsWithValues]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar\nAnyStr = TypeVar('AnyStr', bytes, str)\n\n@overload\ndef f(x: int) -> int: pass\n@overload\ndef f(x: AnyStr) -> str: pass\n\nf(1)() # E: \"int\" not callable\nf('1')() # E: \"str\" not callable\nf(b'1')() # E: \"str\" not callable\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 [AnyStr: (bytes, str)] f(x: AnyStr) -> str\n\n@overload\ndef g(x: AnyStr, *a: AnyStr) -> None: pass\n@overload\ndef g(x: int, *a: AnyStr) -> None: pass\n\ng('foo')\ng('foo', 'bar')\ng('foo', b'bar') # E: Value of type variable \"AnyStr\" of \"g\" cannot be \"Sequence[object]\" \\\n                 # N: \"AnyStr\" of \"g\" is a constrained type variable, it is not generic\ng(1)\ng(1, 'foo')\ng(1, 'foo', b'bar') # E: Value of type variable \"AnyStr\" of \"g\" cannot be \"Sequence[object]\" \\\n                    # N: \"AnyStr\" of \"g\" is a constrained type variable, it is not generic\n[builtins fixtures/primitives.pyi]\n\n[case testOverloadOverlapWithTypeVarsWithValuesOrdering]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar\nAnyStr = TypeVar('AnyStr', bytes, str)\n\n@overload\ndef f(x: AnyStr) -> AnyStr: pass\n@overload\ndef f(x: str) -> str: pass  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n@overload\ndef g(x: str) -> str: pass\n@overload\ndef g(x: AnyStr) -> AnyStr: pass\n[builtins fixtures/primitives.pyi]\n\n[case testOverloadsUsingAny]\nfrom typing import overload, List, Any, Union\n\n@overload\ndef foo(x: List[int]) -> int: ...\n@overload\ndef foo(x: List[str]) -> str: ...\ndef foo(x): pass\n\na: List[int]\nb: List[str]\nc: List[Any]\nd: Union[List[int], List[str]]\ne: List[bool]\nf: List[object]\ng: List[Union[int, str]]\n\nreveal_type(foo(a))\nreveal_type(foo(b))\nreveal_type(foo(c))\nreveal_type(foo(d))\nfoo(e)\nfoo(f)\nfoo(g)\n\n[builtins fixtures/list.pyi]\n[out]\nmain:17: note: Revealed type is \"builtins.int\"\nmain:18: note: Revealed type is \"builtins.str\"\nmain:19: note: Revealed type is \"Any\"\nmain:20: note: Revealed type is \"Union[builtins.int, builtins.str]\"\nmain:21: error: Argument 1 to \"foo\" has incompatible type \"List[bool]\"; expected \"List[int]\"\nmain:21: note: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance\nmain:21: note: Consider using \"Sequence\" instead, which is covariant\nmain:22: error: Argument 1 to \"foo\" has incompatible type \"List[object]\"; expected \"List[int]\"\nmain:23: error: Argument 1 to \"foo\" has incompatible type \"List[Union[int, str]]\"; expected \"List[int]\"\n\n[case testOverloadAgainstEmptyCollections]\nfrom typing import overload, List\n\n@overload\ndef f(x: List[int]) -> int: ...\n@overload\ndef f(x: List[str]) -> str: ...\ndef f(x): pass\n\nreveal_type(f([]))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadAgainstEmptyCovariantCollections]\nfrom typing import overload, TypeVar, Generic\n\nT = TypeVar('T', covariant=True)\nclass Wrapper(Generic[T]): pass\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\n@overload\ndef f(x: Wrapper[A]) -> int: ...\n@overload\ndef f(x: Wrapper[C]) -> str: ...\ndef f(x): pass\n\nreveal_type(f(Wrapper()))     # N: Revealed type is \"builtins.int\"\nreveal_type(f(Wrapper[C]()))  # N: Revealed type is \"builtins.str\"\nreveal_type(f(Wrapper[B]()))  # N: Revealed type is \"builtins.int\"\n\n[case testOverlappingOverloadCounting]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A: pass\nclass B(A): pass\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: B) -> str: pass # E: Overloaded function signatures 2 and 3 overlap with incompatible return types\n@overload\ndef f(x: A) -> int: pass\n\n[case testOverloadWithTupleMatchingTypeVar]\nfrom foo import *\n[file foo.pyi]\nfrom typing import TypeVar, Generic, Tuple, overload\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    @overload\n    def f(self, arg: T) -> None:\n        pass\n    @overload\n    def f(self, arg: T, default: int) -> None:\n        pass\n\nb = A()  # type: A[Tuple[int, int]]\nb.f((0, 0))\nb.f((0, '')) # E: Argument 1 to \"f\" of \"A\" has incompatible type \"Tuple[int, str]\"; expected \"Tuple[int, int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSingleOverloadStub]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(a: int) -> None: pass\ndef f(a: int) -> None: pass\n[out]\ntmp/foo.pyi:2: error: Single overload definition, multiple required\ntmp/foo.pyi:4: error: An implementation for an overloaded function is not allowed in a stub file\n\n[case testSingleOverload2]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\ndef f(a: int) -> None: pass\n@overload\ndef f(a: str) -> None: pass\n[out]\ntmp/foo.pyi:3: error: Name \"f\" already defined on line 2\ntmp/foo.pyi:3: error: Single overload definition, multiple required\n\n[case testNonconsecutiveOverloads]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(a: int) -> None: pass\n1\n@overload\ndef f(a: str) -> None: pass\n[out]\ntmp/foo.pyi:2: error: Single overload definition, multiple required\ntmp/foo.pyi:5: error: Name \"f\" already defined on line 2\ntmp/foo.pyi:5: error: Single overload definition, multiple required\n\n[case testNonconsecutiveOverloadsMissingFirstOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\ndef f(a: int) -> None: pass\n1\n@overload\ndef f(a: str) -> None: pass\n[out]\ntmp/foo.pyi:4: error: Name \"f\" already defined on line 2\ntmp/foo.pyi:4: error: Single overload definition, multiple required\n\n[case testNonconsecutiveOverloadsMissingLaterOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(a: int) -> None: pass\n1\ndef f(a: str) -> None: pass\n[out]\ntmp/foo.pyi:2: error: Single overload definition, multiple required\ntmp/foo.pyi:5: error: Name \"f\" already defined on line 2\n\n[case testOverloadTuple]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Tuple\n@overload\ndef f(x: int, y: Tuple[str, ...]) -> None: pass\n@overload\ndef f(x: int, y: str) -> None: pass\nf(1, ('2', '3'))\nf(1, (2, '3')) # E: Argument 2 to \"f\" has incompatible type \"Tuple[int, str]\"; expected \"Tuple[str, ...]\"\nf(1, ('2',))\nf(1, '2')\nf(1, (2, 3)) # E: Argument 2 to \"f\" has incompatible type \"Tuple[int, int]\"; expected \"Tuple[str, ...]\"\nx = ('2', '3')  # type: Tuple[str, ...]\nf(1, x)\ny: Tuple[int, ...]\nf(1, y) # E: Argument 2 to \"f\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[str, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testCallableSpecificOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Callable\n@overload\ndef f(a: Callable[[], int]) -> None: pass\n@overload\ndef f(a: str) -> None: pass\nf(0)  # E: No overload variant of \"f\" matches argument type \"int\" \\\n      # N: Possible overload variants: \\\n      # N:     def f(a: Callable[[], int]) -> None \\\n      # N:     def f(a: str) -> None\n\n[case testCustomRedefinitionDecorator]\n\nfrom typing import Any, Callable, Type\n\nclass Chain(object):\n    def chain(self, function: Callable[[Any], int]) -> 'Chain':\n        return self\n\nclass Test(object):\n    do_chain = Chain()\n\n    @do_chain.chain  # E: Name \"do_chain\" already defined on line 9\n    def do_chain(self) -> int:\n        return 2\n\n    @do_chain.chain  # E: Name \"do_chain\" already defined on line 11\n    def do_chain(self) -> int:\n        return 3\n\nt = Test()\nreveal_type(t.do_chain)  # N: Revealed type is \"__main__.Chain\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument1]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: object) -> object: ...\ndef f(x): pass\n\na: Any\nreveal_type(f(a))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument2]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: float) -> float: ...\ndef f(x): pass\n\na: Any\nreveal_type(f(a))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument3]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x): pass\n\na: Any\nreveal_type(f(a))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument4]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int, y: int, z: str) -> int: ...\n@overload\ndef f(x: object, y: int, z: str) -> object: ...\ndef f(x): pass\n\na: Any\n# Any causes ambiguity\nreveal_type(f(a, 1, ''))  # N: Revealed type is \"Any\"\n# Any causes no ambiguity\nreveal_type(f(1, a, a))  # N: Revealed type is \"builtins.int\"\nreveal_type(f('', a, a))  # N: Revealed type is \"builtins.object\"\n# Like above, but use keyword arguments.\nreveal_type(f(y=1, z='', x=a))  # N: Revealed type is \"Any\"\nreveal_type(f(y=a, z='', x=1))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(z='', x=1, y=a))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(z='', x=a, y=1))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument5]\nfrom typing import overload, Any, Union\n\nclass A: pass\nclass B(A): pass\n\n@overload\ndef f(x: B) -> B: ...\n@overload\ndef f(x: Union[A, B]) -> A: ...\ndef f(x): pass\n\n# Note: overloads ignore promotions so we treat 'int' and 'float' as distinct types\n@overload\ndef g(x: int) -> int: ...   # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef g(x: Union[int, float]) -> float: ...\ndef g(x): pass\n\na: Any\nreveal_type(f(a))  # N: Revealed type is \"Any\"\nreveal_type(g(a))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument6]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int, y: int) -> int: ...\n@overload\ndef f(x: float, y: int, z: str) -> float: ...\n@overload\ndef f(x: object, y: int, z: str, a: None) -> str: ...\ndef f(x): pass\n\na: Any\n# Any causes ambiguity\nreveal_type(f(*a))  # N: Revealed type is \"Any\"\nreveal_type(f(a, *a))  # N: Revealed type is \"Any\"\nreveal_type(f(1, *a))  # N: Revealed type is \"Any\"\nreveal_type(f(1.1, *a))  # N: Revealed type is \"Any\"\nreveal_type(f('', *a))  # N: Revealed type is \"builtins.str\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument7]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int, y: int, z: int) -> int: ...\n@overload\ndef f(x: object, y: int, z: int) -> object: ...\ndef f(x): pass\n\n@overload\ndef g(x: int, y: int, z: int) -> int: ...\n@overload\ndef g(x: object, y: int, z: str) -> object: ...\ndef g(x): pass\n\na: Any\nreveal_type(f(1, *a))  # N: Revealed type is \"builtins.int\"\nreveal_type(g(1, *a))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument8]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int, y: int, z: int) -> str: ...\n@overload\ndef f(x: object, y: int, z: int) -> str: ...\ndef f(x): pass\n\na: Any\n# The return type is not ambiguous so Any arguments cause no ambiguity.\nreveal_type(f(a, 1, 1)) # N: Revealed type is \"builtins.str\"\nreveal_type(f(1, *a))  # N: Revealed type is \"builtins.str\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument9]\nfrom typing import overload, Any, List\n\n@overload\ndef f(x: List[int]) -> List[int]: ...\n@overload\ndef f(x: List[Any]) -> List[Any]: ...\ndef f(x): pass\n\na: Any\nb: List[Any]\nc: List[str]\nd: List[int]\nreveal_type(f(a)) # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(f(b))  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(f(c))  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(f(d))  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadWithOverlappingItemsAndAnyArgument10]\nfrom typing import overload, Any\n\n@overload\ndef f(*, x: int = 3, y: int = 3) -> int: ...\n@overload\ndef f(**kwargs: str) -> str: ...\ndef f(*args, **kwargs): pass\n\na: Any\ni: int\nreveal_type(f(x=a, y=i))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(y=a))       # N: Revealed type is \"Any\"\nreveal_type(f(x=a, y=a))  # N: Revealed type is \"Any\"\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadWithOverlappingItemsAndAnyArgument11]\nfrom typing import overload, Any, Dict\n\n@overload\ndef f(x: int = 3, **kwargs: int) -> int: ...\n@overload\ndef f(**kwargs: str) -> str: ...\ndef f(*args, **kwargs): pass\n\na: Dict[str, Any]\ni: int\nreveal_type(f(x=i, **a))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(**a))       # N: Revealed type is \"Any\"\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadWithOverlappingItemsAndAnyArgument12]\nfrom typing import overload, Any\n\n@overload\ndef f(x: int) -> Any: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x): pass\n\na: Any\nreveal_type(f(a))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument13]\nfrom typing import Any, overload, TypeVar, Generic\n\nclass slice: pass\n\nT = TypeVar('T')\nclass A(Generic[T]):\n    @overload\n    def f(self, x: int) -> T: ...\n    @overload\n    def f(self, x: slice) -> A[T]: ...\n    def f(self, x): ...\n\ni: Any\na: A[Any]\nreveal_type(a.f(i))  # N: Revealed type is \"Any\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument14]\nfrom typing import Any, overload, TypeVar, Generic\n\nT = TypeVar('T')\n\nclass Wrapper(Generic[T]): pass\nclass slice: pass\n\nclass A(Generic[T]):\n    @overload\n    def f(self, x: int) -> Wrapper[T]: ...\n    @overload\n    def f(self, x: slice) -> Wrapper[A[T]]: ...\n    def f(self, x): ...\n\ni: Any\na: A[Any]\nreveal_type(a.f(i))  # N: Revealed type is \"__main__.Wrapper[Any]\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument15]\nfrom typing import overload, Any, Union\n\n@overload\ndef f(x: int) -> str: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x): pass\n\n@overload\ndef g(x: int) -> Union[str, int]: ...\n@overload\ndef g(x: str) -> Union[int, str]: ...\ndef g(x): pass\n\na: Any\nreveal_type(f(a))  # N: Revealed type is \"builtins.str\"\nreveal_type(g(a))  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n\n[case testOverloadWithOverlappingItemsAndAnyArgument16]\nfrom typing import overload, Any, Union, Callable\n\n@overload\ndef f(x: int) -> Callable[[int, int], int]: ...\n@overload\ndef f(x: str) -> Callable[[str], str]: ...\ndef f(x): pass\n\na: Any\nreveal_type(f(a))     # N: Revealed type is \"def (*Any, **Any) -> Any\"\nreveal_type(f(a)(a))  # N: Revealed type is \"Any\"\n\n[case testOverloadOnOverloadWithType]\nfrom typing import Any, Type, TypeVar, overload\nfrom mod import MyInt\nT = TypeVar('T')\n\n@overload\ndef make(cls: Type[T]) -> T: pass\n@overload\ndef make() -> Any: pass\n\ndef make(*args):\n    pass\n\nc = make(MyInt)\nreveal_type(c) # N: Revealed type is \"mod.MyInt\"\n\n[file mod.pyi]\nfrom typing import overload\nclass MyInt:\n    @overload\n    def __init__(self, x: str) -> None: pass\n    @overload\n    def __init__(self, x: str, y: int) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testOverloadTupleInstance]\nfrom typing import overload, Tuple, Any\n\nclass A: ...\nclass A1(A): ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef f(x: A) -> A: ...\n@overload\ndef f(x: Tuple[C]) -> B: ...\n@overload\ndef f(x: Tuple[A1, int]) -> C: ...  # E: Overloaded function signatures 3 and 5 overlap with incompatible return types\n@overload\ndef f(x: Tuple[A, str]) -> D: ...\n@overload\ndef f(x: Tuple[A, int]) -> D: ...\n@overload\ndef f(x: Tuple[()]) -> D: ...\ndef f(x: Any) -> Any:...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadTupleEllipsisNumargs]\nfrom typing import overload, Tuple, Any\n\nclass A: ...\nclass B: ...\n\n@overload\ndef r1(x: Tuple[()]) -> B: ...  # E: Overloaded function signatures 1 and 4 overlap with incompatible return types\n@overload\ndef r1(x: Tuple[A]) -> B: ...  # E: Overloaded function signatures 2 and 4 overlap with incompatible return types\n@overload\ndef r1(x: Tuple[A, A]) -> B: ...  # E: Overloaded function signatures 3 and 4 overlap with incompatible return types\n@overload\ndef r1(x: Tuple[A, ...]) -> A: ...\ndef r1(x: Any) -> Any: ...\n\n@overload\ndef r2(x: Tuple[A, ...]) -> A: ...\n@overload\ndef r2(x: Tuple[A, A]) -> B: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n@overload\ndef r2(x: Tuple[A]) -> B: ...  # E: Overloaded function signature 3 will never be matched: signature 1's parameter type(s) are the same or broader\n@overload\ndef r2(x: Tuple[()]) -> B: ...  # E: Overloaded function signature 4 will never be matched: signature 1's parameter type(s) are the same or broader\ndef r2(x: Any) -> Any: ...\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadTupleEllipsisVariance]\nfrom typing import overload, Tuple, Any\n\nclass A: ...\nclass A1(A): ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef r(x: Tuple[A1, ...]) -> A: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef r(x: Tuple[A, ...]) -> B: ...\n@overload\ndef r(x: Tuple[B, ...]) -> C: ...\ndef r(x: Any) -> Any:...\n\n@overload\ndef g(x: A) -> A: ...\n@overload\ndef g(x: Tuple[A1, ...]) -> B: ...  # E: Overloaded function signatures 2 and 3 overlap with incompatible return types\n@overload\ndef g(x: Tuple[A, A]) -> C: ...\n@overload\ndef g(x: Tuple[A, B]) -> D: ...\ndef g(x: Any) -> Any:...\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadWithMethodOverrideAndImplementation]\nfrom typing import overload, Union, Any\n\nclass Parent:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n\nclass Child1(Parent):\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Union[int, str]) -> Union[int, str]: ...\n\nclass Child2(Parent):\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Union[int, str]) -> int: ... # E: Overloaded function implementation cannot produce return type of signature 2\n\nclass Child3(Parent):\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n\nclass Child4(Parent):\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Union[int, str]) -> Union[int, str]:\n        return b''  # E: Incompatible return value type (got \"bytes\", expected \"Union[int, str]\")\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadWithIncompatibleMethodOverrideAndImplementation]\nfrom typing import overload, Union, Any\n\nclass StrSub: pass\n\nclass ParentWithTypedImpl:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Union[int, str]) -> Union[int, str]: ...\n\nclass Child1(ParentWithTypedImpl):\n    @overload  # Fail\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: StrSub) -> str: ...\n    def f(self, arg: Union[int, StrSub]) -> Union[int, str]: ...\n\nclass Child2(ParentWithTypedImpl):\n    @overload  # Fail\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: StrSub) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n\nclass ParentWithDynamicImpl:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n\nclass Child3(ParentWithDynamicImpl):\n    @overload  # Fail\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: StrSub) -> str: ...\n    def f(self, arg: Union[int, StrSub]) -> Union[int, str]: ...\n\nclass Child4(ParentWithDynamicImpl):\n    @overload  # Fail\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: StrSub) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nmain:13: error: Signature of \"f\" incompatible with supertype \"ParentWithTypedImpl\"\nmain:13: note:      Superclass:\nmain:13: note:          @overload\nmain:13: note:          def f(self, arg: int) -> int\nmain:13: note:          @overload\nmain:13: note:          def f(self, arg: str) -> str\nmain:13: note:      Subclass:\nmain:13: note:          @overload\nmain:13: note:          def f(self, arg: int) -> int\nmain:13: note:          @overload\nmain:13: note:          def f(self, arg: StrSub) -> str\nmain:20: error: Signature of \"f\" incompatible with supertype \"ParentWithTypedImpl\"\nmain:20: note:      Superclass:\nmain:20: note:          @overload\nmain:20: note:          def f(self, arg: int) -> int\nmain:20: note:          @overload\nmain:20: note:          def f(self, arg: str) -> str\nmain:20: note:      Subclass:\nmain:20: note:          @overload\nmain:20: note:          def f(self, arg: int) -> int\nmain:20: note:          @overload\nmain:20: note:          def f(self, arg: StrSub) -> str\nmain:34: error: Signature of \"f\" incompatible with supertype \"ParentWithDynamicImpl\"\nmain:34: note:      Superclass:\nmain:34: note:          @overload\nmain:34: note:          def f(self, arg: int) -> int\nmain:34: note:          @overload\nmain:34: note:          def f(self, arg: str) -> str\nmain:34: note:      Subclass:\nmain:34: note:          @overload\nmain:34: note:          def f(self, arg: int) -> int\nmain:34: note:          @overload\nmain:34: note:          def f(self, arg: StrSub) -> str\nmain:41: error: Signature of \"f\" incompatible with supertype \"ParentWithDynamicImpl\"\nmain:41: note:      Superclass:\nmain:41: note:          @overload\nmain:41: note:          def f(self, arg: int) -> int\nmain:41: note:          @overload\nmain:41: note:          def f(self, arg: str) -> str\nmain:41: note:      Subclass:\nmain:41: note:          @overload\nmain:41: note:          def f(self, arg: int) -> int\nmain:41: note:          @overload\nmain:41: note:          def f(self, arg: StrSub) -> str\n\n[case testOverloadAnyIsConsideredValidReturnSubtype]\nfrom typing import Any, overload, Optional\n\n@overload\ndef foo(x: None) -> Any: ...\n@overload\ndef foo(x: Optional[str]) -> str: ...\ndef foo(x): pass\n\n@overload\ndef bar(x: None) -> object: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef bar(x: Optional[str]) -> str: ...\ndef bar(x): pass\n\n[case testOverloadWithNonPositionalArgs]\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\n\n@overload\ndef foo(*, p1: A, p2: B = B()) -> A: ...\n@overload\ndef foo(*, p2: B = B()) -> B: ...\ndef foo(p1, p2=None): ...\n\nreveal_type(foo())  # N: Revealed type is \"__main__.B\"\nreveal_type(foo(p2=B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(foo(p1=A()))  # N: Revealed type is \"__main__.A\"\n\n[case testOverloadWithNonPositionalArgsIgnoresOrder]\nfrom typing import overload\n\nclass A: ...\nclass B(A): ...\nclass X: ...\nclass Y: ...\n\n@overload\ndef f(*, p1: X, p2: A) -> X: ...\n@overload\ndef f(*, p2: B, p1: X) -> Y: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\ndef f(*, p1, p2): ...\n\n@overload\ndef g(*, p1: X, p2: B) -> X: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef g(*, p2: A, p1: X) -> Y: ...\ndef g(*, p1, p2): ...\n\n[case testOverloadWithVariableArgsAreOverlapping]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n# Safety of this highly depends on the implementation, so we lean towards being silent.\n@overload\ndef foo1(*x: int) -> int: ...\n@overload\ndef foo1(x: int, y: int, z: int) -> str: ...\n\n@overload\ndef foo2(*x: int) -> int: ...\n@overload\ndef foo2(x: int, y: str, z: int) -> str: ...\n\n# Note: this is technically unsafe, but we don't report this for now.\n@overload\ndef bar1(x: int, y: int, z: int) -> str: ...\n@overload\ndef bar1(*x: int) -> int: ...\n\n@overload\ndef bar2(x: int, y: str, z: int) -> str: ...\n@overload\ndef bar2(*x: int) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadDetectsPossibleMatchesWithGenerics]\n# flags: --strict-optional\nfrom typing import overload, TypeVar, Generic, Optional, List\n\nT = TypeVar('T')\n# The examples below are unsafe, but it is a quite common pattern\n# so we ignore the possibility of type variables taking value `None`\n# for the purpose of overload overlap checks.\n\n@overload\ndef foo(x: None, y: None) -> str: ...\n@overload\ndef foo(x: T, y: T) -> int: ...\ndef foo(x): ...\n\noi: Optional[int]\nreveal_type(foo(None, None))  # N: Revealed type is \"builtins.str\"\nreveal_type(foo(None, 42))  # N: Revealed type is \"builtins.int\"\nreveal_type(foo(42, 42))  # N: Revealed type is \"builtins.int\"\nreveal_type(foo(oi, None))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(foo(oi, 42))  # N: Revealed type is \"builtins.int\"\nreveal_type(foo(oi, oi))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\n@overload\ndef foo_list(x: None) -> None: ...\n@overload\ndef foo_list(x: T) -> List[T]: ...\ndef foo_list(x): ...\n\nreveal_type(foo_list(oi))  # N: Revealed type is \"Union[builtins.list[builtins.int], None]\"\n\n# What if 'T' is 'object'?\n@overload\ndef bar(x: None, y: int) -> str: ...\n@overload\ndef bar(x: T, y: T) -> int: ...\ndef bar(x, y): ...\n\nclass Wrapper(Generic[T]):\n    @overload\n    def foo(self, x: None, y: None) -> str: ...\n    @overload\n    def foo(self, x: T, y: None) -> int: ...\n    def foo(self, x): ...\n\n    @overload\n    def bar(self, x: None, y: int) -> str: ...\n    @overload\n    def bar(self, x: T, y: T) -> int: ...\n    def bar(self, x, y): ...\n\n@overload\ndef baz(x: str, y: str) -> str: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef baz(x: T, y: T) -> int: ...\ndef baz(x): ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadFlagsPossibleMatches]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(x: str) -> str: ...\n@overload\ndef foo1(x: str, y: str = ...) -> int: ...\n\n@overload\ndef foo2(x: str, y: str = ...) -> int: ...\n@overload\ndef foo2(x: str) -> str: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n@overload\ndef foo3(x: str) -> str: ...\n@overload\ndef foo3(x: str, y: str) -> int: ...\n\n[case testOverloadPossibleOverlapWithArgsAndKwargs]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(*args: int) -> int: ...\n@overload\ndef foo1(**kwargs: int) -> str: ...\n\n@overload\ndef foo2(**kwargs: int) -> str: ...\n@overload\ndef foo2(*args: int) -> int: ...\n[builtins fixtures/dict.pyi]\n\n[case testOverloadPossibleOverlapWithVarargs]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(*args: int) -> int: ...\n@overload\ndef foo1(*args2: int) -> str: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n@overload\ndef foo2(*args: int) -> str: ...\n@overload\ndef foo2(*args2: str) -> int: ...\n\n@overload\ndef foo3(*args: int) -> str: ...\n@overload\ndef foo3(*args: str) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapWithVarargs2]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(*args: str) -> int: ...\n@overload\ndef foo1(x: int, *args2: int) -> str: ...\n\n@overload\ndef foo2(x: int, *args: int) -> str: ...\n@overload\ndef foo2(*args2: str) -> int: ...\n\n# The two examples are unsafe, but this is hard to detect.\n@overload\ndef foo3(*args: int) -> int: ...\n@overload\ndef foo3(x: int, *args2: int) -> str: ...\n\n@overload\ndef foo4(x: int, *args: int) -> str: ...\n@overload\ndef foo4(*args2: int) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapWithVarargs3]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\nclass Other: ...\n\n@overload\ndef foo1(x: Other, *args: int) -> str: ...\n@overload\ndef foo1(*args: str) -> int: ...\n\n@overload\ndef foo2(*args: int) -> str: ...\n@overload\ndef foo2(x: Other, *args: str) -> int: ...\n\n@overload\ndef foo3(x: Other = ..., *args: int) -> str: ...\n@overload\ndef foo3(*args: str) -> int: ...\n\n@overload\ndef foo4(*args: int) -> str: ...\n@overload\ndef foo4(x: Other = ..., *args: str) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapWithVarargs4]\nfrom typing import overload\n\n@overload\ndef foo1(x: int = 0, y: int = 0) -> int: ...\n@overload\ndef foo1(*xs: int) -> str: ...\ndef foo1(*args): pass\n\n@overload\ndef foo2(*xs: int) -> str: ...\n@overload\ndef foo2(x: int = 0, y: int = 0) -> int: ...\ndef foo2(*args): pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapWithKwargs]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(**kwargs: int) -> int: ...\n@overload\ndef foo1(**kwargs2: int) -> str: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n@overload\ndef foo2(**kwargs: int) -> str: ...\n@overload\ndef foo2(**kwargs2: str) -> int: ...\n\n@overload\ndef foo(**kwargs: int) -> str: ...\n@overload\ndef foo(**kwargs: str) -> int: ...\n[builtins fixtures/dict.pyi]\n\n[case testOverloadPossibleOverlapMixingNamedArgsWithVarargs]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(x: str, *, y: str) -> str: ...\n@overload\ndef foo1(*x: str) -> int: ...\n\n@overload\ndef foo2(*x: str) -> int: ...\n@overload\ndef foo2(x: str, *, y: str) -> str: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapMixingOptionalArgsWithVarargs]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(x: str, y: str = ..., z: str = ...) -> str: ...\n@overload\ndef foo1(*x: str) -> int: ...\n\n@overload\ndef foo2(*x: str) -> int: ...\n@overload\ndef foo2(x: str, y: str = ..., z: str = ...) -> str: ...\n\n@overload\ndef foo3(x: int, y: str = ..., z: str = ...) -> str: ...\n@overload\ndef foo3(*x: str) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapMixingOptionalArgsWithVarargs2]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(x: str, y: str = ..., z: int = ...) -> str: ...\n@overload\ndef foo1(*x: str) -> int: ...\n\n@overload\ndef foo2(x: str, y: str = ..., z: int = ...) -> str: ...\n@overload\ndef foo2(*x: str) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadPossibleOverlapMixingNamedArgsWithKwargs]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(*, x: str, y: str, z: str) -> str: ...\n@overload\ndef foo1(**x: str) -> int: ...\n\n@overload\ndef foo2(**x: str) -> int: ...\n@overload\ndef foo2(*, x: str, y: str, z: str) -> str: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n@overload\ndef foo3(*, x: int, y: str, z: str) -> str: ...\n@overload\ndef foo3(*x: str) -> int: ...\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadPossibleOverlapMixingNamedArgsWithKwargs2]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(*, x: str, y: str, z: int) -> str: ...\n@overload\ndef foo1(**x: str) -> int: ...\n\n@overload\ndef foo2(**x: str) -> int: ...\n@overload\ndef foo2(*, x: str, y: str, z: int) -> str: ...\n\n@overload\ndef foo3(*, x: str, y: str, z: int = ...) -> str: ...\n@overload\ndef foo3(**x: str) -> int: ...\n\n@overload\ndef foo4(**x: str) -> int: ...\n@overload\ndef foo4(*, x: str, y: str, z: int = ...) -> str: ...\n[builtins fixtures/dict.pyi]\n\n[case testOverloadPossibleOverlapMixingNamedArgsWithKwargs3]\nfrom wrapper import *\n[file wrapper.pyi]\nfrom typing import overload\n\n@overload\ndef foo1(x: str, *, y: str, z: str) -> str: ...  # 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 foo1(**x: str) -> int: ...\n\n@overload\ndef foo2(**x: str) -> int: ...\n@overload\ndef foo2(x: str, *, y: str, z: str) -> str: ...\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadVarargInputAndVarargDefinition]\nfrom typing import overload, List\n\nclass A: ...\nclass B: ...\nclass C: ...\n\n@overload\ndef foo(x: int) -> A: ...\n@overload\ndef foo(x: int, y: int) -> B: ...\n@overload\ndef foo(x: int, y: int, z: int, *args: int) -> C: ...\ndef foo(*args): pass\n\nreveal_type(foo(1))        # N: Revealed type is \"__main__.A\"\nreveal_type(foo(1, 2))     # N: Revealed type is \"__main__.B\"\nreveal_type(foo(1, 2, 3))  # N: Revealed type is \"__main__.C\"\n\nreveal_type(foo(*[1]))        # N: Revealed type is \"__main__.C\"\nreveal_type(foo(*[1, 2]))     # N: Revealed type is \"__main__.C\"\nreveal_type(foo(*[1, 2, 3]))  # N: Revealed type is \"__main__.C\"\n\nx: List[int]\nreveal_type(foo(*x))  # N: Revealed type is \"__main__.C\"\n\ny: List[str]\nfoo(*y)  # E: No overload variant of \"foo\" matches argument type \"List[str]\" \\\n         # N: Possible overload variants: \\\n         # N:     def foo(x: int) -> A \\\n         # N:     def foo(x: int, y: int) -> B \\\n         # N:     def foo(x: int, y: int, z: int, *args: int) -> C\n[builtins fixtures/list.pyi]\n\n[case testOverloadMultipleVarargDefinition]\nfrom typing import overload, List, Any\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef foo(x: int) -> A: ...\n@overload\ndef foo(x: int, y: int) -> B: ...\n@overload\ndef foo(x: int, y: int, z: int, *args: int) -> C: ...\n@overload\ndef foo(*x: str) -> D: ...\ndef foo(*args): pass\n\nreveal_type(foo(*[1, 2]))      # N: Revealed type is \"__main__.C\"\nreveal_type(foo(*[\"a\", \"b\"]))  # N: Revealed type is \"__main__.D\"\n\nx: List[Any]\nreveal_type(foo(*x))  # N: Revealed type is \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadMultipleVarargDefinitionComplex]\nfrom typing import TypeVar, overload, Any, Callable\n\nT1 = TypeVar('T1')\nT2 = TypeVar('T2')\nT3 = TypeVar('T3')\n\n@overload\ndef chain_call(input_value: T1,\n               f1: Callable[[T1], T2]) -> T2: ...\n@overload\ndef chain_call(input_value: T1,\n               f1: Callable[[T1], T2],\n               f2: Callable[[T2], T3]) -> T3: ...\n@overload\ndef chain_call(input_value: T1,\n               *f_rest: Callable[[T1], T1]) -> T1: ...\n@overload\ndef chain_call(input_value: T1,\n               f1: Callable[[T1], T2],\n               f2: Callable[[T2], T3],\n               f3: Callable[[T3], Any],\n               *f_rest: Callable[[Any], Any]) -> Any: ...\ndef chain_call(input_value, *f_rest):\n    for function in f_rest:\n        input_value = function(input_value)\n    return input_value\n\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\ndef f(x: A) -> A: ...\ndef f1(x: A) -> B: ...\ndef f2(x: B) -> C: ...\ndef f3(x: C) -> D: ...\n\nreveal_type(chain_call(A(), f1, f2))       # N: Revealed type is \"__main__.C\"\nreveal_type(chain_call(A(), f1, f2, f3))   # N: Revealed type is \"Any\"\nreveal_type(chain_call(A(), f, f, f, f))   # N: Revealed type is \"__main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadVarargsSelection]\nfrom typing import overload, Tuple\n@overload\ndef f(x: int) -> Tuple[int]: ...\n@overload\ndef f(x: int, y: int) -> Tuple[int, int]: ...\n@overload\ndef f(*xs: int) -> Tuple[int, ...]: ...\ndef f(*args): pass\n\ni: int\nreveal_type(f(i))           # N: Revealed type is \"Tuple[builtins.int]\"\nreveal_type(f(i, i))        # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\nreveal_type(f(i, i, i))     # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nreveal_type(f(*[]))         # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(*[i]))        # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(*[i, i]))     # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(*[i, i, i]))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadVarargsSelectionWithTuples]\nfrom typing import overload, Tuple\n@overload\ndef f(x: int) -> Tuple[int]: ...\n@overload\ndef f(x: int, y: int) -> Tuple[int, int]: ...\n@overload\ndef f(*xs: int) -> Tuple[int, ...]: ...\ndef f(*args): pass\n\ni: int\nreveal_type(f(*()))         # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(*(i,)))       # N: Revealed type is \"Tuple[builtins.int]\"\nreveal_type(f(*(i, i)))     # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\nreveal_type(f(*(i, i, i)))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadVarargsSelectionWithNamedTuples]\nfrom typing import overload, Tuple, NamedTuple\n@overload\ndef f(x: int, y: int) -> Tuple[int, int]: ...\n@overload\ndef f(*xs: int) -> Tuple[int, ...]: ...\ndef f(*args): pass\n\nA = NamedTuple('A', [('x', int), ('y', int)])\nB = NamedTuple('B', [('a', int), ('b', int)])\nC = NamedTuple('C', [('a', int), ('b', int), ('c', int)])\n\na: A\nb: B\nc: C\nreveal_type(f(*a))  # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\nreveal_type(f(*b))  # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\nreveal_type(f(*c))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadKwargsSelectionWithDict]\nfrom typing import overload, Tuple, Dict\n@overload\ndef f(*, x: int) -> Tuple[int]: ...\n@overload\ndef f(*, x: int, y: int) -> Tuple[int, int]: ...\n@overload\ndef f(**xs: int) -> Tuple[int, ...]: ...\ndef f(**kwargs): pass\n\nempty: Dict[str, int]\nreveal_type(f(**empty))                      # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(**{'x': 4}))                   # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(**{'x': 4, 'y': 4}))           # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(f(**{'a': 4, 'b': 4, 'c': 4}))   # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/dict.pyi]\n\n[case testOverloadKwargsSelectionWithTypedDict]\nfrom typing import overload, Tuple\nfrom typing_extensions import TypedDict\n@overload\ndef f(*, x: int) -> Tuple[int]: ...\n@overload\ndef f(*, x: int, y: int) -> Tuple[int, int]: ...\n@overload\ndef f(**xs: int) -> Tuple[int, ...]: ...\ndef f(**args): pass\n\nA = TypedDict('A', {'x': int})\nB = TypedDict('B', {'x': int, 'y': int})\nC = TypedDict('C', {'x': int, 'y': int, 'z': int})\n\na: A\nb: B\nc: C\n\nreveal_type(f(**a))  # N: Revealed type is \"Tuple[builtins.int]\"\nreveal_type(f(**b))  # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\nreveal_type(f(**c))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/dict.pyi]\n\n[case testOverloadVarargsAndKwargsSelection]\nfrom typing import overload, Any, Tuple, Dict\n\nclass A: pass\nclass B(A): pass\n\n@overload\ndef f(x: int, y: int) -> B: pass\n@overload\ndef f(x: int, y: int, **kwargs: int) -> A: pass\n@overload\ndef f(*args: int, **kwargs: int) -> Any: pass\ndef f(*args, **kwargs): pass\n\na: Tuple[int, int]\nb: Tuple[int, ...]\nc: Dict[str, int]\n\nreveal_type(f(*a, **c))  # N: Revealed type is \"__main__.A\"\nreveal_type(f(*b, **c))  # N: Revealed type is \"__main__.A\"\nreveal_type(f(*a))       # N: Revealed type is \"__main__.B\"\nreveal_type(f(*b))       # N: Revealed type is \"Any\"\n\n# TODO: Should this be 'Any' instead?\n# The first matching overload with a kwarg is f(int, int, **int) -> A,\n# but f(*int, **int) -> Any feels like a better fit.\nreveal_type(f(**c))      # N: Revealed type is \"__main__.A\"\n[builtins fixtures/args.pyi]\n\n[case testOverloadWithPartiallyOverlappingUnions]\nfrom typing import overload, Union\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef f(x: Union[A, B]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: Union[B, C]) -> str: ...\ndef f(x): ...\n\n@overload\ndef g(x: Union[A, B]) -> int: ...\n@overload\ndef g(x: Union[B, C]) -> int: ...\ndef g(x): ...\n\n@overload\ndef h(x: Union[A, B]) -> int: ...\n@overload\ndef h(x: Union[C, D]) -> str: ...\ndef h(x): ...\n\n@overload\ndef i(x: Union[A, B]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef i(x: Union[A, B, C]) -> str: ...\ndef i(x): ...\n\n[case testOverloadWithPartiallyOverlappingUnionsNested]\nfrom typing import overload, Union, List\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef f(x: List[Union[A, B]]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: List[Union[B, C]]) -> str: ...\ndef f(x): ...\n\n@overload\ndef g(x: List[Union[A, B]]) -> int: ...\n@overload\ndef g(x: List[Union[B, C]]) -> int: ...\ndef g(x): ...\n\n@overload\ndef h(x: List[Union[A, B]]) -> int: ...\n@overload\ndef h(x: List[Union[C, D]]) -> str: ...\ndef h(x): ...\n\n@overload\ndef i(x: List[Union[A, B]]) -> int: ...  # 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 i(x: List[Union[A, B, C]]) -> str: ...\ndef i(x): ...\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadPartialOverlapWithUnrestrictedTypeVar]\nfrom typing import TypeVar, overload\n\nT = TypeVar('T')\n\n# Note: this is unsafe, but it is hard to detect.\n@overload\ndef f(x: int) -> str: ...\n@overload\ndef f(x: T) -> T: ...\ndef f(x): ...\n\n@overload\ndef g(x: int) -> int: ...\n@overload\ndef g(x: T) -> T: ...\ndef g(x): ...\n\n[case testOverloadPartialOverlapWithUnrestrictedTypeVarNested]\nfrom typing import TypeVar, overload, List\n\nT = TypeVar('T')\n\n# Note: first two examples are unsafe, but it is hard to detect.\n@overload\ndef f1(x: List[int]) -> str: ...\n@overload\ndef f1(x: List[T]) -> T: ...\ndef f1(x): ...\n\n@overload\ndef f2(x: List[int]) -> List[str]: ...\n@overload\ndef f2(x: List[T]) -> List[T]: ...\ndef f2(x): ...\n\n@overload\ndef g1(x: List[int]) -> int: ...\n@overload\ndef g1(x: List[T]) -> T: ...\ndef g1(x): ...\n\n@overload\ndef g2(x: List[int]) -> List[int]: ...\n@overload\ndef g2(x: List[T]) -> List[T]: ...\ndef g2(x): ...\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadPartialOverlapWithUnrestrictedTypeVarInClass]\nfrom typing import TypeVar, overload, Generic\n\nT = TypeVar('T')\n\nclass Wrapper(Generic[T]):\n    # Similar to above: this is unsafe, but it is hard to detect.\n    @overload\n    def f(self, x: int) -> str: ...\n    @overload\n    def f(self, x: T) -> T: ...\n    def f(self, x): ...\n\n    @overload\n    def g(self, x: int) -> int: ...\n    @overload\n    def g(self, x: T) -> T: ...\n    def g(self, x): ...\n\n[case testOverloadPartialOverlapWithUnrestrictedTypeVarInClassNested]\nfrom typing import TypeVar, overload, Generic, List\n\nT = TypeVar('T')\n\nclass Wrapper(Generic[T]):\n    # Similar to above: first two examples are unsafe, but it is hard to detect.\n    @overload\n    def f1(self, x: List[int]) -> str: ...\n    @overload\n    def f1(self, x: List[T]) -> T: ...\n    def f1(self, x): ...\n\n    @overload\n    def f2(self, x: List[int]) -> List[str]: ...\n    @overload\n    def f2(self, x: List[T]) -> List[T]: ...\n    def f2(self, x): ...\n\n    @overload\n    def g1(self, x: List[int]) -> int: ...\n    @overload\n    def g1(self, x: List[T]) -> T: ...\n    def g1(self, x): ...\n\n    @overload\n    def g2(self, x: List[int]) -> List[int]: ...\n    @overload\n    def g2(self, x: List[T]) -> List[T]: ...\n    def g2(self, x): ...\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadTypedDictDifferentRequiredKeysMeansDictsAreDisjoint]\nfrom typing import overload\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': int})\nB = TypedDict('B', {'x': int, 'y': str})\n\n@overload\ndef f(x: A) -> int: ...\n@overload\ndef f(x: B) -> str: ...\ndef f(x): pass\n[builtins fixtures/dict.pyi]\n\n[case testOverloadedTypedDictPartiallyOverlappingRequiredKeys]\nfrom typing import overload, Union\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': Union[int, str]})\nB = TypedDict('B', {'x': int, 'y': Union[str, float]})\n\n@overload\ndef f(x: A) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: B) -> str: ...\ndef f(x): pass\n\n@overload\ndef g(x: A) -> int: ...\n@overload\ndef g(x: B) -> object: ...\ndef g(x): pass\n[builtins fixtures/dict.pyi]\n\n[case testOverloadedTypedDictFullyNonTotalDictsAreAlwaysPartiallyOverlapping]\nfrom typing import overload\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str}, total=False)\nB = TypedDict('B', {'a': bool}, total=False)\nC = TypedDict('C', {'x': str, 'y': int}, total=False)\n\n@overload\ndef f(x: A) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: B) -> str: ...\ndef f(x): pass\n\n@overload\ndef g(x: A) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef g(x: C) -> str: ...\ndef g(x): pass\n[builtins fixtures/dict.pyi]\n\n[case testOverloadedTotalAndNonTotalTypedDictsCanPartiallyOverlap]\nfrom typing import overload, Union\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str})\nB = TypedDict('B', {'x': Union[int, str], 'y': str, 'z': int}, total=False)\n\n@overload\ndef f1(x: A) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f1(x: B) -> str: ...\ndef f1(x): pass\n\n@overload\ndef f2(x: B) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f2(x: A) -> str: ...\ndef f2(x): pass\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadedTypedDictsWithSomeOptionalKeysArePartiallyOverlapping]\nfrom typing import overload, Union\nfrom mypy_extensions import TypedDict\n\nclass A(TypedDict):\n    x: int\n    y: int\n\nclass B(TypedDict, total=False):\n    z: str\n\nclass C(TypedDict, total=False):\n    z: int\n\n@overload\ndef f(x: B) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: C) -> str: ...\ndef f(x): pass\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadedPartiallyOverlappingInheritedTypes1]\nfrom typing import overload, List, Union, TypeVar, Generic\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nT = TypeVar('T')\n\nclass ListSubclass(List[T]): pass\nclass Unrelated(Generic[T]): pass\n\n@overload\ndef f(x: List[Union[A, B]]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: ListSubclass[Union[B, C]]) -> str: ...\ndef f(x): pass\n\n@overload\ndef g(x: List[Union[A, B]]) -> int: ...\n@overload\ndef g(x: Unrelated[Union[B, C]]) -> str: ...\ndef g(x): pass\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadedPartiallyOverlappingInheritedTypes2]\nfrom typing import overload, List, Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nclass ListSubclass(List[Union[B, C]]): pass\n\n@overload\ndef f(x: List[Union[A, B]]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: ListSubclass) -> str: ...\ndef f(x): pass\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadedPartiallyOverlappingInheritedTypes3]\nfrom typing import overload, Union, Dict, TypeVar\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nS = TypeVar('S')\n\nclass DictSubclass(Dict[str, S]): pass\n\n@overload\ndef f(x: Dict[str, Union[A, B]]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: DictSubclass[Union[B, C]]) -> str: ...\ndef f(x): pass\n\n[builtins fixtures/dict.pyi]\n\n[case testOverloadedPartiallyOverlappingTypeVarsAndUnion]\nfrom typing import overload, TypeVar, Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nS = TypeVar('S', A, B)\n\n@overload\ndef f(x: S) -> int: ...  # 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 f(x: Union[B, C]) -> str: ...\ndef f(x): pass\n\n@overload\ndef g(x: Union[B, C]) -> int: ...\n@overload\ndef g(x: S) -> str: ...\ndef g(x): pass\n\n[case testOverloadPartiallyOverlappingTypeVarsIdentical]\nfrom typing import overload, TypeVar, Union\n\nT = TypeVar('T')\n\nclass A: pass\nclass B: pass\nclass C: pass\n\n@overload\ndef f(x: T, y: T, z: Union[A, B]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: T, y: T, z: Union[B, C]) -> str: ...\ndef f(x, y, z): pass\n\n[case testOverloadedPartiallyOverlappingCallables]\nfrom typing import overload, Union, Callable\n\nclass A: pass\nclass B: pass\nclass C: pass\n\n@overload\ndef f(x: Callable[[Union[A, B]], int]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: Callable[[Union[B, C]], int]) -> str: ...\ndef f(x): pass\n\n[case testOverloadNotConfusedForProperty]\nfrom typing import overload\n\nclass PropertyClass:\n    @property\n    def foo(self) -> str: return \"...\"\n    @foo.setter\n    def foo(self, value: str) -> None: pass\n    @foo.deleter\n    def foo(self) -> None: pass\n\nclass OverloadClass:\n    @overload\n    def foo(self) -> str: pass\n    @overload\n    def foo(self, value: str) -> None: pass\n    @overload\n    def foo(self) -> None: pass  # E: Overloaded function signature 3 will never be matched: signature 1's parameter type(s) are the same or broader\n    def foo(self, *args): pass\n\n[builtins fixtures/property.pyi]\n\n[case testOverloadInferUnionReturnBasic]\nfrom typing import overload, Union\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef f1(x: A) -> B: ...\n@overload\ndef f1(x: C) -> D: ...\ndef f1(x): ...\n\narg1: Union[A, C]\nreveal_type(f1(arg1))  # N: Revealed type is \"Union[__main__.B, __main__.D]\"\n\narg2: Union[A, B]\nf1(arg2)  # E: Argument 1 to \"f1\" has incompatible type \"Union[A, B]\"; expected \"A\"\n\n@overload\ndef f2(x: A) -> B: ...\n@overload\ndef f2(x: C) -> B: ...\ndef f2(x): ...\n\nreveal_type(f2(arg1))  # N: Revealed type is \"__main__.B\"\n\n[case testOverloadInferUnionReturnMultipleArguments]\nfrom typing import overload, Union\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef f1(x: A, y: C) -> B: ...\n@overload\ndef f1(x: C, y: A) -> D: ...\ndef f1(x, y): ...\n\narg1: Union[A, C]\nreveal_type(f1(arg1, arg1))\n\n@overload\ndef f2(x: A, y: C) -> B: ...\n@overload\ndef f2(x: C, y: C) -> D: ...\ndef f2(x, y): ...\n\nreveal_type(f2(arg1, arg1))\nreveal_type(f2(arg1, C()))\n\n[out]\nmain:15: note: Revealed type is \"__main__.B\"\nmain:15: error: Argument 1 to \"f1\" has incompatible type \"Union[A, C]\"; expected \"A\"\nmain:15: error: Argument 2 to \"f1\" has incompatible type \"Union[A, C]\"; expected \"C\"\nmain:23: note: Revealed type is \"__main__.B\"\nmain:23: error: Argument 1 to \"f2\" has incompatible type \"Union[A, C]\"; expected \"A\"\nmain:23: error: Argument 2 to \"f2\" has incompatible type \"Union[A, C]\"; expected \"C\"\nmain:24: note: Revealed type is \"Union[__main__.B, __main__.D]\"\n\n[case testOverloadInferUnionRespectsVariance]\nfrom typing import overload, TypeVar, Union, Generic\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass WrapperCo(Generic[T_co]): pass\nclass WrapperContra(Generic[T_contra]): pass\n\n@overload\ndef foo(x: WrapperCo[B]) -> int: ...\n@overload\ndef foo(x: WrapperContra[B]) -> str: ...\ndef foo(x): pass\n\ncompat: Union[WrapperCo[C], WrapperContra[A]]\nreveal_type(foo(compat))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\nnot_compat: Union[WrapperCo[A], WrapperContra[C]]\nfoo(not_compat)  # E: Argument 1 to \"foo\" has incompatible type \"Union[WrapperCo[A], WrapperContra[C]]\"; expected \"WrapperCo[B]\"\n\n[case testOverloadInferUnionIfParameterNamesAreDifferent]\nfrom typing import overload, Union\n\nclass A: ...\nclass B: ...\nclass C: ...\n\n@overload\ndef f(x: A) -> B: ...\n@overload\ndef f(y: B) -> C: ...\ndef f(x): ...\n\nx: Union[A, B]\nreveal_type(f(A()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f(B()))  # N: Revealed type is \"__main__.C\"\nreveal_type(f(x))    # N: Revealed type is \"Union[__main__.B, __main__.C]\"\n\n[case testOverloadInferUnionReturnFunctionsWithKwargs]\nfrom typing import overload, Union, Optional\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D(B, C): ...\n\n@overload\ndef f(x: A) -> D: ...\n@overload\ndef f(x: A, y: Optional[B] = None) -> C: ...\n@overload\ndef f(x: A, z: Optional[C] = None) -> B: ...\ndef f(x, y=None, z=None): ...\n\nreveal_type(f(A(), B()))  # N: Revealed type is \"__main__.C\"\nreveal_type(f(A(), C()))  # N: Revealed type is \"__main__.B\"\n\narg: Union[B, C]\nreveal_type(f(A(), arg))  # N: Revealed type is \"Union[__main__.C, __main__.B]\"\nreveal_type(f(A()))       # N: Revealed type is \"__main__.D\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadInferUnionWithDifferingLengths]\nfrom typing import overload, Union\n\nclass Parent: ...\nclass Child(Parent): ...\n\nclass A: ...\nclass B: ...\n\n@overload\ndef f(x: A) -> Child: ...\n@overload\ndef f(x: B, y: B = B()) -> Parent: ...\ndef f(*args): ...\n\nx: Union[A, B]\nreveal_type(f(x))  # N: Revealed type is \"__main__.Parent\"\nf(x, B())  # E: Argument 1 to \"f\" has incompatible type \"Union[A, B]\"; expected \"B\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadInferUnionWithMixOfPositionalAndOptionalArgs]\nfrom typing import overload, Union, Optional\n\nclass A: ...\nclass B: ...\n\n@overload\ndef f(x: A) -> int: ...\n@overload\ndef f(x: Optional[B] = None) -> str: ...\ndef f(*args): ...\n\nx: Union[A, B]\ny: Optional[A]\nz: Union[A, Optional[B]]\nreveal_type(f(x))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(f(y))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(f(z))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(f())   # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadingInferUnionReturnWithTypevarWithValueRestriction]\nfrom typing import overload, Union, TypeVar, Generic\n\nclass A: pass\nclass B: pass\nclass C: pass\n\nT = TypeVar('T', B, C)\n\nclass Wrapper(Generic[T]):\n    @overload\n    def f(self, x: T) -> B: ...\n\n    @overload\n    def f(self, x: A) -> C: ...\n\n    def f(self, x): ...\n\nobj: Wrapper[B] = Wrapper()\nx: Union[A, B]\n\nreveal_type(obj.f(A()))  # N: Revealed type is \"__main__.C\"\nreveal_type(obj.f(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(obj.f(x))    # N: Revealed type is \"Union[__main__.C, __main__.B]\"\n\n[case testOverloadingInferUnionReturnWithFunctionTypevarReturn]\nfrom typing import overload, Union, TypeVar, Generic\n\nT = TypeVar('T')\n\nclass W1(Generic[T]): pass\nclass W2(Generic[T]): pass\nclass A: pass\nclass B: pass\n\n@overload\ndef foo(x: W1[T]) -> T: ...\n@overload\ndef foo(x: W2[T]) -> T: ...\ndef foo(x): ...\n\ndef bar(x: Union[W1[T], W2[T]]) -> T: ...\n\ndef wrapper() -> None:\n    obj1: Union[W1[A], W2[A]]\n\n    a1: A = foo(obj1)\n    a2 = foo(obj1)\n    reveal_type(a1)  # N: Revealed type is \"__main__.A\"\n    reveal_type(a2)  # N: Revealed type is \"__main__.A\"\n\n    obj2: Union[W1[A], W2[B]]\n\n    reveal_type(foo(obj2))  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n    bar(obj2)  # E: Cannot infer type argument 1 of \"bar\"\n\n    b1_overload: A = foo(obj2)  # E: Incompatible types in assignment (expression has type \"Union[A, B]\", variable has type \"A\")\n    b1_union: A    = bar(obj2)  # E: Cannot infer type argument 1 of \"bar\"\n\n[case testOverloadingInferUnionReturnWithObjectTypevarReturn]\nfrom typing import overload, Union, TypeVar, Generic\n\nT = TypeVar('T')\n\nclass W1(Generic[T]): pass\nclass W2(Generic[T]): pass\nclass A: pass\nclass B: pass\n\nclass SomeType(Generic[T]):\n    @overload\n    def foo(self, x: W1[T]) -> T: ...\n    @overload\n    def foo(self, x: W2[T]) -> T: ...\n    def foo(self, x): ...\n\n    def bar(self, x: Union[W1[T], W2[T]]) -> T: ...\n\ndef wrapper() -> None:\n    obj1: Union[W1[A], W2[A]]\n\n    a1 = SomeType[A]().foo(obj1)\n    reveal_type(a1)  # N: Revealed type is \"__main__.A\"\n\n    # Note: These should be fine, but mypy has an unrelated bug\n    #       that makes them error out?\n    a2_overload: A = SomeType().foo(obj1)  # E: Argument 1 to \"foo\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[A]]\"; expected \"W1[Never]\"\n    a2_union: A    = SomeType().bar(obj1)  # E: Argument 1 to \"bar\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[A]]\"; expected \"Union[W1[Never], W2[Never]]\"\n\n    SomeType().foo(obj1)  # E: Argument 1 to \"foo\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[A]]\"; expected \"W1[Never]\"\n    SomeType().bar(obj1)  # E: Argument 1 to \"bar\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[A]]\"; expected \"Union[W1[Never], W2[Never]]\"\n\n[case testOverloadingInferUnionReturnWithBadObjectTypevarReturn]\nfrom typing import overload, Union, TypeVar, Generic\n\nT = TypeVar('T')\n\nclass W1(Generic[T]): pass\nclass W2(Generic[T]): pass\nclass A: pass\nclass B: pass\n\nclass SomeType(Generic[T]):\n    @overload\n    def foo(self, x: W1[T]) -> T: ...\n    @overload\n    def foo(self, x: W2[T]) -> T: ...\n    def foo(self, x): ...\n\n    def bar(self, x: Union[W1[T], W2[T]]) -> T: ...\n\ndef wrapper(mysterious: T) -> T:\n    obj1: Union[W1[A], W2[B]]\n\n    SomeType().foo(obj1)  # E: Argument 1 to \"foo\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[B]]\"; expected \"W1[Never]\"\n    SomeType().bar(obj1)  # E: Argument 1 to \"bar\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[B]]\"; expected \"Union[W1[Never], W2[Never]]\"\n\n    SomeType[A]().foo(obj1)  # E: Argument 1 to \"foo\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[B]]\"; expected \"W1[A]\"\n    SomeType[A]().bar(obj1)  # E: Argument 1 to \"bar\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[B]]\"; expected \"Union[W1[A], W2[A]]\"\n\n    SomeType[T]().foo(obj1)  # E: Argument 1 to \"foo\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[B]]\"; expected \"W1[T]\"\n    SomeType[T]().bar(obj1)  # E: Argument 1 to \"bar\" of \"SomeType\" has incompatible type \"Union[W1[A], W2[B]]\"; expected \"Union[W1[T], W2[T]]\"\n\n    return mysterious\n\n[case testOverloadingInferUnionReturnWithMixedTypevars]\nfrom typing import overload, Generic, TypeVar, List, Tuple, Union\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\n\nT = TypeVar('T', bound=A)\nS = TypeVar('S')\n\nclass Dummy(Generic[T]):\n    @overload\n    def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...\n    @overload\n    def foo(self, x: List[S], y: S) -> S: ...\n    def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...\n\nT1 = TypeVar('T1', bound=A)\n\ndef t_is_same_bound(arg1: T1, arg2: S) -> Tuple[T1, S]:\n    x1: Union[List[S], List[Tuple[T1, S]]]\n    y1: S\n    reveal_type(Dummy[T1]().foo(x1, y1))  # N: Revealed type is \"Union[S`-2, T1`-1]\"\n\n    x2: Union[List[T1], List[Tuple[T1, T1]]]\n    y2: T1\n    reveal_type(Dummy[T1]().foo(x2, y2))  # N: Revealed type is \"T1`-1\"\n\n    return arg1, arg2\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadingInferUnionReturnWithMixedTypevarsInnerMismatch]\nfrom typing import overload, Generic, TypeVar, List, Tuple, Union\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\n\nT = TypeVar('T', bound=A)\nS = TypeVar('S')\n\nclass Dummy(Generic[T]):\n    @overload\n    def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...\n    @overload\n    def foo(self, x: List[S], y: S) -> S: ...\n    def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...\n\nT1 = TypeVar('T1', bound=A)\n\ndef t_is_same_bound(arg1: T1, arg2: S) -> Tuple[T1, S]:\n    # The arguments in the tuple are swapped\n    x3: Union[List[S], List[Tuple[S, T1]]]\n    y3: S\n    Dummy[T1]().foo(x3, y3)  # E: Cannot infer type argument 1 of \"foo\" of \"Dummy\" \\\n                             # E: Argument 1 to \"foo\" of \"Dummy\" has incompatible type \"Union[List[S], List[Tuple[S, T1]]]\"; expected \"List[Tuple[T1, Any]]\"\n\n    x4: Union[List[int], List[Tuple[C, int]]]\n    y4: int\n    reveal_type(Dummy[C]().foo(x4, y4))  # N: Revealed type is \"Union[builtins.int, __main__.C]\"\n    Dummy[A]().foo(x4, y4)               # E: Argument 1 to \"foo\" of \"Dummy\" has incompatible type \"Union[List[int], List[Tuple[C, int]]]\"; expected \"List[Tuple[A, int]]\"\n\n    return arg1, arg2\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadingInferUnionReturnWithMixedTypevarsTighterBound]\nfrom typing import overload, Generic, TypeVar, List, Tuple, Union\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\n\nT = TypeVar('T', bound=A)\nS = TypeVar('S')\n\nclass Dummy(Generic[T]):\n    @overload\n    def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...\n    @overload\n    def foo(self, x: List[S], y: S) -> S: ...\n    def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...\n\nT1 = TypeVar('T1', bound=B)\n\ndef t_is_tighter_bound(arg1: T1, arg2: S) -> Tuple[T1, S]:\n    x1: Union[List[S], List[Tuple[T1, S]]]\n    y1: S\n    reveal_type(Dummy[T1]().foo(x1, y1))  # N: Revealed type is \"Union[S`-2, T1`-1]\"\n\n    x2: Union[List[T1], List[Tuple[T1, T1]]]\n    y2: T1\n    reveal_type(Dummy[T1]().foo(x2, y2))  # N: Revealed type is \"T1`-1\"\n\n    return arg1, arg2\n\n[builtins fixtures/list.pyi]\n\n[case testOverloadingInferUnionReturnWithTypevarsAndValueRestrictions]\nfrom typing import overload, Generic, TypeVar, List, Tuple, Union\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\n\nT = TypeVar('T', bound=A)\nS = TypeVar('S')\n\nclass Dummy(Generic[T]):\n    @overload\n    def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...\n    @overload\n    def foo(self, x: List[S], y: S) -> S: ...\n    def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...\n\nT3 = TypeVar('T3', B, C)\n\ndef t_is_compatible_bound(arg1: T3, arg2: S) -> Tuple[T3, S]:\n    x1: Union[List[S], List[Tuple[T3, S]]]\n    y1: S\n    reveal_type(Dummy[T3]().foo(x1, y1))\n\n    x2: Union[List[T3], List[Tuple[T3, T3]]]\n    y2: T3\n    reveal_type(Dummy[T3]().foo(x2, y2))\n\n    return arg1, arg2\n\n[builtins fixtures/list.pyi]\n[out]\nmain:22: note: Revealed type is \"Union[S`-2, __main__.B]\"\nmain:22: note: Revealed type is \"Union[S`-2, __main__.C]\"\nmain:26: note: Revealed type is \"__main__.B\"\nmain:26: note: Revealed type is \"__main__.C\"\n\n[case testOverloadInferUnionReturnWithInconsistentTypevarNames]\nfrom typing import overload, TypeVar, Union\n\nT = TypeVar('T')\nS = TypeVar('S')\n\n@overload\ndef consistent(x: T, y: str) -> T: ...\n@overload\ndef consistent(x: T, y: int) -> T: ...\ndef consistent(x: T, y: Union[str, int]) -> T:\n    return x\n\n@overload\ndef inconsistent(x: T, y: str) -> T: ...\n@overload\ndef inconsistent(x: S, y: int) -> S: ...\ndef inconsistent(x: T, y: Union[str, int]) -> T:\n    return x\n\ndef test(x: T) -> T:\n    y: Union[str, int]\n\n    reveal_type(consistent(x, y))  # N: Revealed type is \"T`-1\"\n\n    # On one hand, this overload is defined in a weird way; on the other, there's technically nothing wrong with it.\n    inconsistent(x, y)\n\n    return x\n\n[case testOverloadsAndNoneWithoutStrictOptional]\n# flags: --no-strict-optional\nfrom typing import overload, Optional\n\n@overload\ndef f(x: None) -> int: ...\n@overload\ndef f(x: object) -> str: ...\ndef f(x): ...\n\n# We pretend strict-optional is enabled for overload definitions,\n# even in non-strict optional mode\n@overload\ndef g(x: None) -> int: ...\n@overload\ndef g(x: int) -> str: ...\ndef g(x): ...\n\n# Calls are still checked normally though\na: None\nb: int\nc: Optional[int]\nreveal_type(g(a))  # N: Revealed type is \"builtins.int\"\nreveal_type(g(b))  # N: Revealed type is \"builtins.str\"\nreveal_type(g(c))  # N: Revealed type is \"builtins.str\"\n\n[case testOverloadsAndNoneWithStrictOptional]\nfrom typing import overload, Optional\n\n@overload\ndef f(x: None) -> int: ...\n@overload\ndef f(x: object) -> str: ...\ndef f(x): ...\n\n@overload\ndef g(x: None) -> int: ...\n@overload\ndef g(x: int) -> str: ...\ndef g(x): ...\n\na: None\nb: int\nc: Optional[int]\nreveal_type(g(a))  # N: Revealed type is \"builtins.int\"\nreveal_type(g(b))  # N: Revealed type is \"builtins.str\"\nreveal_type(g(c))  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n\n[case testOverloadsNoneAndTypeVarsWithNoStrictOptional]\n# flags: --no-strict-optional\nfrom typing import Callable, Iterable, TypeVar, overload, Optional\n\nT = TypeVar('T')\nS = TypeVar('S')\n\n@overload\ndef mymap(func: None, seq: Iterable[T]) -> Iterable[T]: ...\n@overload\ndef mymap(func: Callable[[T], S], seq: Iterable[T]) -> Iterable[S]: ...\ndef mymap(*args): ...\n\nseq = [1, 2, 3]\nf1: Callable[[int], str]\nf2: None\nf3: Optional[Callable[[int], str]]\n\nreveal_type(mymap(f1, seq))  # N: Revealed type is \"typing.Iterable[builtins.str]\"\nreveal_type(mymap(f2, seq))  # N: Revealed type is \"typing.Iterable[builtins.int]\"\nreveal_type(mymap(f3, seq))  # N: Revealed type is \"typing.Iterable[builtins.str]\"\n\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsNoneAndTypeVarsWithStrictOptional]\nfrom typing import Callable, Iterable, TypeVar, overload, Optional\n\nT = TypeVar('T')\nS = TypeVar('S')\n\n@overload\ndef mymap(func: None, seq: Iterable[T]) -> Iterable[T]: ...\n@overload\ndef mymap(func: Callable[[T], S], seq: Iterable[T]) -> Iterable[S]: ...\ndef mymap(*args): ...\n\nseq = [1, 2, 3]\nf1: Callable[[int], str]\nf2: None\nf3: Optional[Callable[[int], str]]\n\nreveal_type(mymap(f1, seq))  # N: Revealed type is \"typing.Iterable[builtins.str]\"\nreveal_type(mymap(f2, seq))  # N: Revealed type is \"typing.Iterable[builtins.int]\"\nreveal_type(mymap(f3, seq))  # N: Revealed type is \"Union[typing.Iterable[builtins.str], typing.Iterable[builtins.int]]\"\n\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowTypeNoStrictOptional1]\n# flags: --no-strict-optional\nfrom typing import overload, Union, NoReturn\n\n@overload\ndef narrow_int(x: str) -> NoReturn: ...\n@overload\ndef narrow_int(x: int) -> int: ...\ndef narrow_int(x: Union[int, str]) -> Union[int, NoReturn]:\n    assert isinstance(x, int)\n    return x\n\ndef test_narrow_int() -> None:\n    a: Union[int, str]\n    if int():\n        a = narrow_int(a)\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    b: int\n    if int():\n        b = narrow_int(b)\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    c: str\n    if int():\n        c = narrow_int(c)\n        reveal_type(c)  # Note: branch is now dead, so no type is revealed\n                        # TODO: maybe we should make mypy report a warning instead?\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowTypeWithStrictOptional1]\nfrom typing import overload, Union, NoReturn\n\n@overload\ndef narrow_int(x: str) -> NoReturn: ...\n@overload\ndef narrow_int(x: int) -> int: ...\ndef narrow_int(x: Union[int, str]) -> Union[int, NoReturn]:\n    assert isinstance(x, int)\n    return x\n\ndef test_narrow_int() -> None:\n    a: Union[int, str]\n    if int():\n        a = narrow_int(a)\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    b: int\n    if int():\n        b = narrow_int(b)\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    c: str\n    if int():\n        c = narrow_int(c)\n        reveal_type(c)  # Note: branch is now dead, so no type is revealed\n                        # TODO: maybe we should make mypy report a warning instead?\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowTypeNoStrictOptional2]\n# flags: --no-strict-optional\nfrom typing import overload, Union, TypeVar, NoReturn, Optional\n\nT = TypeVar('T')\n@overload\ndef narrow_none(x: None) -> NoReturn: ...\n@overload\ndef narrow_none(x: T) -> T: ...\ndef narrow_none(x: Optional[T]) -> Union[NoReturn, T]:\n    assert x is not None\n    return x\n\ndef test_narrow_none() -> None:\n    a: Optional[int]\n    if int():\n        a = narrow_none(a)\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    b: int\n    if int():\n        b = narrow_none(b)\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    c: None\n    if int():\n        c = narrow_none(c)\n        reveal_type(c)  # Note: branch is now dead, so no type is revealed\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowTypeWithStrictOptional2]\nfrom typing import overload, Union, TypeVar, NoReturn, Optional\n\nT = TypeVar('T')\n@overload\ndef narrow_none(x: None) -> NoReturn: ...\n@overload\ndef narrow_none(x: T) -> T: ...\ndef narrow_none(x: Optional[T]) -> Union[NoReturn, T]:\n    assert x is not None\n    return x\n\ndef test_narrow_none() -> None:\n    a: Optional[int]\n    if int():\n        a = narrow_none(a)\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    b: int\n    if int():\n        b = narrow_none(b)\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    c: None\n    if int():\n        c = narrow_none(c)\n        reveal_type(c)  # Branch is now dead\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n\n[case testOverloadsAndNoReturnNarrowTypeNoStrictOptional3]\n# flags: --no-strict-optional\nfrom typing import overload, TypeVar, NoReturn, Optional\n\n@overload\ndef narrow_none_v2(x: None) -> NoReturn: ...\n@overload\ndef narrow_none_v2(x: T) -> T: ...\ndef narrow_none_v2(x: Optional[T]) -> T:\n    assert x is not None\n    return x\n\ndef test_narrow_none_v2() -> None:\n    a: Optional[int]\n    if int():\n        a = narrow_none_v2(a)\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    b: int\n    if int():\n        b = narrow_none_v2(b)\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    c: None\n    if int():\n        c = narrow_none_v2(c)\n        reveal_type(c)  # Note: branch is now dead, so no type is revealed\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowTypeWithStrictOptional3]\nfrom typing import overload, TypeVar, NoReturn, Optional\n\n@overload\ndef narrow_none_v2(x: None) -> NoReturn: ...\n@overload\ndef narrow_none_v2(x: T) -> T: ...\ndef narrow_none_v2(x: Optional[T]) -> T:\n    assert x is not None\n    return x\n\ndef test_narrow_none_v2() -> None:\n    a: Optional[int]\n    if int():\n        a = narrow_none_v2(a)\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    b: int\n    if int():\n        b = narrow_none_v2(b)\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    c: None\n    if int():\n        c = narrow_none_v2(c)\n        reveal_type(c)  # Note: branch is now dead, so no type is revealed\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowWhenBlacklistingSubtype]\nfrom typing import TypeVar, NoReturn, Union, overload\n\nclass Parent: ...\nclass A(Parent): ...\nclass B(Parent): ...\nT = TypeVar('T', bound=Parent)\n\n@overload\ndef narrow_to_not_a(x: A) -> NoReturn: ...\n@overload\ndef narrow_to_not_a(x: T) -> T: ...\ndef narrow_to_not_a(x: T) -> Union[NoReturn, T]:\n    assert not isinstance(x, A)\n    return x\n\ndef test() -> None:\n    val: Union[A, B]\n    if int():\n        val = narrow_to_not_a(val)\n        reveal_type(val)   # N: Revealed type is \"__main__.B\"\n\n    val2: A\n    if int():\n        val2 = narrow_to_not_a(val2)\n        reveal_type(val2)  # Branch now dead\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsAndNoReturnNarrowWhenBlacklistingSubtype2]\nfrom typing import TypeVar, NoReturn, Union, overload\n\nclass Parent: ...\nclass A(Parent): ...\nclass B(Parent): ...\nT = TypeVar('T', bound=Parent)\n\n@overload\ndef narrow_to_not_a_v2(x: A) -> NoReturn: ...\n@overload\ndef narrow_to_not_a_v2(x: T) -> T: ...\ndef narrow_to_not_a_v2(x: T) -> T:\n    assert not isinstance(x, A)\n    return x\n\ndef test_v2(val: Union[A, B], val2: A) -> None:\n    if int():\n        val = narrow_to_not_a_v2(val)\n        reveal_type(val)   # N: Revealed type is \"__main__.B\"\n\n    if int():\n        val2 = narrow_to_not_a_v2(val2)\n        reveal_type(val2)  # Branch now dead\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadWithNonGenericDescriptor]\nfrom typing import overload, Any, Optional, Union\n\nclass NumberAttribute:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> 'NumberAttribute': ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> int: ...\n    def __get__(self, instance: Optional[object], owner: Any) -> Union['NumberAttribute', int]:\n        if instance is None:\n            return self\n        else:\n            return 3\n\n    def foo(self) -> str: ...\n\nclass MyModel:\n    my_number = NumberAttribute()\n\nreveal_type(MyModel().my_number)  # N: Revealed type is \"builtins.int\"\nMyModel().my_number.foo()         # E: \"int\" has no attribute \"foo\"\n\nreveal_type(MyModel.my_number)        # N: Revealed type is \"__main__.NumberAttribute\"\nreveal_type(MyModel.my_number.foo())  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadWithNonGenericDescriptorLookalike]\nfrom typing import overload, Any, Optional, Union\n\nclass FakeAttribute:\n    @overload\n    def dummy(self, instance: None, owner: Any) -> 'FakeAttribute': ...\n    @overload\n    def dummy(self, instance: object, owner: Any) -> int: ...\n    def dummy(self, instance: Optional[object], owner: Any) -> Union['FakeAttribute', int]: ...\n\n[case testOverloadWithGenericDescriptor]\nfrom typing import overload, Any, Optional, TypeVar, Type, Union, Generic\n\nT = TypeVar('T')\n\nclass NumberAttribute(Generic[T]):\n    @overload\n    def __get__(self, instance: None, owner: Type[T]) -> 'NumberAttribute[T]': ...\n    @overload\n    def __get__(self, instance: T, owner: Type[T]) -> int: ...\n    def __get__(self, instance: Optional[T], owner: Type[T]) -> Union['NumberAttribute[T]', int]:\n        if instance is None:\n            return self\n        else:\n            return 3\n\n    def foo(self) -> str: ...\n\nclass MyModel:\n    my_number = NumberAttribute[MyModel]()\n\nreveal_type(MyModel().my_number)  # N: Revealed type is \"builtins.int\"\nMyModel().my_number.foo()         # E: \"int\" has no attribute \"foo\"\n\nreveal_type(MyModel.my_number)        # N: Revealed type is \"__main__.NumberAttribute[__main__.MyModel]\"\nreveal_type(MyModel.my_number.foo())  # N: Revealed type is \"builtins.str\"\n\nreveal_type(NumberAttribute[MyModel]().__get__(None, MyModel))  # N: Revealed type is \"__main__.NumberAttribute[__main__.MyModel]\"\nreveal_type(NumberAttribute[str]().__get__(None, str))      # N: Revealed type is \"__main__.NumberAttribute[builtins.str]\"\n\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadWithGenericDescriptorLookalike]\nfrom typing import overload, Any, Optional, TypeVar, Type, Union, Generic\n\nT = TypeVar('T')\n\nclass FakeAttribute(Generic[T]):\n    @overload\n    def dummy(self, instance: None, owner: Type[T]) -> 'FakeAttribute[T]': ...\n    @overload\n    def dummy(self, instance: T, owner: Type[T]) -> int: ...\n    def dummy(self, instance: Optional[T], owner: Type[T]) -> Union['FakeAttribute[T]', int]: ...\n\n[case testOverloadWithClassMethods]\nfrom typing import overload\n\nclass Wrapper:\n    @overload\n    @classmethod\n    def foo(cls, x: int) -> int: ...\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n    @classmethod\n    def foo(cls, x): pass\n\nreveal_type(Wrapper.foo(3))      # N: Revealed type is \"builtins.int\"\nreveal_type(Wrapper.foo(\"foo\"))  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testOverloadWithInconsistentClassMethods]\nfrom typing import overload\n\nclass Wrapper1:\n    @overload   # E: Overload does not consistently use the \"@classmethod\" decorator on all function signatures.\n    @classmethod\n    def foo(cls, x: int) -> int: ...\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n    def foo(cls, x): pass\n\nclass Wrapper2:\n    @overload   # E: Overload does not consistently use the \"@classmethod\" decorator on all function signatures.\n    @classmethod\n    def foo(cls, x: int) -> int: ...\n    @overload\n    def foo(cls, x: str) -> str: ...\n    @classmethod\n    def foo(cls, x): pass\n\nclass Wrapper3:\n    @overload   # E: Overload does not consistently use the \"@classmethod\" decorator on all function signatures.\n    def foo(cls, x: int) -> int: ...\n    @overload\n    def foo(cls, x: str) -> str: ...\n    @classmethod\n    def foo(cls, x): pass\n\n[builtins fixtures/classmethod.pyi]\n\n[case testOverloadWithSwappedDecorators]\nfrom typing import overload\n\nclass Wrapper1:\n    @classmethod\n    @overload\n    def foo(cls, x: int) -> int: ...\n\n    @classmethod\n    @overload\n    def foo(cls, x: str) -> str: ...\n\n    @classmethod\n    def foo(cls, x): pass\n\nclass Wrapper2:\n    @classmethod\n    @overload\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): pass\n\nclass Wrapper3:\n    @classmethod   # E: Overload does not consistently use the \"@classmethod\" decorator on all function signatures.\n    @overload\n    def foo(cls, x: int) -> int: ...\n\n    @overload\n    def foo(cls, x: str) -> str: ...\n\n    def foo(cls, x): pass\n\nreveal_type(Wrapper1.foo(3))  # N: Revealed type is \"builtins.int\"\nreveal_type(Wrapper2.foo(3))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testOverloadFaultyClassMethodInheritance]\nfrom typing import overload\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\nclass Parent:\n    @overload\n    @classmethod\n    def foo(cls, x: B) -> int: ...\n\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n\n    @classmethod\n    def foo(cls, x): pass\n\nclass BadChild(Parent):\n    @overload                           # Fail\n    @classmethod\n    def foo(cls, x: C) -> int: ...\n\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n\n    @classmethod\n    def foo(cls, x): pass\n\nclass GoodChild(Parent):\n    @overload\n    @classmethod\n    def foo(cls, x: A) -> int: ...\n\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n\n    @classmethod\n    def foo(cls, x): pass\n\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:20: error: Signature of \"foo\" incompatible with supertype \"Parent\"\nmain:20: note:      Superclass:\nmain:20: note:          @overload\nmain:20: note:          @classmethod\nmain:20: note:          def foo(cls, x: B) -> int\nmain:20: note:          @overload\nmain:20: note:          @classmethod\nmain:20: note:          def foo(cls, x: str) -> str\nmain:20: note:      Subclass:\nmain:20: note:          @overload\nmain:20: note:          @classmethod\nmain:20: note:          def foo(cls, x: C) -> int\nmain:20: note:          @overload\nmain:20: note:          @classmethod\nmain:20: note:          def foo(cls, x: str) -> str\n\n[case testOverloadClassMethodMixingInheritance]\nfrom typing import overload\n\nclass BadParent:\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): pass\n\nclass BadChild(BadParent):\n    @overload                           # Fail\n    def foo(cls, x: int) -> int: ...\n\n    @overload\n    def foo(cls, x: str) -> str: ...\n\n    def foo(cls, x): pass\n\nclass GoodParent:\n    @overload\n    def foo(cls, x: int) -> int: ...\n\n    @overload\n    def foo(cls, x: str) -> str: ...\n\n    def foo(cls, x): pass\n\nclass GoodChild(GoodParent):\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): pass\n\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:16: error: Signature of \"foo\" incompatible with supertype \"BadParent\"\nmain:16: note:      Superclass:\nmain:16: note:          @overload\nmain:16: note:          @classmethod\nmain:16: note:          def foo(cls, x: int) -> int\nmain:16: note:          @overload\nmain:16: note:          @classmethod\nmain:16: note:          def foo(cls, x: str) -> str\nmain:16: note:      Subclass:\nmain:16: note:          @overload\nmain:16: note:          def foo(cls, x: int) -> int\nmain:16: note:          @overload\nmain:16: note:          def foo(cls, x: str) -> str\n\n[case testOverloadClassMethodImplementation]\nfrom typing import overload, Union\n\nclass Wrapper:\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    # E: Overloaded function implementation cannot produce return type of signature 1\n    def foo(cls, x: Union[int, str]) -> str:\n        reveal_type(cls)          # N: Revealed type is \"Type[__main__.Wrapper]\"\n        reveal_type(cls.other())  # N: Revealed type is \"builtins.str\"\n        return \"...\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testOverloadWithStaticMethods]\nfrom typing import overload\n\nclass Wrapper:\n    @overload\n    @staticmethod\n    def foo(x: int) -> int: ...\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n    @staticmethod\n    def foo(x): pass\n\nreveal_type(Wrapper.foo(3))      # N: Revealed type is \"builtins.int\"\nreveal_type(Wrapper.foo(\"foo\"))  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/staticmethod.pyi]\n\n[case testOverloadWithInconsistentStaticMethods]\nfrom typing import overload, Union\n\nclass Wrapper1:\n    @overload   # E: Overload does not consistently use the \"@staticmethod\" decorator on all function signatures.\n    @staticmethod\n    def foo(x: int) -> int: ...\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n    def foo(x): pass\n\nclass Wrapper2:\n    @overload   # E: Overload does not consistently use the \"@staticmethod\" decorator on all function signatures.\n    @staticmethod\n    def foo(x: int) -> int: ...\n    @overload\n    def foo(x: str) -> str: ...  # E: Self argument missing for a non-static method (or an invalid type for self)\n    @staticmethod\n    def foo(x): pass\n\nclass Wrapper3:\n    @overload   # E: Overload does not consistently use the \"@staticmethod\" decorator on all function signatures.\n    @staticmethod\n    def foo(x: int) -> int: ...\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n    def foo(x: Union[int, str]): pass  # E: Self argument missing for a non-static method (or an invalid type for self)\n[builtins fixtures/staticmethod.pyi]\n\n[case testOverloadWithSwappedDecorators2]\nfrom typing import overload\n\nclass Wrapper1:\n    @staticmethod\n    @overload\n    def foo(x: int) -> int: ...\n\n    @staticmethod\n    @overload\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\nclass Wrapper2:\n    @staticmethod\n    @overload\n    def foo(x: int) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\nclass Wrapper3:\n    @staticmethod   # E: Overload does not consistently use the \"@staticmethod\" decorator on all function signatures.\n    @overload\n    def foo(x: int) -> int: ...\n\n    @overload\n    def foo(x: str) -> str: ...  # E: Self argument missing for a non-static method (or an invalid type for self)\n\n    @staticmethod\n    def foo(x): pass\n\nreveal_type(Wrapper1.foo(3))  # N: Revealed type is \"builtins.int\"\nreveal_type(Wrapper2.foo(3))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/staticmethod.pyi]\n\n[case testOverloadFaultyStaticMethodInheritance]\nfrom typing import overload\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\nclass Parent:\n    @overload\n    @staticmethod\n    def foo(x: B) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\nclass BadChild(Parent):\n    @overload                       # Fail\n    @staticmethod\n    def foo(x: C) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\nclass GoodChild(Parent):\n    @overload\n    @staticmethod\n    def foo(x: A) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\n[builtins fixtures/staticmethod.pyi]\n[out]\nmain:20: error: Signature of \"foo\" incompatible with supertype \"Parent\"\nmain:20: note:      Superclass:\nmain:20: note:          @overload\nmain:20: note:          @staticmethod\nmain:20: note:          def foo(x: B) -> int\nmain:20: note:          @overload\nmain:20: note:          @staticmethod\nmain:20: note:          def foo(x: str) -> str\nmain:20: note:      Subclass:\nmain:20: note:          @overload\nmain:20: note:          @staticmethod\nmain:20: note:          def foo(x: C) -> int\nmain:20: note:          @overload\nmain:20: note:          @staticmethod\nmain:20: note:          def foo(x: str) -> str\n\n[case testOverloadStaticMethodMixingInheritance]\nfrom typing import overload\n\nclass BadParent:\n    @overload\n    @staticmethod\n    def foo(x: int) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\nclass BadChild(BadParent):\n    @overload                            # Fail\n    def foo(self, x: int) -> int: ...\n\n    @overload\n    def foo(self, x: str) -> str: ...\n\n    def foo(self, x): pass\n\nclass GoodParent:\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): pass\n\nclass GoodChild(GoodParent):\n    @overload\n    @staticmethod\n    def foo(x: int) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod\n    def foo(x): pass\n\n[builtins fixtures/staticmethod.pyi]\n[out]\nmain:16: error: Signature of \"foo\" incompatible with supertype \"BadParent\"\nmain:16: note:      Superclass:\nmain:16: note:          @overload\nmain:16: note:          @staticmethod\nmain:16: note:          def foo(x: int) -> int\nmain:16: note:          @overload\nmain:16: note:          @staticmethod\nmain:16: note:          def foo(x: str) -> str\nmain:16: note:      Subclass:\nmain:16: note:          @overload\nmain:16: note:          def foo(self, x: int) -> int\nmain:16: note:          @overload\nmain:16: note:          def foo(self, x: str) -> str\n\n[case testOverloadStaticMethodImplementation]\nfrom typing import overload, Union\n\nclass Wrapper:\n    @staticmethod\n    def other() -> str:\n        return \"...\"\n\n    @overload\n    @staticmethod\n    def foo(x: int) -> int: ...\n\n    @overload\n    @staticmethod\n    def foo(x: str) -> str: ...\n\n    @staticmethod    # E: Overloaded function implementation cannot produce return type of signature 1\n    def foo(x: Union[int, str]) -> str:\n        return 3  # E: Incompatible return value type (got \"int\", expected \"str\")\n\n[builtins fixtures/staticmethod.pyi]\n\n[case testUnionMathOverloadingReturnsBestType]\nfrom typing import Union, overload\n\n@overload\ndef f(x: Union[int, str]) -> int: ...\n@overload\ndef f(x: object) -> object: ...\ndef f(x):\n    pass\n\nx: Union[int, str]\nreveal_type(f(x))  # N: Revealed type is \"builtins.int\"\n[out]\n\n[case testOverloadAndSelfTypes]\nfrom typing import overload, Union, TypeVar, Type\n\nT = TypeVar('T', bound='Parent')\nclass Parent:\n    @overload\n    def foo(self: T, x: int) -> T: pass\n\n    @overload\n    def foo(self, x: str) -> str: pass\n\n    def foo(self: T, x: Union[int, str]) -> Union[T, str]:\n        reveal_type(self.bar())    # N: Revealed type is \"builtins.str\"\n        return self\n\n    def bar(self) -> str: pass\n\nclass Child(Parent):\n    def child_only(self) -> int: pass\n\nx: Union[int, str]\nreveal_type(Parent().foo(3))                  # N: Revealed type is \"__main__.Parent\"\nreveal_type(Child().foo(3))                   # N: Revealed type is \"__main__.Child\"\nreveal_type(Child().foo(\"...\"))               # N: Revealed type is \"builtins.str\"\nreveal_type(Child().foo(x))                   # N: Revealed type is \"Union[__main__.Child, builtins.str]\"\nreveal_type(Child().foo(3).child_only())      # N: Revealed type is \"builtins.int\"\n\n[case testOverloadAndSelfTypesGenericNoOverlap]\nfrom typing import Generic, TypeVar, Any, overload, Self, Union\n\nT = TypeVar(\"T\")\nclass C(Generic[T]):\n    @overload\n    def get(self, obj: None) -> Self: ...\n    @overload\n    def get(self, obj: Any) -> T: ...\n    def get(self, obj: Union[Any, None]) -> Union[T, Self]:\n        return self\n\nclass D(C[int]): ...\nd: D\nreveal_type(d.get(None))  # N: Revealed type is \"__main__.D\"\nreveal_type(d.get(\"whatever\"))  # N: Revealed type is \"builtins.int\"\n\n[case testOverloadAndClassTypes]\nfrom typing import overload, Union, TypeVar, Type\n\nT = TypeVar('T', bound='Parent')\nclass Parent:\n    @overload\n    @classmethod\n    def foo(cls: Type[T], x: int) -> Type[T]: pass\n\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: pass\n\n    @classmethod\n    def foo(cls: Type[T], x: Union[int, str]) -> Union[Type[T], str]:\n        reveal_type(cls.bar())    # N: Revealed type is \"builtins.str\"\n        return cls\n\n    @classmethod\n    def bar(cls) -> str: pass\n\nclass Child(Parent):\n    def child_only(self) -> int: pass\n\nx: Union[int, str]\nreveal_type(Parent.foo(3))                  # N: Revealed type is \"Type[__main__.Parent]\"\nreveal_type(Child.foo(3))                   # N: Revealed type is \"Type[__main__.Child]\"\nreveal_type(Child.foo(\"...\"))               # N: Revealed type is \"builtins.str\"\nreveal_type(Child.foo(x))                   # N: Revealed type is \"Union[Type[__main__.Child], builtins.str]\"\nreveal_type(Child.foo(3)().child_only())    # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testOptionalIsNotAUnionIfNoStrictOverload]\n# flags: --no-strict-optional\nfrom typing import Optional, overload\n\nclass B: pass\nclass C(B): pass\n\n@overload\ndef rp(x: C) -> C: ...\n@overload\ndef rp(x: B) -> B: ...\ndef rp(x):\n    pass\n\nx: Optional[C]\nreveal_type(rp(x))  # N: Revealed type is \"__main__.C\"\n[out]\n\n[case testUnionMathTrickyOverload1]\nfrom typing import Union, overload\n\n@overload\ndef f(x: int, y: int) -> int: ...\n@overload\ndef f(x: object, y: str) -> str: ...\ndef f(x):\n    pass\n\nx: Union[int, str]\ny: Union[int, str]\nf(x, y)\n[out]\nmain:12: error: Argument 1 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:12: error: Argument 2 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\n\n[case testUnionMathTrickyOverload2]\nfrom typing import overload, Union, Any\n\nclass C:\n    def f(self, other: C) -> C: ...\n\nclass D(C):\n    @overload\n    def f(self, other: D) -> D: ...\n    @overload\n    def f(self, other: C) -> C: ...\n    def f(self, other): ...\n\nx: D\ny: Union[D, Any]\nreveal_type(x.f(y))  # N: Revealed type is \"Union[__main__.D, Any]\"\n[out]\n\n[case testManyUnionsInOverload]\nfrom typing import overload, TypeVar, Union\n\nT = TypeVar('T')\n\n@overload\ndef f(x: int, y: object, z: object, t: object, u: object, w: object, v: object, s: object) -> int: ...\n@overload\ndef f(x: str, y: object, z: object, t: object, u: object, w: object, v: object, s: object) -> str: ...\n@overload\ndef f(x: T, y: object, z: object, t: object, u: object, w: object, v: object, s: object) -> T: ...\ndef f(*args, **kwargs):\n    pass\n\nclass A: pass\nclass B: pass\nx: Union[int, str, A, B]\ny = f(x, x, x, x, x, x, x, x) # 8 args\n\nreveal_type(y)  # N: Revealed type is \"Union[builtins.int, builtins.str, __main__.A, __main__.B]\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testOverloadsWithNoneComingSecondAreAlwaysFlaggedInNoStrictOptional]\n# flags: --no-strict-optional\nfrom typing import overload\n\n@overload\ndef none_first(x: None) -> None: ...\n@overload\ndef none_first(x: int) -> int: ...\ndef none_first(x: int) -> int:\n    return x\n\n@overload\ndef none_second(x: int) -> int: ...\n@overload\ndef none_second(x: None) -> None: ...  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\ndef none_second(x: int) -> int:\n    return x\n\n[case testOverloadsWithNoneComingSecondIsOkInStrictOptional]\nfrom typing import overload, Optional\n\n@overload\ndef none_first(x: None) -> None: ...\n@overload\ndef none_first(x: int) -> int: ...\ndef none_first(x: Optional[int]) -> Optional[int]:\n    return x\n\n@overload\ndef none_second(x: int) -> int: ...\n@overload\ndef none_second(x: None) -> None: ...\ndef none_second(x: Optional[int]) -> Optional[int]:\n    return x\n\n@overload\ndef none_loose_impl(x: None) -> None: ...\n@overload\ndef none_loose_impl(x: int) -> int: ...\ndef none_loose_impl(x: int) -> int:\n    return x\n[out]\nmain:21: error: Overloaded function implementation does not accept all possible arguments of signature 1\nmain:21: error: Overloaded function implementation cannot produce return type of signature 1\n\n[case testTooManyUnionsException]\nfrom typing import overload, Union\n\n@overload\ndef f(*args: int) -> int: ...\n@overload\ndef f(*args: str) -> str: ...\ndef f(*args):\n    pass\n\nx: Union[int, str]\nf(x, x, x, x, x, x, x, x)\n[builtins fixtures/tuple.pyi]\n[out]\nmain:11: error: Not all union combinations were tried because there are too many unions\nmain:11: error: Argument 1 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 2 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 3 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 4 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 5 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 6 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 7 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\nmain:11: error: Argument 8 to \"f\" has incompatible type \"Union[int, str]\"; expected \"int\"\n\n[case testSafeDunderOverlapInSubclass]\nfrom typing import overload\n\nclass A:\n    def __add__(self, x : 'A') -> 'A': ...\n\nclass B(A):\n    @overload\n    def __add__(self, x : 'B') -> 'B': ...\n    @overload\n    def __add__(self, x : 'A') -> 'A' : ...\n    def __add__(self, x):\n        pass\n[out]\n\n[case testUnsafeDunderOverlapInSubclass]\nfrom typing import overload\n\nclass A:\n    def __add__(self, x : 'A') -> 'A':\n        if isinstance(x, A):\n            return A()\n        else:\n            return NotImplemented\n\n# This is unsafe override because of the problem below\nclass B(A):\n     @overload                                  # Fail\n     def __add__(self, x : 'Other') -> 'B' : ...\n     @overload\n     def __add__(self, x : 'A') -> 'A': ...\n     def __add__(self, x):\n        if isinstance(x, Other):\n            return B()\n        elif isinstance(x, A):\n            return A()\n        else:\n            return NotImplemented\n\nclass Other:\n    def __radd__(self, x: 'A') -> 'Other':\n        if isinstance(x, A):\n            return Other()\n        else:\n            return NotImplemented\n\nactually_b: A  # = B()\nreveal_type(actually_b + Other())               # Note\n# Runtime type is B, this is why we report the error on overriding.\n[builtins fixtures/isinstance.pyi]\n[out]\nmain:12: error: Signature of \"__add__\" incompatible with supertype \"A\"\nmain:12: note:      Superclass:\nmain:12: note:          def __add__(self, A, /) -> A\nmain:12: note:      Subclass:\nmain:12: note:          @overload\nmain:12: note:          def __add__(self, Other, /) -> B\nmain:12: note:          @overload\nmain:12: note:          def __add__(self, A, /) -> A\nmain:12: note: Overloaded operator methods can't have wider argument types in overrides\nmain:32: note: Revealed type is \"__main__.Other\"\n\n[case testOverloadErrorMessageManyMatches]\nfrom typing import overload\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\n\n@overload\ndef f(x: A) -> None: ...\n@overload\ndef f(x: B) -> None: ...\n@overload\ndef f(x: C) -> None: ...\n@overload\ndef f(x: D) -> None: ...\n@overload\ndef f(x: int, y: int) -> None: ...\ndef f(*args): pass\n\nf(3)  # E: No overload variant of \"f\" matches argument type \"int\" \\\n      # N: Possible overload variants: \\\n      # N:     def f(x: A) -> None \\\n      # N:     def f(x: B) -> None \\\n      # N:     def f(x: C) -> None \\\n      # N:     def f(x: D) -> None \\\n      # N:     def f(x: int, y: int) -> None\n\n@overload\ndef g(x: A) -> None: ...\n@overload\ndef g(x: B) -> None: ...\n@overload\ndef g(x: C) -> None: ...\ndef g(*args): pass\n\ng(3)  # E: No overload variant of \"g\" matches argument type \"int\" \\\n      # N: Possible overload variants: \\\n      # N:     def g(x: A) -> None \\\n      # N:     def g(x: B) -> None \\\n      # N:     def g(x: C) -> None\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadedInIter]\nfrom lib import f, g\n\nfor fun in [f, g]:\n    reveal_type(fun)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.str, def (x: builtins.str) -> builtins.int)\"\n[file lib.pyi]\nfrom typing import overload\n\n@overload\ndef f(x: int) -> str: ...\n@overload\ndef f(x: str) -> int: ...\n\n@overload\ndef g(x: int) -> str: ...\n@overload\ndef g(x: str) -> int: ...\n\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n\n[case testNestedOverloadsNoCrash]\nfrom typing import overload\n\ndef f() -> None:\n    @overload\n    def g(x: str) -> str: ...\n    @overload\n    def g(x: int) -> int: ...\n    def g(x):\n        pass\n    g(str())\n[out]\n\n[case testNestedOverloadsTypeVar]\nfrom typing import overload, TypeVar\n\nT = TypeVar('T')\n\ndef f() -> None:\n    @overload\n    def g(x: str) -> str: ...\n    @overload\n    def g(x: T, y: int) -> T: ...\n    def g(x):\n        pass\n\n    g(str(), str())  # E: No overload variant of \"g\" matches argument types \"str\", \"str\" \\\n                     # N: Possible overload variants: \\\n                     # N:     def g(x: str) -> str \\\n                     # N:     def [T] g(x: T, y: int) -> T\n    reveal_type(g(str(), int()))  # N: Revealed type is \"builtins.str\"\n[out]\n\n[case testNestedOverloadsTypeVarOverlap]\nfrom typing import overload, TypeVar\n\nT = TypeVar('T')\n\ndef f() -> None:\n    @overload\n    def g(x: str) -> int: ...\n    @overload\n    def g(x: T) -> T: ...\n    def g(x):\n        pass\n[out]\n\n[case testNestedOverloadsMutuallyRecursive]\nfrom typing import overload, TypeVar, Dict, Any\n\nclass C: ...\nT = TypeVar('T')\n\ndef f() -> None:\n    @overload\n    def g() -> None: ...\n    @overload\n    def g(x: T) -> Dict[int, T]: ...\n    def g(*args, **kwargs) -> Any:\n        reveal_type(h(C()))  # N: Revealed type is \"builtins.dict[builtins.str, __main__.C]\"\n        return args\n\n    @overload\n    def h() -> None: ...\n    @overload\n    def h(x: T) -> Dict[str, T]: ...\n    def h(*args, **kwargs) -> Any:\n        reveal_type(g(C()))  # N: Revealed type is \"builtins.dict[builtins.int, __main__.C]\"\n        return args\n\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testOverloadConstrainedTypevarNotShadowingAny]\nfrom lib import attr\nfrom typing import Any\n\nreveal_type(attr(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(attr(\"hi\"))  # N: Revealed type is \"builtins.int\"\nx: Any\nreveal_type(attr(x)) # N: Revealed type is \"Any\"\nattr(\"hi\", 1)  # E: No overload variant of \"attr\" matches argument types \"str\", \"int\" \\\n               # N: Possible overload variants: \\\n               # N:     def [T: (int, float)] attr(default: T, blah: int = ...) -> T \\\n               # N:     def attr(default: Any = ...) -> int\n[file lib.pyi]\nfrom typing import overload, Any, TypeVar\n\nT = TypeVar('T', int, float)\n\n@overload\ndef attr(default: T, blah: int = ...) -> T: ...\n@overload\ndef attr(default: Any = ...) -> int: ...\n[out]\n\n[case testOverloadBoundedTypevarNotShadowingAny]\nfrom lib import attr\nfrom typing import Any\n\nreveal_type(attr(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(attr(\"hi\"))  # N: Revealed type is \"builtins.int\"\nx: Any\nreveal_type(attr(x)) # N: Revealed type is \"Any\"\nattr(\"hi\", 1)  # E: No overload variant of \"attr\" matches argument types \"str\", \"int\" \\\n               # N: Possible overload variants: \\\n               # N:     def [T: int] attr(default: T = ..., blah: int = ...) -> T \\\n               # N:     def attr(default: Any = ...) -> int\n[file lib.pyi]\nfrom typing import overload, TypeVar, Any\n\nT = TypeVar('T', bound=int)\n\n@overload\ndef attr(default: T = ..., blah: int = ...) -> T: ...\n@overload\ndef attr(default: Any = ...) -> int: ...\n[out]\n\n[case testAnyIsOKAsFallbackInOverloads]\nimport stub\n[file stub.pyi]\nfrom typing import TypeVar, Any, overload\n\nT = TypeVar('T')\n\n@overload\ndef foo(x: T) -> T: ...\n@overload\ndef foo(x: Any) -> Any: ...\n\n@overload\ndef bar(x: T) -> T: ...\n@overload\ndef bar(x: Any) -> int: ...\n[out]\n\n[case testOverloadsIgnorePromotions]\nfrom typing import overload, List, Union, _promote\n\nclass Parent: pass\nclass Child(Parent): pass\n\nchildren: List[Child]\nparents: List[Parent]\n\n@overload\ndef f(x: Child) -> List[Child]: pass\n@overload\ndef f(x: Parent) -> List[Parent]: pass\ndef f(x: Union[Child, Parent]) -> Union[List[Child], List[Parent]]:\n    if isinstance(x, Child):\n        reveal_type(x)      # N: Revealed type is \"__main__.Child\"\n        return children\n    else:\n        reveal_type(x)      # N: Revealed type is \"__main__.Parent\"\n        return parents\n\nints: List[int]\nfloats: List[float]\n\n@overload\ndef g(x: int) -> List[int]: pass\n@overload\ndef g(x: float) -> List[float]: pass\ndef g(x: Union[int, float]) -> Union[List[int], List[float]]:\n    if isinstance(x, int):\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n        return ints\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.float\"\n        return floats\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadsTypesAndUnions]\nfrom typing import overload, Type, Union\n\nclass A: pass\nclass B: pass\n\n@overload\ndef f(x: Type[A]) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(x: Union[Type[A], Type[B]]) -> str: ...\ndef f(x: Union[Type[A], Type[B]]) -> Union[int, str]:\n    return 1\n\n[case testBadOverloadProbableMatch]\nfrom typing import overload, List, Type\n\nclass Other: pass\n\n@overload\ndef multiple_plausible(x: int) -> int: ...\n@overload\ndef multiple_plausible(x: str) -> str: ...\ndef multiple_plausible(x): pass\n\n\n@overload\ndef single_plausible(x: Type[int]) -> int: ...\n@overload\ndef single_plausible(x: List[str]) -> str: ...\ndef single_plausible(x): pass\n\na = multiple_plausible(Other())  # E: No overload variant of \"multiple_plausible\" matches argument type \"Other\" \\\n                                 # N: Possible overload variants: \\\n                                 # N:     def multiple_plausible(x: int) -> int \\\n                                 # N:     def multiple_plausible(x: str) -> str\nreveal_type(a)                   # N: Revealed type is \"Any\"\n\nb = single_plausible(Other)      # E: Argument 1 to \"single_plausible\" has incompatible type \"Type[Other]\"; expected \"Type[int]\"\nreveal_type(b)                   # N: Revealed type is \"builtins.int\"\n\nc = single_plausible([Other()])  # E: List item 0 has incompatible type \"Other\"; expected \"str\"\nreveal_type(c)                   # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowUntypedDecoratorsOverload]\n# flags: --disallow-untyped-decorators\nfrom typing import Any, Callable, overload, TypeVar\n\nF = TypeVar('F', bound=Callable[..., Any])\n\n@overload\ndef dec(x: F) -> F: ...\n@overload\ndef dec(x: str) -> Callable[[F], F]: ...\ndef dec(x) -> Any:\n    pass\n\n@dec\ndef f(name: str) -> int:\n    return 0\n\n@dec('abc')\ndef g(name: str) -> int:\n    return 0\n\nreveal_type(f)  # N: Revealed type is \"def (name: builtins.str) -> builtins.int\"\nreveal_type(g)  # N: Revealed type is \"def (name: builtins.str) -> builtins.int\"\n\n[case testDisallowUntypedDecoratorsOverloadDunderCall]\n# flags: --disallow-untyped-decorators\nfrom typing import Any, Callable, overload, TypeVar\n\nF = TypeVar('F', bound=Callable[..., Any])\n\nclass Dec:\n    @overload\n    def __call__(self, x: F) -> F: ...\n    @overload\n    def __call__(self, x: str) -> Callable[[F], F]: ...\n    def __call__(self, x) -> Any:\n        pass\n\ndec = Dec()\n\n@dec\ndef f(name: str) -> int:\n    return 0\n\n@dec('abc')\ndef g(name: str) -> int:\n    return 0\n\nreveal_type(f)  # N: Revealed type is \"def (name: builtins.str) -> builtins.int\"\nreveal_type(g)  # N: Revealed type is \"def (name: builtins.str) -> builtins.int\"\n\n[case testOverloadBadArgumentsInferredToAny1]\nfrom typing import Union, Any, overload\n\ndef bar(x: int) -> Union[int, Any]: ...\n\n@overload\ndef foo(x: str) -> None: ...\n@overload\ndef foo(x: int) -> None: ...\ndef foo(x) -> None: pass\n\nfoo(bar('lol'))  # E: Argument 1 to \"bar\" has incompatible type \"str\"; expected \"int\"\n\n[case testOverloadBadArgumentsInferredToAny2]\nfrom typing import Union, Iterable, Tuple, TypeVar, Generic, overload, Any\n\nclass A:\n    def foo(self) -> Iterable[int]: pass\n\ndef bar(x: int) -> Union[A, int]: ...\n\n_T = TypeVar('_T')\n\n@overload\ndef foo() -> None: ...\n@overload\ndef foo(iterable: Iterable[_T]) -> None: ...\ndef foo(iterable = None) -> None: pass\n\nfoo(bar('lol').foo())  # E: Item \"int\" of \"Union[A, int]\" has no attribute \"foo\" \\\n                       # E: Argument 1 to \"bar\" has incompatible type \"str\"; expected \"int\"\n\n\n[case testOverloadInferringArgumentsUsingContext1]\nfrom typing import Optional, List, overload, TypeVar\nT = TypeVar('T')\n\ndef g(x: Optional[T] = None) -> List[T]: ...\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: List[int]) -> List[int]: ...\ndef f(x): pass\n\nreveal_type(f(g()))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadInferringArgumentsUsingContext2-skip]\n# TODO: Overloads only use outer context to infer type variables in a given overload variant,\n# but never use outer context to _choose_ a better overload in ambiguous situations\n# like empty containers or multiple inheritance, instead just always choosing the first one.\n\nfrom typing import Optional, List, overload, TypeVar\nT = TypeVar('T')\n@overload\ndef g(x: List[str]) -> List[str]: ...\n@overload\ndef g(x: List[int]) -> List[int]: ...\ndef g(x):\n    pass\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: List[int]) -> List[int]: ...\ndef f(x):\n    pass\n\nreveal_type(f(g([])))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testOverloadDeferredNode]\nfrom typing import Callable, TypeVar, Generic, Any, overload\n\n_S = TypeVar('_S')\n_T = TypeVar('_T')\n_R = TypeVar('_R')\n\n@overload\ndef partial(__func: Callable[[_T], _S], __arg: _T) -> Callable[[], _S]: ...\n@overload\ndef partial(__func: Callable[[_T, _S], _S], __arg: _T) -> Callable[[_S], _R]: ...\ndef partial(*args: Any) -> Any:\n    pass\n\ndef f(f: Callable[[int], int]) -> None:\n    pass\n\ndef dec(f: Callable[[_S, _T], _R]) -> Callable[[_S, _T], _R]: pass\n\ndef asdf() -> None:\n    f(partial(lol, 0))\n\n@dec\ndef lol(x: int, y: int) -> int:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testVeryBrokenOverload]\nimport lib\nreveal_type(lib.func)\n[file lib.pyi]\n@overload\ndef func(x: int) -> int: ...\n\ndef func(x):\n    return x\n[out]\ntmp/lib.pyi:1: error: Name \"overload\" is not defined\ntmp/lib.pyi:4: error: Name \"func\" already defined on line 1\nmain:2: note: Revealed type is \"Any\"\n\n-- Order of errors is different\n[case testVeryBrokenOverload2]\n\nimport lib\nreveal_type(lib.func)\n[file lib.pyi]\n@overload\ndef func(x: int) -> int: ...\n@overload\ndef func(x: str) -> str: ...\n[out]\ntmp/lib.pyi:1: error: Name \"overload\" is not defined\ntmp/lib.pyi:3: error: Name \"func\" already defined on line 1\ntmp/lib.pyi:3: error: Name \"overload\" is not defined\nmain:3: note: Revealed type is \"Any\"\n\n[case testLiteralSubtypeOverlap]\nfrom typing import overload\nfrom typing_extensions import Literal\n\nclass MyInt(int): ...\n\n# Strictly speaking we can't prove this is unsafe (this depends on the implementation),\n# but such APIs seem like an anti-pattern anyways.\n@overload\ndef foo(x: Literal[0]) -> None: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef foo(x: MyInt) -> int: ...\ndef foo(x):\n    ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadedToGeneric]\nfrom typing import TypeVar, Callable, NewType, overload, Union\n\n# int in our stubs isn't overloaded\nclass fakeint:\n    @overload\n    def __init__(self, x: Union[str, bytes] = ...) -> None: ...\n    @overload\n    def __init__(self, x: Union[str, bytes], base: int) -> None: ...\n    def __init__(self, *args) -> None: pass  # type: ignore\n\n\nU = TypeVar('U')\nV = TypeVar('V')\nW = TypeVar('W')\ndef compose(f: Callable[[U], V], g: Callable[[W], U]) -> Callable[[W], V]:\n    return lambda x: f(g(x))\n\nID = NewType(\"ID\", fakeint)\n\ncompose(ID, fakeint)(\"test\")\nreveal_type(compose(ID, fakeint))  # N: Revealed type is \"def (Union[builtins.str, builtins.bytes]) -> __main__.ID\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadTwoTypeArgs]\nfrom typing import Generic, overload, TypeVar, Any\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\n\nclass A: ...\nclass B: ...\nclass G(Generic[T1, T2]): ...\n\n@overload\ndef f1(g: G[A, A]) -> A: ...\n@overload\ndef f1(g: G[A, B]) -> B: ...\ndef f1(g: Any) -> Any: ...\n\n@overload\ndef f2(g: G[A, Any]) -> A: ...\n@overload\ndef f2(g: G[A, B], x: int = ...) -> B: ...\ndef f2(g: Any, x: int = ...) -> Any: ...\n\n[case testOverloadTypeVsCallable]\nfrom typing import TypeVar, Type, Callable, Any, overload, Optional\nclass Foo:\n    def __init__(self, **kwargs: Any): pass\n_T = TypeVar('_T')\n@overload\ndef register(cls: Type[_T]) -> int: ...\n@overload\ndef register(cls: Callable[..., _T]) -> Optional[int]: ...\ndef register(cls: Any) -> Any: return None\n\n\nx = register(Foo)\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n\n[case testOverloadWithObjectDecorator]\nfrom typing import Any, Callable, Union, overload\n\nclass A:\n    def __call__(self, *arg, **kwargs) -> None: ...\n\ndef dec_a(f: Callable[..., Any]) -> A:\n    return A()\n\n@overload\ndef f_a(arg: int) -> None: ...\n@overload\ndef f_a(arg: str) -> None: ...\n@dec_a\ndef f_a(arg): ...\n\nclass B:\n    def __call__(self, arg: Union[int, str]) -> None: ...\n\ndef dec_b(f: Callable[..., Any]) -> B:\n    return B()\n\n@overload\ndef f_b(arg: int) -> None: ...\n@overload\ndef f_b(arg: str) -> None: ...\n@dec_b\ndef f_b(arg): ...\n\nclass C:\n    def __call__(self, arg: int) -> None: ...\n\ndef dec_c(f: Callable[..., Any]) -> C:\n    return C()\n\n@overload\ndef f_c(arg: int) -> None: ...\n@overload\ndef f_c(arg: str) -> None: ...\n@dec_c  # E: Overloaded function implementation does not accept all possible arguments of signature 2\ndef f_c(arg): ...\n[builtins fixtures/dict.pyi]\n\n[case testOverloadWithErrorDecorator]\nfrom typing import Any, Callable, TypeVar, overload\n\ndef dec_d(f: Callable[..., Any]) -> int: ...\n\n@overload\ndef f_d(arg: int) -> None: ...\n@overload\ndef f_d(arg: str) -> None: ...\n@dec_d  # E: \"int\" not callable\ndef f_d(arg): ...\n\nBad1 = TypeVar(Bad1)  # type: ignore\n\ndef dec_e(f: Bad1) -> Bad1: ...  # type: ignore\n\n@overload\ndef f_e(arg: int) -> None: ...\n@overload\ndef f_e(arg: str) -> None: ...\n@dec_e\ndef f_e(arg): ...\n\nclass Bad2:\n    def __getattr__(self, attr):\n        # __getattr__ is not called for implicit `__call__`\n        if attr == \"__call__\":\n            return lambda *a, **kw: print(a, kw)\n        raise AttributeError\n\n@overload\ndef f_f(arg: int) -> None: ...\n@overload\ndef f_f(arg: str) -> None: ...\n@Bad2()  # E: \"Bad2\" not callable\ndef f_f(arg): ...\n[builtins fixtures/dict.pyi]\n\n\n[case testOverloadIfBasic]\n# flags: --always-true True --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# Test basic overload merging\n# -----\n\n@overload\ndef f1(g: A) -> A: ...\nif True:\n    @overload\n    def f1(g: B) -> B: ...\ndef f1(g): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\n\n@overload\ndef f2(g: A) -> A: ...\n@overload\ndef f2(g: B) -> B: ...\nif False:\n    @overload\n    def f2(g: C) -> C: ...\ndef f2(g): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(C()))  # E: No overload variant of \"f2\" matches argument type \"C\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f2(g: A) -> A \\\n                      # N:     def f2(g: B) -> B \\\n                      # N: Revealed type is \"Any\"\n\n@overload\ndef f3(g: A) -> A: ...\n@overload\ndef f3(g: B) -> B: ...\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f3(g: C) -> C: ...\ndef f3(g): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(C()))  # E: No overload variant of \"f3\" matches argument type \"C\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f3(g: A) -> A \\\n                      # N:     def f3(g: B) -> B \\\n                      # N: Revealed type is \"Any\"\n\nif True:\n    @overload\n    def f4(g: A) -> A: ...\nif True:\n    @overload\n    def f4(g: B) -> B: ...\n@overload\ndef f4(g: C) -> C: ...\ndef f4(g): ...\nreveal_type(f4(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f4(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f4(C()))  # N: Revealed type is \"__main__.C\"\n\nif True:\n    @overload\n    def f5(g: A) -> A: ...\n@overload\ndef f5(g: B) -> B: ...\nif True:\n    @overload\n    def f5(g: C) -> C: ...\n@overload\ndef f5(g: D) -> D: ...\ndef f5(g): ...\nreveal_type(f5(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f5(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f5(C()))  # N: Revealed type is \"__main__.C\"\nreveal_type(f5(D()))  # N: Revealed type is \"__main__.D\"\n\n[case testOverloadIfSysVersion]\n# flags: --python-version 3.9\nfrom typing import overload\nimport sys\n\nclass A: ...\nclass B: ...\nclass C: ...\n\n# -----\n# \"Real\" world example\n# Test overload merging for sys.version_info\n# -----\n\n@overload\ndef f1(g: A) -> A: ...\nif sys.version_info >= (3, 9):\n    @overload\n    def f1(g: B) -> B: ...\ndef f1(g): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\n\n@overload\ndef f2(g: A) -> A: ...\n@overload\ndef f2(g: B) -> B: ...\nif sys.version_info >= (3, 10):\n    @overload\n    def f2(g: C) -> C: ...\ndef f2(g): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(C()))  # E: No overload variant of \"f2\" matches argument type \"C\" \\\n    # N: Possible overload variants: \\\n    # N:     def f2(g: A) -> A \\\n    # N:     def f2(g: B) -> B \\\n    # N: Revealed type is \"Any\"\n[builtins fixtures/ops.pyi]\n\n[case testOverloadIfMerging]\n# flags: --always-true True\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\n\n# -----\n# Test overload merging\n# -----\n\n@overload\ndef f1(g: A) -> A: ...\nif True:\n    # Some comment\n    @overload\n    def f1(g: B) -> B: ...\ndef f1(g): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\n\n@overload\ndef f2(g: A) -> A: ...\nif True:\n    @overload\n    def f2(g: bytes) -> B: ...\n    @overload\n    def f2(g: B) -> C: ...\ndef f2(g): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(B()))  # N: Revealed type is \"__main__.C\"\n\n@overload\ndef f3(g: A) -> A: ...\n@overload\ndef f3(g: B) -> B: ...\nif True:\n    def f3(g): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(B()))  # N: Revealed type is \"__main__.B\"\n\nif True:\n    @overload\n    def f4(g: A) -> A: ...\n@overload\ndef f4(g: B) -> B: ...\ndef f4(g): ...\nreveal_type(f4(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f4(B()))  # N: Revealed type is \"__main__.B\"\n\nif True:\n    # Some comment\n    @overload\n    def f5(g: A) -> A: ...\n    @overload\n    def f5(g: B) -> B: ...\ndef f5(g): ...\nreveal_type(f5(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f5(B()))  # N: Revealed type is \"__main__.B\"\n\n[case testOverloadIfNotMerging]\n# flags: --always-true True\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\n\n# -----\n# Don't merge if IfStmt contains nodes other than overloads\n# -----\n\n@overload  # E: An overloaded function outside a stub file must have an implementation\ndef f1(g: A) -> A: ...\n@overload\ndef f1(g: B) -> B: ...\nif True:\n    @overload  # E: Name \"f1\" already defined on line 12 \\\n               # E: Single overload definition, multiple required\n    def f1(g: C) -> C: ...\n    pass  # Some other action\ndef f1(g): ...  # E: Name \"f1\" already defined on line 12\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(C()))  # E: No overload variant of \"f1\" matches argument type \"C\" \\\n                          # N: Possible overload variants: \\\n                          # N:     def f1(g: A) -> A \\\n                          # N:     def f1(g: B) -> B \\\n                          # N: Revealed type is \"Any\"\n\nif True:\n    pass  # Some other action\n    @overload  # E: Single overload definition, multiple required\n    def f2(g: A) -> A: ...\n@overload  # E: Name \"f2\" already defined on line 26\ndef f2(g: B) -> B: ...\n@overload\ndef f2(g: C) -> C: ...\ndef f2(g): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(C()))  # N: Revealed type is \"__main__.A\" \\\n    # E: Argument 1 to \"f2\" has incompatible type \"C\"; expected \"A\"\n\n[case testOverloadIfOldStyle]\n# flags: --always-false var_false --always-true var_true\nfrom typing import overload\n\nclass A: ...\nclass B: ...\n\n# -----\n# Test old style to make sure it still works\n# -----\n\nvar_true = True\nvar_false = False\n\nif var_false:\n    @overload\n    def f1(g: A) -> A: ...\n    @overload\n    def f1(g: B) -> B: ...\n    def f1(g): ...\nelif var_true:\n    @overload\n    def f1(g: A) -> A: ...\n    @overload\n    def f1(g: B) -> B: ...\n    def f1(g): ...\nelse:\n    @overload\n    def f1(g: A) -> A: ...\n    @overload\n    def f1(g: B) -> B: ...\n    def f1(g): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\n\n[case testOverloadIfElse]\n# flags: --always-true True --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# Match the first always-true block\n# -----\n\n@overload\ndef f1(x: A) -> A: ...\nif True:\n    @overload\n    def f1(x: B) -> B: ...\nelif False:\n    @overload\n    def f1(x: C) -> C: ...\nelse:\n    @overload\n    def f1(x: D) -> D: ...\ndef f1(x): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f1(C()))  # E: No overload variant of \"f1\" matches argument type \"C\" \\\n    # N: Possible overload variants: \\\n    # N:     def f1(x: A) -> A \\\n    # N:     def f1(x: B) -> B \\\n    # N: Revealed type is \"Any\"\n\n@overload\ndef f2(x: A) -> A: ...\nif False:\n    @overload\n    def f2(x: B) -> B: ...\nelif True:\n    @overload\n    def f2(x: C) -> C: ...\nelse:\n    @overload\n    def f2(x: D) -> D: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(B()))  # E: No overload variant of \"f2\" matches argument type \"B\" \\\n    # N: Possible overload variants: \\\n    # N:     def f2(x: A) -> A \\\n    # N:     def f2(x: C) -> C \\\n    # N: Revealed type is \"Any\"\nreveal_type(f2(C()))  # N: Revealed type is \"__main__.C\"\n\n@overload\ndef f3(x: A) -> A: ...\nif False:\n    @overload\n    def f3(x: B) -> B: ...\nelif False:\n    @overload\n    def f3(x: C) -> C: ...\nelse:\n    @overload\n    def f3(x: D) -> D: ...\ndef f3(x): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(C()))  # E: No overload variant of \"f3\" matches argument type \"C\" \\\n    # N: Possible overload variants: \\\n    # N:     def f3(x: A) -> A \\\n    # N:     def f3(x: D) -> D \\\n    # N: Revealed type is \"Any\"\nreveal_type(f3(D()))  # N: Revealed type is \"__main__.D\"\n\n[case testOverloadIfElse2]\n# flags: --always-true True\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# Match the first always-true block\n# Don't merge overloads if can't be certain about execution of block\n# -----\n\n@overload\ndef f1(x: A) -> A: ...\nif True:\n    @overload\n    def f1(x: B) -> B: ...\nelse:\n    @overload\n    def f1(x: D) -> D: ...\ndef f1(x): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f1(D()))  # E: No overload variant of \"f1\" matches argument type \"D\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f1(x: A) -> A \\\n                      # N:     def f1(x: B) -> B \\\n                      # N: Revealed type is \"Any\"\n\n@overload\ndef f2(x: A) -> A: ...\nif True:\n    @overload\n    def f2(x: B) -> B: ...\nelif maybe_true:\n    @overload\n    def f2(x: C) -> C: ...\nelse:\n    @overload\n    def f2(x: D) -> D: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f2(C()))  # E: No overload variant of \"f2\" matches argument type \"C\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f2(x: A) -> A \\\n                      # N:     def f2(x: B) -> B \\\n                      # N: Revealed type is \"Any\"\n\n@overload  # E: Single overload definition, multiple required\ndef f3(x: A) -> A: ...\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f3(x: B) -> B: ...\nelif True:\n    @overload\n    def f3(x: C) -> C: ...\nelse:\n    @overload\n    def f3(x: D) -> D: ...\ndef f3(x): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(B()))  # E: No overload variant of \"f3\" matches argument type \"B\" \\\n                      # N: Possible overload variant: \\\n                      # N:     def f3(x: A) -> A \\\n                      # N: Revealed type is \"Any\"\n\n@overload  # E: Single overload definition, multiple required\ndef f4(x: A) -> A: ...\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f4(x: B) -> B: ...\nelse:\n    @overload\n    def f4(x: D) -> D: ...\ndef f4(x): ...\nreveal_type(f4(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f4(B()))  # E: No overload variant of \"f4\" matches argument type \"B\" \\\n                      # N: Possible overload variant: \\\n                      # N:     def f4(x: A) -> A \\\n                      # N: Revealed type is \"Any\"\n\n\n[case testOverloadIfElse3]\n# flags: --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\nclass E: ...\n\n# -----\n# Match the first always-true block\n# Don't merge overloads if can't be certain about execution of block\n# -----\n\n@overload\ndef f1(x: A) -> A: ...\nif False:\n    @overload\n    def f1(x: B) -> B: ...\nelse:\n    @overload\n    def f1(x: D) -> D: ...\ndef f1(x): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # E: No overload variant of \"f1\" matches argument type \"B\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f1(x: A) -> A \\\n                      # N:     def f1(x: D) -> D \\\n                      # N: Revealed type is \"Any\"\nreveal_type(f1(D()))  # N: Revealed type is \"__main__.D\"\n\n@overload  # E: Single overload definition, multiple required\ndef f2(x: A) -> A: ...\nif False:\n    @overload\n    def f2(x: B) -> B: ...\nelif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                  # E: Name \"maybe_true\" is not defined\n    @overload\n    def f2(x: C) -> C: ...\nelse:\n    @overload\n    def f2(x: D) -> D: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(C()))  # E: No overload variant of \"f2\" matches argument type \"C\" \\\n                      # N: Possible overload variant: \\\n                      # N:     def f2(x: A) -> A \\\n                      # N: Revealed type is \"Any\"\n\n@overload  # E: Single overload definition, multiple required\ndef f3(x: A) -> A: ...\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f3(x: B) -> B: ...\nelif False:\n    @overload\n    def f3(x: C) -> C: ...\nelse:\n    @overload\n    def f3(x: D) -> D: ...\ndef f3(x): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(B()))  # E: No overload variant of \"f3\" matches argument type \"B\" \\\n                      # N: Possible overload variant: \\\n                      # N:     def f3(x: A) -> A \\\n                      # N: Revealed type is \"Any\"\n\ndef g(bool_var: bool) -> None:\n    @overload\n    def f4(x: A) -> A: ...\n    if bool_var:  # E: Condition can't be inferred, unable to merge overloads\n        @overload\n        def f4(x: B) -> B: ...\n    elif maybe_true:  # E: Name \"maybe_true\" is not defined\n            # No 'Condition cannot be inferred' error here since it's already\n            # emitted on the first condition, 'bool_var', above.\n        @overload\n        def f4(x: C) -> C: ...\n    else:\n        @overload\n        def f4(x: D) -> D: ...\n    @overload\n    def f4(x: E) -> E: ...\n    def f4(x): ...\n    reveal_type(f4(E()))  # N: Revealed type is \"__main__.E\"\n    reveal_type(f4(B()))  # E: No overload variant of \"f4\" matches argument type \"B\" \\\n                          # N: Possible overload variants: \\\n                          # N:     def f4(x: A) -> A \\\n                          # N:     def f4(x: E) -> E \\\n                          # N: Revealed type is \"Any\"\n\n\n[case testOverloadIfSkipUnknownExecution]\n# flags: --always-true True\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# If blocks should be skipped if execution can't be certain\n# Overload name must match outer name\n# -----\n\n@overload  # E: Single overload definition, multiple required\ndef f1(x: A) -> A: ...\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f1(x: B) -> B: ...\ndef f1(x): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\n\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f2(x: A) -> A: ...\n@overload\ndef f2(x: B) -> B: ...\n@overload\ndef f2(x: C) -> C: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # E: No overload variant of \"f2\" matches argument type \"A\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f2(x: B) -> B \\\n                      # N:     def f2(x: C) -> C \\\n                      # N: Revealed type is \"Any\"\n\nif True:\n    @overload  # E: Single overload definition, multiple required\n    def f3(x: A) -> A: ...\n    if maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                    # E: Name \"maybe_true\" is not defined\n        @overload\n        def f3(x: B) -> B: ...\n    def f3(x): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\n\nif True:\n    if maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                    # E: Name \"maybe_true\" is not defined\n        @overload\n        def f4(x: A) -> A: ...\n    @overload\n    def f4(x: B) -> B: ...\n    @overload\n    def f4(x: C) -> C: ...\n    def f4(x): ...\nreveal_type(f4(A()))  # E: No overload variant of \"f4\" matches argument type \"A\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f4(x: B) -> B \\\n                      # N:     def f4(x: C) -> C \\\n                      # N: Revealed type is \"Any\"\n\n[case testOverloadIfDontSkipUnrelatedOverload]\n# flags: --always-true True\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# Don't skip if block if overload name doesn't match outer name\n# -----\n\n@overload  # E: Single overload definition, multiple required\ndef f1(x: A) -> A: ...\nif maybe_true:  # E: Name \"maybe_true\" is not defined\n    @overload  # E: Single overload definition, multiple required\n    def g1(x: B) -> B: ...\ndef f1(x): ...  # E: Name \"f1\" already defined on line 13\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\n\nif maybe_true:  # E: Name \"maybe_true\" is not defined\n    @overload  # E: Single overload definition, multiple required\n    def g2(x: A) -> A: ...\n@overload\ndef f2(x: B) -> B: ...\n@overload\ndef f2(x: C) -> C: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # E: No overload variant of \"f2\" matches argument type \"A\" \\\n    # N: Possible overload variants: \\\n    # N:     def f2(x: B) -> B \\\n    # N:     def f2(x: C) -> C \\\n    # N: Revealed type is \"Any\"\n\nif True:\n    @overload  # E: Single overload definition, multiple required\n    def f3(x: A) -> A: ...\n    def f3(x): ...\n    if maybe_true:  # E: Name \"maybe_true\" is not defined\n        @overload  # E: Single overload definition, multiple required\n        def g3(x: B) -> B: ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\n\nif True:\n    if maybe_true:  # E: Name \"maybe_true\" is not defined\n        @overload  # E: Single overload definition, multiple required\n        def g4(x: A) -> A: ...\n    @overload\n    def f4(x: B) -> B: ...\n    @overload\n    def f4(x: C) -> C: ...\n    def f4(x): ...\nreveal_type(f4(A()))  # E: No overload variant of \"f4\" matches argument type \"A\" \\\n    # N: Possible overload variants: \\\n    # N:     def f4(x: B) -> B \\\n    # N:     def f4(x: C) -> C \\\n    # N: Revealed type is \"Any\"\n\n[case testOverloadIfNotMergingDifferentNames]\n# flags: --always-true True\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# Don't merge overloads if IfStmts contains overload with different name\n# -----\n\n@overload  # E: An overloaded function outside a stub file must have an implementation\ndef f1(x: A) -> A: ...\n@overload\ndef f1(x: B) -> B: ...\nif True:\n    @overload  # E: Single overload definition, multiple required\n    def g1(x: C) -> C: ...\ndef f1(x): ...  # E: Name \"f1\" already defined on line 13\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(C()))  # E: No overload variant of \"f1\" matches argument type \"C\" \\\n    # N: Possible overload variants: \\\n    # N:     def f1(x: A) -> A \\\n    # N:     def f1(x: B) -> B \\\n    # N: Revealed type is \"Any\"\n\nif True:\n    @overload  # E: Single overload definition, multiple required\n    def g2(x: A) -> A: ...\n@overload\ndef f2(x: B) -> B: ...\n@overload\ndef f2(x: C) -> C: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # E: No overload variant of \"f2\" matches argument type \"A\" \\\n    # N: Possible overload variants: \\\n    # N:     def f2(x: B) -> B \\\n    # N:     def f2(x: C) -> C \\\n    # N: Revealed type is \"Any\"\nreveal_type(f2(B()))  # N: Revealed type is \"__main__.B\"\n\nif True:\n    if True:\n        @overload  # E: Single overload definition, multiple required\n        def g3(x: A) -> A: ...\n    @overload\n    def f3(x: B) -> B: ...\n    @overload\n    def f3(x: C) -> C: ...\n    def f3(x): ...\nreveal_type(f3(A()))  # E: No overload variant of \"f3\" matches argument type \"A\" \\\n    # N: Possible overload variants: \\\n    # N:     def f3(x: B) -> B \\\n    # N:     def f3(x: C) -> C \\\n    # N: Revealed type is \"Any\"\nreveal_type(f3(B()))  # N: Revealed type is \"__main__.B\"\n\n[case testOverloadIfSplitFunctionDef]\n# flags: --always-true True --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n# -----\n# Test split FuncDefs\n# -----\n\n@overload\ndef f1(x: A) -> A: ...\n@overload\ndef f1(x: B) -> B: ...\nif True:\n    def f1(x): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\n\n@overload\ndef f2(x: A) -> A: ...\n@overload\ndef f2(x: B) -> B: ...\nif False:\n    def f2(x): ...\nelse:\n    def f2(x): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\n\n@overload  # E: An overloaded function outside a stub file must have an implementation\ndef f3(x: A) -> A: ...\n@overload\ndef f3(x: B) -> B: ...\nif True:\n    def f3(x): ...   # E: Name \"f3\" already defined on line 31\nelse:\n    pass  # some other node\n    def f3(x): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\n\n[case testOverloadIfMixed]\n# flags: --always-true True --always-false False\nfrom typing import overload, TYPE_CHECKING\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\nif maybe_var:  # E: Name \"maybe_var\" is not defined\n    pass\nif True:\n    @overload\n    def f1(x: A) -> A: ...\n@overload\ndef f1(x: B) -> B: ...\ndef f1(x): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\n\nif True:\n    @overload\n    def f2(x: A) -> A: ...\n    @overload\n    def f2(x: B) -> B: ...\ndef f2(x): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(B()))  # N: Revealed type is \"__main__.B\"\n\nif True:\n    @overload\n    def f3(x: A) -> A: ...\n    @overload\n    def f3(x: B) -> B: ...\n    def f3(x): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(B()))  # N: Revealed type is \"__main__.B\"\n\n# Don't crash with AssignmentStmt if elif\n@overload  # E: Single overload definition, multiple required\ndef f4(x: A) -> A: ...\nif False:\n    @overload\n    def f4(x: B) -> B: ...\nelif True:\n    var = 1\ndef f4(x): ...  # E: Name \"f4\" already defined on line 39\n\nif TYPE_CHECKING:\n    @overload\n    def f5(x: A) -> A: ...\n    @overload\n    def f5(x: B) -> B: ...\ndef f5(x): ...\nreveal_type(f5(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f5(B()))  # N: Revealed type is \"__main__.B\"\n\n# Test from check-functions - testUnconditionalRedefinitionOfConditionalFunction\n# Don't merge If blocks if they appear before any overloads\n# and don't contain any overloads themselves.\nif maybe_true:  # E: Name \"maybe_true\" is not defined\n    def f6(x): ...\ndef f6(x): ...  # E: Name \"f6\" already defined on line 61\n\nif maybe_true:  # E: Name \"maybe_true\" is not defined\n    pass  # Some other node\n    def f7(x): ...\ndef f7(x): ...  # E: Name \"f7\" already defined on line 66\n\n@overload\ndef f8(x: A) -> A: ...\n@overload\ndef f8(x: B) -> B: ...\nif False:\n    def f8(x: C) -> C: ...\ndef f8(x): ...\nreveal_type(f8(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f8(C()))  # E: No overload variant of \"f8\" matches argument type \"C\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f8(x: A) -> A \\\n                      # N:     def f8(x: B) -> B \\\n                      # N: Revealed type is \"Any\"\n\nif maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                # E: Name \"maybe_true\" is not defined\n    @overload\n    def f9(x: A) -> A: ...\nif another_maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                        # E: Name \"another_maybe_true\" is not defined\n    @overload\n    def f9(x: B) -> B: ...\n@overload\ndef f9(x: C) -> C: ...\n@overload\ndef f9(x: D) -> D: ...\ndef f9(x): ...\nreveal_type(f9(A()))  # E: No overload variant of \"f9\" matches argument type \"A\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def f9(x: C) -> C \\\n                      # N:     def f9(x: D) -> D \\\n                      # N: Revealed type is \"Any\"\nreveal_type(f9(C()))  # N: Revealed type is \"__main__.C\"\n\nif True:\n    if maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                    # E: Name \"maybe_true\" is not defined\n        @overload\n        def f10(x: A) -> A: ...\n    if another_maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                            # E: Name \"another_maybe_true\" is not defined\n        @overload\n        def f10(x: B) -> B: ...\n    @overload\n    def f10(x: C) -> C: ...\n    @overload\n    def f10(x: D) -> D: ...\n    def f10(x): ...\nreveal_type(f10(A()))  # E: No overload variant of \"f10\" matches argument type \"A\" \\\n                       # N: Possible overload variants: \\\n                       # N:     def f10(x: C) -> C \\\n                       # N:     def f10(x: D) -> D \\\n                       # N: Revealed type is \"Any\"\nreveal_type(f10(C()))  # N: Revealed type is \"__main__.C\"\n\nif some_var:  # E: Name \"some_var\" is not defined\n    pass\n@overload\ndef f11(x: A) -> A: ...\n@overload\ndef f11(x: B) -> B: ...\ndef f11(x): ...\nreveal_type(f11(A()))  # N: Revealed type is \"__main__.A\"\n\nif True:\n    if some_var:  # E: Name \"some_var\" is not defined\n        pass\n    @overload\n    def f12(x: A) -> A: ...\n    @overload\n    def f12(x: B) -> B: ...\n    def f12(x): ...\nreveal_type(f12(A()))  # N: Revealed type is \"__main__.A\"\n\n[typing fixtures/typing-medium.pyi]\n\n[case testOverloadIfUnconditionalFuncDef]\n# flags: --always-true True --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\n\n# -----\n# Don't merge conditional FuncDef after unconditional one\n# -----\n\n@overload\ndef f1(x: A) -> A: ...\n@overload\ndef f1(x: B) -> B: ...\ndef f1(x): ...\n\n@overload\ndef f2(x: A) -> A: ...\nif True:\n    @overload\n    def f2(x: B) -> B: ...\ndef f2(x): ...\nif True:\n    def f2(x): ...  # E: Name \"f2\" already defined on line 17\n\n[case testOverloadItemHasMoreGeneralReturnType]\nfrom typing import overload\n\n@overload\ndef f() -> object: ...\n\n@overload\ndef f(x: int) -> object: ...\n\ndef f(x: int = 0) -> int:\n    return x\n\n@overload\ndef g() -> object: ...\n\n@overload\ndef g(x: int) -> str: ...\n\ndef g(x: int = 0) -> int:  # E: Overloaded function implementation cannot produce return type of signature 2\n    return x\n\n[case testOverloadIfNestedOk]\n# flags: --always-true True --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload\ndef f1(g: A) -> A: ...\nif True:\n    @overload\n    def f1(g: B) -> B: ...\n    if True:\n        @overload\n        def f1(g: C) -> C: ...\n        @overload\n        def f1(g: D) -> D: ...\ndef f1(g): ...\nreveal_type(f1(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f1(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f1(C()))  # N: Revealed type is \"__main__.C\"\nreveal_type(f1(D()))  # N: Revealed type is \"__main__.D\"\n\n@overload\ndef f2(g: A) -> A: ...\nif True:\n    @overload\n    def f2(g: B) -> B: ...\n    if True:\n        @overload\n        def f2(g: C) -> C: ...\n        if True:\n            @overload\n            def f2(g: D) -> D: ...\ndef f2(g): ...\nreveal_type(f2(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f2(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f2(C()))  # N: Revealed type is \"__main__.C\"\nreveal_type(f2(D()))  # N: Revealed type is \"__main__.D\"\n\n@overload\ndef f3(g: A) -> A: ...\nif True:\n    if True:\n        @overload\n        def f3(g: B) -> B: ...\n    if True:\n        @overload\n        def f3(g: C) -> C: ...\ndef f3(g): ...\nreveal_type(f3(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f3(B()))  # N: Revealed type is \"__main__.B\"\nreveal_type(f3(C()))  # N: Revealed type is \"__main__.C\"\n\n@overload\ndef f4(g: A) -> A: ...\nif True:\n    if False:\n        @overload\n        def f4(g: B) -> B: ...\n    else:\n        @overload\n        def f4(g: C) -> C: ...\ndef f4(g): ...\nreveal_type(f4(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f4(B()))  # E: No overload variant of \"f4\" matches argument type \"B\" \\\n    # N: Possible overload variants: \\\n    # N:     def f4(g: A) -> A \\\n    # N:     def f4(g: C) -> C \\\n    # N: Revealed type is \"Any\"\nreveal_type(f4(C()))  # N: Revealed type is \"__main__.C\"\n\n@overload\ndef f5(g: A) -> A: ...\nif True:\n    if False:\n        @overload\n        def f5(g: B) -> B: ...\n    elif True:\n        @overload\n        def f5(g: C) -> C: ...\ndef f5(g): ...\nreveal_type(f5(A()))  # N: Revealed type is \"__main__.A\"\nreveal_type(f5(B()))  # E: No overload variant of \"f5\" matches argument type \"B\" \\\n    # N: Possible overload variants: \\\n    # N:     def f5(g: A) -> A \\\n    # N:     def f5(g: C) -> C \\\n    # N: Revealed type is \"Any\"\nreveal_type(f5(C()))  # N: Revealed type is \"__main__.C\"\n\n[case testOverloadIfNestedFailure]\n# flags: --always-true True --always-false False\nfrom typing import overload\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\n@overload  # E: Single overload definition, multiple required\ndef f1(g: A) -> A: ...\nif True:\n    @overload  # E: Single overload definition, multiple required\n    def f1(g: B) -> B: ...  # E: Incompatible redefinition (redefinition with type \"Callable[[B], B]\", original type \"Callable[[A], A]\")\n    if maybe_true:  # E: Condition can't be inferred, unable to merge overloads \\\n                    # E: Name \"maybe_true\" is not defined\n        @overload\n        def f1(g: C) -> C: ...\n        @overload\n        def f1(g: D) -> D: ...\ndef f1(g): ...  # E: Name \"f1\" already defined on line 9\n\n@overload  # E: Single overload definition, multiple required\ndef f2(g: A) -> A: ...\nif True:\n    if False:\n        @overload\n        def f2(g: B) -> B: ...\n    elif maybe_true:  # E: Name \"maybe_true\" is not defined\n        @overload  # E: Single overload definition, multiple required\n        def f2(g: C) -> C: ...  # E: Incompatible redefinition (redefinition with type \"Callable[[C], C]\", original type \"Callable[[A], A]\")\ndef f2(g): ...  # E: Name \"f2\" already defined on line 21\n\n@overload  # E: Single overload definition, multiple required\ndef f3(g: A) -> A: ...\nif True:\n    @overload  # E: Single overload definition, multiple required\n    def f3(g: B) -> B: ...  # E: Incompatible redefinition (redefinition with type \"Callable[[B], B]\", original type \"Callable[[A], A]\")\n    if True:\n        pass  # Some other node\n        @overload  # E: Name \"f3\" already defined on line 32 \\\n                   # E: An overloaded function outside a stub file must have an implementation\n        def f3(g: C) -> C: ...\n        @overload\n        def f3(g: D) -> D: ...\ndef f3(g): ...  # E: Name \"f3\" already defined on line 32\n\n[case testOverloadingWithParamSpec]\nfrom typing import TypeVar, Callable, Any, overload\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\n@overload\ndef func(x: Callable[Concatenate[Any, P], R]) -> Callable[P, R]: ...\n@overload\ndef func(x: Callable[P, R]) -> Callable[Concatenate[str, P], R]: ...\ndef func(x: Callable[..., R]) -> Callable[..., R]: ...\n\ndef foo(arg1: str, arg2: int) -> bytes: ...\nreveal_type(func(foo))  # N: Revealed type is \"def (arg2: builtins.int) -> builtins.bytes\"\n\ndef bar() -> int: ...\nreveal_type(func(bar))  # N: Revealed type is \"def (builtins.str) -> builtins.int\"\n\nbaz: Callable[[str, str], str]\nif bool():\n    baz = lambda x, y: 'baz'\nreveal_type(func(baz))  # N: Revealed type is \"def (builtins.str) -> builtins.str\"\n\neggs = lambda: 'eggs'\nreveal_type(func(eggs))  # N: Revealed type is \"def (builtins.str) -> builtins.str\"\n\nspam: Callable[..., str]\nif bool():\n    spam = lambda x, y: 'baz'\nreveal_type(func(spam))  # N: Revealed type is \"def (*Any, **Any) -> Any\"\n[builtins fixtures/paramspec.pyi]\n\n[case testGenericOverloadOverlapWithType]\nimport m\n\n[file m.pyi]\nfrom typing import TypeVar, Type, overload, Callable\n\nT = TypeVar(\"T\", bound=str)\n@overload\ndef foo(x: Type[T] | int) -> int: ...\n@overload\ndef foo(x: Callable[[int], bool]) -> str: ...\n\n[case testGenericOverloadOverlapWithCollection]\nimport m\n\n[file m.pyi]\nfrom typing import TypeVar, Sequence, overload, List\n\nT = TypeVar(\"T\", bound=str)\n\n@overload\ndef foo(x: List[T]) -> str: ...\n@overload\ndef foo(x: Sequence[int]) -> int: ...\n[builtins fixtures/list.pyi]\n\n# Also see `check-python38.test` for similar tests with `/` args:\n[case testOverloadPositionalOnlyErrorMessageOldStyle]\nfrom typing import overload\n\n@overload\ndef foo(__a: int): ...\n@overload\ndef foo(a: str): ...\ndef foo(a): ...\n\nfoo(a=1)\n[out]\nmain:9: error: No overload variant of \"foo\" matches argument type \"int\"\nmain:9: note: Possible overload variants:\nmain:9: note:     def foo(int, /) -> Any\nmain:9: note:     def foo(a: str) -> Any\n\n[case testOverloadUnionGenericBounds]\nfrom typing import overload, TypeVar, Sequence, Union\n\nclass Entity: ...\nclass Assoc: ...\n\nE = TypeVar(\"E\", bound=Entity)\nA = TypeVar(\"A\", bound=Assoc)\n\nclass Test:\n    @overload\n    def foo(self, arg: Sequence[E]) -> None: ...\n    @overload\n    def foo(self, arg: Sequence[A]) -> None: ...\n    def foo(self, arg: Union[Sequence[E], Sequence[A]]) -> None:\n        ...\n\n[case testOverloadedStaticMethodOnInstance]\nfrom typing import overload\n\nclass Snafu(object):\n    @overload\n    @staticmethod\n    def snafu(value: bytes) -> bytes: ...\n    @overload\n    @staticmethod\n    def snafu(value: str) -> str: ...\n    @staticmethod\n    def snafu(value):\n        ...\nreveal_type(Snafu().snafu('123'))  # N: Revealed type is \"builtins.str\"\nreveal_type(Snafu.snafu('123'))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/staticmethod.pyi]\n\n[case testOverloadedWithInternalTypeVars]\n# flags: --new-type-inference\nimport m\n\n[file m.pyi]\nfrom typing import Callable, TypeVar, overload\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\", bound=str)\n\n@overload\ndef foo(x: int = ...) -> Callable[[T], T]: ...\n@overload\ndef foo(x: S = ...) -> Callable[[T], T]: ...\n\n[case testOverloadGenericStarArgOverlap]\nfrom typing import Any, Callable, TypeVar, overload, Union, Tuple, List\n\nF = TypeVar(\"F\", bound=Callable[..., Any])\nS = TypeVar(\"S\", bound=int)\n\ndef id(f: F) -> F: ...\n\n@overload\ndef struct(*cols: S) -> int: ...\n@overload\ndef struct(__cols: Union[List[S], Tuple[S, ...]]) -> int: ...\n@id\ndef struct(*cols: Union[S, Union[List[S], Tuple[S, ...]]]) -> int:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testRegularGenericDecoratorOverload]\nfrom typing import Callable, overload, TypeVar, List\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\ndef transform(func: Callable[[S], List[T]]) -> Callable[[S], 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 (builtins.int) -> builtins.float, def (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 (builtins.int) -> builtins.float, def (builtins.str) -> builtins.str)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testOverloadOverlapWithNameOnlyArgs]\nfrom typing import overload\n\n@overload\ndef d(x: int) -> int: ...\n@overload\ndef d(f: int, *, x: int) -> str: ...\ndef d(*args, **kwargs): ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadCallableGenericSelf]\nfrom typing import Any, TypeVar, Generic, overload, reveal_type\n\nT = TypeVar(\"T\")\n\nclass MyCallable(Generic[T]):\n    def __init__(self, t: T):\n        self.t = t\n\n    @overload\n    def __call__(self: \"MyCallable[int]\") -> str: ...\n    @overload\n    def __call__(self: \"MyCallable[str]\") -> int: ...\n    def __call__(self): ...\n\nc = MyCallable(5)\nreveal_type(c)  # N: Revealed type is \"__main__.MyCallable[builtins.int]\"\nreveal_type(c())  # N: Revealed type is \"builtins.str\"\n\nc2 = MyCallable(\"test\")\nreveal_type(c2)  # N: Revealed type is \"__main__.MyCallable[builtins.str]\"\nreveal_type(c2()) # should be int  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadWithStarAnyFallback]\nfrom typing import overload, Any\n\nclass A:\n    @overload\n    def f(self, e: str) -> str: ...\n    @overload\n    def f(self, *args: Any, **kwargs: Any) -> Any: ...\n    def f(self, *args, **kwargs):\n        pass\n\nclass B:\n    @overload\n    def f(self, e: str, **kwargs: Any) -> str: ...\n    @overload\n    def f(self, *args: Any, **kwargs: Any) -> Any: ...\n    def f(self, *args, **kwargs):\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadsSafeOverlapAllowed]\nfrom lib import *\n[file lib.pyi]\nfrom typing import overload\n\n@overload\ndef bar(x: object) -> object: ...\n@overload\ndef bar(x: int = ...) -> int: ...\n\n[case testOverloadsInvariantOverlapAllowed]\nfrom lib import *\n[file lib.pyi]\nfrom typing import overload, List\n\n@overload\ndef bar(x: List[int]) -> List[int]: ...\n@overload\ndef bar(x: List[object]) -> List[object]: ...\n\n[case testOverloadsNoneAnyOverlapAllowed]\nfrom lib import *\n[file lib.pyi]\nfrom typing import overload, Any\n\n@overload\ndef foo(x: None) -> int: ...\n@overload\ndef foo(x: object) -> str: ...\n\n@overload\ndef bar(x: int) -> int: ...\n@overload\ndef bar(x: Any) -> str: ...\n\n[case testOverloadOnInvalidTypeArgument]\nfrom typing import TypeVar, Self, Generic, overload\n\nclass C: pass\n\nT = TypeVar(\"T\", bound=C)\n\nclass D(Generic[T]):\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    def f(Self, x): ...\n\na: D[str]  # E: Type argument \"str\" of \"D\" must be a subtype of \"C\"\nreveal_type(a.f(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(a.f(\"x\"))  # N: Revealed type is \"builtins.str\"\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                          # 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        args = a\n        kwargs = a\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 \"typing.Callable\"\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 \"Callable[[Arg(int, 'x')], None]\"; expected \"Callable[[Arg(int, 'y')], 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 \"Callable[[NamedArg(int, 'x')], int]\"; expected \"Callable[[int, NamedArg(int, 'x')], int]\"\ndef two(*, x: int) -> int: ...\n\n@expects_int_first  # E: Argument 1 to \"expects_int_first\" has incompatible type \"Callable[[KwArg(int)], int]\"; expected \"Callable[[int, KwArg(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: \"run_job\" defined here\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`6, *_P.args, **_P.kwargs) -> _R`6\"\nreveal_type(A().func)  # N: Revealed type is \"def [_P, _R] (action: def (*_P.args, **_P.kwargs) -> _R`10, *_P.args, **_P.kwargs) -> _R`10\"\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`4, None]) -> __main__.Job[_P`4, None]\"\nreveal_type(A().func)  # N: Revealed type is \"def [_P] (action: __main__.Job[_P`6, None]) -> __main__.Job[_P`6, 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]\n# flags: --new-type-inference\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 \"P2\" is unbound \\\n                                                                        # E: ParamSpec must have \"*args\" typed as \"P1.args\" and \"**kwargs\" typed as \"P1.kwargs\"\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) -> Union[builtins.int, ...]\"\ny: C[int, str]\nreveal_type(y)  # N: Revealed type is \"def (builtins.int, builtins.str) -> Union[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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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]\n# flags: --new-type-inference\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 type argument 1 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 \"Callable[[Callable[[], R], VarArg(object), DefaultNamedArg(str, 'backend')], 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[Union[T`-1, builtins.str]]\"\nreveal_type(func(42))  # N: Revealed type is \"builtins.list[Union[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) -> Union[T`-1, builtins.str]\"\nreveal_type(func2(42))  # N: Revealed type is \"Union[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: \"run\" defined here\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: \"run\" defined here\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 \"Union[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"
  },
  {
    "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 type argument 1 of \"A\"\nA([1], '2')  # E: Cannot infer type argument 1 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[Union[__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`5, other: _AT`5) -> builtins.bool\"\nreveal_type(B.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`6, other: _AT`6) -> builtins.bool\"\nreveal_type(C.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`7, other: _AT`7) -> builtins.bool\"\nreveal_type(D.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`8, other: _AT`8) -> 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]\n# flags: --new-type-inference\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 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\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])\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])\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])\n[builtins fixtures/list.pyi]\n[out]\ntmp/b.py:8: error: Value of type \"int\" is not indexable\ntmp/a.py:7: error: Name \"Lst\" is not defined\ntmp/a.py:10: error: The type \"Type[Callable]\" is not generic and not indexable\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 \"Union[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 \"Union[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 \"Union[TA, TB, int]\" whose item \"TB\" is not bound to an attrs class \\\n                               # E: Argument 1 to \"evolve\" has incompatible type \"Union[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 \"Union[builtins.int, None]\"\n[builtins fixtures/plugin_attrs.pyi]\n"
  },
  {
    "path": "test-data/unit/check-possibly-undefined.test",
    "content": "[case testDefinedInOneBranch]\n# flags: --enable-error-code possibly-undefined\nif int():\n    a = 1\nelse:\n    x = 2\nz = a + 1  # E: Name \"a\" may be undefined\nz = a + 1  # We only report the error on first occurrence.\n\n[case testElif]\n# flags: --enable-error-code possibly-undefined\nif int():\n    a = 1\nelif int():\n    a = 2\nelse:\n    x = 3\n\nz = a + 1  # E: Name \"a\" may be undefined\n\n[case testUsedInIf]\n# flags: --enable-error-code possibly-undefined\nif int():\n    y = 1\nif int():\n    x = y  # E: Name \"y\" may be undefined\n\n[case testDefinedInAllBranches]\n# flags: --enable-error-code possibly-undefined\nif int():\n    a = 1\nelif int():\n    a = 2\nelse:\n    a = 3\nz = a + 1\n\n[case testOmittedElse]\n# flags: --enable-error-code possibly-undefined\nif int():\n    a = 1\nz = a + 1  # E: Name \"a\" may be undefined\n\n[case testUpdatedInIf]\n# flags: --enable-error-code possibly-undefined\n# Variable a is already defined. Just updating it in an \"if\" is acceptable.\na = 1\nif int():\n    a = 2\nz = a + 1\n\n[case testNestedIf]\n# flags: --enable-error-code possibly-undefined\nif int():\n    if int():\n        a = 1\n        x = 1\n        x = x + 1\n    else:\n        a = 2\n    b = a + x  # E: Name \"x\" may be undefined\n    b = b + 1\nelse:\n    b = 2\nz = a + b  # E: Name \"a\" may be undefined\n\n[case testVeryNestedIf]\n# flags: --enable-error-code possibly-undefined\nif int():\n    if int():\n        if int():\n            a = 1\n        else:\n            a = 2\n        x = a\n    else:\n        a = 2\n    b = a\nelse:\n    b = 2\nz = a + b  # E: Name \"a\" may be undefined\n\n[case testTupleUnpack]\n# flags: --enable-error-code possibly-undefined\n\nif int():\n    (x, y) = (1, 2)\nelse:\n    [y, z] = [1, 2]\na = y + x  # E: Name \"x\" may be undefined\na = y + z  # E: Name \"z\" may be undefined\n\n[case testIndexExpr]\n# flags: --enable-error-code possibly-undefined\n\nif int():\n    *x, y = (1, 2)\nelse:\n    x = [1, 2]\na = x  # No error.\nb = y  # E: Name \"y\" may be undefined\n\n[case testRedefined]\n# flags: --enable-error-code possibly-undefined\ny = 3\nif int():\n    if int():\n        y = 2\n    x = y + 2\nelse:\n    if int():\n        y = 2\n    x = y + 2\n\nx = y + 2\n\n[case testFunction]\n# flags: --enable-error-code possibly-undefined\ndef f0() -> None:\n    if int():\n        def some_func() -> None:\n            pass\n\n    some_func()  # E: Name \"some_func\" may be undefined\n\ndef f1() -> None:\n    if int():\n        def some_func() -> None:\n            pass\n    else:\n        def some_func() -> None:\n            pass\n\n    some_func()  # No error.\n\n[case testLambda]\n# flags: --enable-error-code possibly-undefined\ndef f0(b: bool) -> None:\n    if b:\n        fn = lambda: 2\n    y = fn   # E: Name \"fn\" may be undefined\n\n[case testUsedBeforeDefClass]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f(x: A):  # No error here.\n    pass\ny = A()  # E: Name \"A\" is used before definition\nclass A: pass\n\n[case testClassScope]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\nclass C:\n    x = 0\n    def f0(self) -> None: pass\n\n    def f2(self) -> None:\n        f0()  # No error.\n        self.f0()  # No error.\n\nf0()  # E: Name \"f0\" is used before definition\ndef f0() -> None: pass\ny = x  # E: Name \"x\" is used before definition\nx = 1\n\n[case testClassInsideFunction]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f() -> None:\n    class C: pass\n\nc = C()  # E: Name \"C\" is used before definition\nclass C: pass\n\n[case testUsedBeforeDefFunc]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\nfoo() # E: Name \"foo\" is used before definition\ndef foo(): pass\n[case testGenerator]\n# flags: --enable-error-code possibly-undefined\nif int():\n    a = 3\ns = [a + 1 for a in [1, 2, 3]]\nx = a  # E: Name \"a\" may be undefined\n\n[case testScope]\n# flags: --enable-error-code possibly-undefined\ndef foo() -> None:\n    if int():\n        y = 2\n\nif int():\n    y = 3\nx = y  # E: Name \"y\" may be undefined\n\n[case testVarDefinedInOuterScopeUpdated]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f0() -> None:\n    global x\n    y = x\n    x = 1  # No error.\n\nx = 2\n\n[case testNonlocalVar]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f0() -> None:\n    x = 2\n\n    def inner() -> None:\n        nonlocal x\n        y = x\n        x = 1  # No error.\n\n[case testGlobalDeclarationAfterUsage]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f0() -> None:\n    y = x  # E: Name \"x\" is used before definition\n    global x\n    x = 1  # No error.\n\nx = 2\n\n[case testVarDefinedInOuterScope]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f0() -> None:\n  global x\n  y = x  # We do not detect such errors right now.\n\nf0()\nx = 1\n\n[case testDefinedInOuterScopeNoError]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef foo() -> None:\n    bar()\n\ndef bar() -> None:\n    foo()\n\n[case testClassFromOuterScopeRedefined]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\nclass c: pass\n\ndef f0() -> None:\n    s = c()  # E: Name \"c\" is used before definition\n    class c: pass\n\ndef f1() -> None:\n    s = c()  # No error.\n\ndef f2() -> None:\n    s = c()  # E: Name \"c\" is used before definition\n    if int():\n        class c: pass\n\nglob = c()\ndef f3(x: c = glob) -> None:\n    glob = 123\n\n[case testVarFromOuterScopeRedefined]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\nx = 0\n\ndef f0() -> None:\n    y = x  # E: Name \"x\" is used before definition\n    x = 0\n\ndef f1() -> None:\n    y = x  # No error.\n\ndef f2() -> None:\n    y = x  # E: Name \"x\" is used before definition\n    global x\n\ndef f3() -> None:\n    global x\n    y = x  # No error.\n\ndef f4() -> None:\n    if int():\n        x = 0\n    y = x  # E: Name \"x\" may be undefined\n\n[case testFuncParams]\n# flags: --enable-error-code possibly-undefined\ndef foo(a: int) -> None:\n    if int():\n        a = 2\n    x = a\n\n[case testWhile]\n# flags: --enable-error-code possibly-undefined\nwhile int():\n    a = 1\n\nx = a  # E: Name \"a\" may be undefined\n\nwhile int():\n    b = 1\nelse:\n    b = 2\n\ny = b  # No error.\n\nwhile True:\n    c = 1\n    if int():\n        break\ny = c  # No error.\n\n# This while loop doesn't have a `break` inside, so we know that the else must always get executed.\nwhile int():\n    pass\nelse:\n    d = 1\ny = d  # No error.\n\nwhile int():\n    if int():\n        break\nelse:\n    e = 1\n# If a while loop has a `break`, it's possible that the else didn't get executed.\ny = e  # E: Name \"e\" may be undefined\n\nwhile int():\n    while int():\n        if int():\n            break\n    else:\n        f = 1\nelse:\n    g = 2\n\ny = f  # E: Name \"f\" may be undefined\ny = g\n\n[case testForLoop]\n# flags: --enable-error-code possibly-undefined\nfor x in [1, 2, 3]:\n    if x:\n        x = 1\n    y = x\nelse:\n    z = 2\n\na = z + y  # E: Name \"y\" may be undefined\n\n[case testReturn]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> int:\n    if int():\n        x = 1\n    else:\n        return 0\n    return x\n\ndef f2() -> int:\n    if int():\n        x = 1\n    elif int():\n        return 0\n    else:\n        x = 2\n    return x\n\ndef f3() -> int:\n    if int():\n        x = 1\n    elif int():\n        return 0\n    else:\n        y = 2\n    return x  # E: Name \"x\" may be undefined\n\ndef f4() -> int:\n    if int():\n        x = 1\n    elif int():\n        return 0\n    else:\n        return 0\n    return x\n\ndef f5() -> int:\n    # This is a test against crashes.\n    if int():\n        return 1\n    if int():\n        return 2\n    else:\n        return 3\n    return 1\n\ndef f6() -> int:\n    if int():\n        x = 0\n        return x\n    return x  # E: Name \"x\" may be undefined\n\n[case testDefinedDifferentBranchUsedBeforeDef]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\n\ndef f0() -> None:\n    if int():\n        x = 0\n    else:\n        y = x  # E: Name \"x\" is used before definition\n        z = x  # E: Name \"x\" is used before definition\n\ndef f1() -> None:\n    x = 1\n    if int():\n        x = 0\n    else:\n        y = x  # No error.\n\ndef f2() -> None:\n    if int():\n        x = 0\n    elif int():\n        y = x  # E: Name \"x\" is used before definition\n    else:\n        y = x  # E: Name \"x\" is used before definition\n        if int():\n            z = x  # E: Name \"x\" is used before definition\n            x = 1\n        else:\n            x = 2\n        w = x  # No error.\n\n[case testPossiblyUndefinedLoop]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\n\ndef f0() -> None:\n    first_iter = True\n    for i in [0, 1]:\n        if first_iter:\n            first_iter = False\n            x = 0\n        elif int():\n            # This is technically a false positive but mypy isn't smart enough for this yet.\n            y = x  # E: Name \"x\" may be undefined\n        else:\n            y = x  # E: Name \"x\" may be undefined\n            if int():\n                z = x  # E: Name \"x\" may be undefined\n                x = 1\n            else:\n                x = 2\n            w = x  # No error.\n\ndef f1() -> None:\n    while True:\n        if int():\n            x = 0\n        else:\n            y = x  # E: Name \"x\" may be undefined\n            z = x  # E: Name \"x\" may be undefined\n\ndef f2() -> None:\n    for i in [0, 1]:\n        x = i\n    else:\n        y = x  # E: Name \"x\" may be undefined\n\ndef f3() -> None:\n    while int():\n        x = 1\n    else:\n        y = x  # E: Name \"x\" may be undefined\n\ndef f4() -> None:\n    while int():\n        y = x  # E: Name \"x\" may be undefined\n        x: int = 1\n\n[case testAssert]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> int:\n    if int():\n        x = 1\n    else:\n        assert False, \"something something\"\n    return x\n\ndef f2() -> int:\n    if int():\n        x = 1\n    elif int():\n        assert False\n    else:\n        y = 2\n    return x  # E: Name \"x\" may be undefined\n\n[case testRaise]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> int:\n    if int():\n        x = 1\n    else:\n        raise BaseException(\"something something\")\n    return x\n\ndef f2() -> int:\n    if int():\n        x = 1\n    elif int():\n        raise BaseException(\"something something\")\n    else:\n        y = 2\n    return x  # E: Name \"x\" may be undefined\n[builtins fixtures/exception.pyi]\n\n[case testContinue]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> int:\n    while int():\n        if int():\n            x = 1\n        else:\n            continue\n        y = x\n    else:\n        x = 2\n    return x\n\ndef f2() -> int:\n    while int():\n        if int():\n            x = 1\n        elif int():\n            pass\n        else:\n            continue\n        y = x  # E: Name \"x\" may be undefined\n    return x  # E: Name \"x\" may be undefined\n\ndef f3() -> None:\n    while True:\n        if int():\n            x = 2\n        elif int():\n            continue\n        else:\n            continue\n        y = x\n\n[case testBreak]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> None:\n    while int():\n        if int():\n            x = 1\n        else:\n            break\n        y = x  # No error -- x is always defined.\n\ndef f2() -> None:\n    while int():\n        if int():\n            x = 1\n        elif int():\n            pass\n        else:\n            break\n        y = x  # E: Name \"x\" may be undefined\n\ndef f3() -> None:\n    while int():\n        x = 1\n        while int():\n            if int():\n                x = 2\n            else:\n                break\n        y = x\n    z = x  # E: Name \"x\" may be undefined\n\n[case testTryBasic]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f1() -> int:\n    try:\n        x = 1\n    except:\n        pass\n    return x  # E: Name \"x\" may be undefined\n\ndef f2() -> int:\n    try:\n        pass\n    except:\n        x = 1\n    return x  # E: Name \"x\" may be undefined\n\ndef f3() -> int:\n    try:\n        x = 1\n    except:\n        y = x  # E: Name \"x\" may be undefined\n    return x  # E: Name \"x\" may be undefined\n\ndef f4() -> int:\n    try:\n        x = 1\n    except:\n        return 0\n    return x\n\ndef f5() -> int:\n    try:\n        x = 1\n    except:\n        raise\n    return x\n\ndef f6() -> None:\n    try:\n        pass\n    except BaseException as exc:\n        x = exc  # No error.\n        exc = BaseException()\n    # This case is covered by the other check, not by possibly undefined check.\n    y = exc # E: Trying to read deleted variable \"exc\"\n\ndef f7() -> int:\n    try:\n        if int():\n            x = 1\n        assert False\n    except:\n        pass\n    return x  # E: Name \"x\" may be undefined\n[builtins fixtures/exception.pyi]\n\n[case testTryMultiExcept]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> int:\n    try:\n        x = 1\n    except BaseException:\n        x = 2\n    except:\n        x = 3\n    return x\n\ndef f2() -> int:\n    try:\n        x = 1\n    except BaseException:\n        pass\n    except:\n        x = 3\n    return x  # E: Name \"x\" may be undefined\n[builtins fixtures/exception.pyi]\n\n[case testTryFinally]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\ndef f1() -> int:\n    try:\n        x = 1\n    finally:\n        x = 2\n    return x\n\ndef f2() -> int:\n    try:\n        pass\n    except:\n        pass\n    finally:\n        x = 2\n    return x\n\ndef f3() -> int:\n    try:\n        x = 1\n    except:\n        pass\n    finally:\n        y = x  # E: Name \"x\" may be undefined\n    return x\n\ndef f4() -> int:\n    try:\n        x = 0\n    except BaseException:\n        raise\n    finally:\n        y = x  # E: Name \"x\" may be undefined\n    return y\n\ndef f5() -> int:\n    try:\n        if int():\n            x = 1\n        else:\n            return 0\n    finally:\n        pass\n    return x  # No error.\n\ndef f6() -> int:\n    try:\n        if int():\n            x = 1\n        else:\n            return 0\n    finally:\n        a = x  # E: Name \"x\" may be undefined\n    return a\n[builtins fixtures/exception.pyi]\n\n[case testTryElse]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> int:\n    try:\n        return 0\n    except BaseException:\n        x = 1\n    else:\n        x = 2\n    finally:\n        y = x\n    return y\n\ndef f2() -> int:\n    try:\n        pass\n    except:\n        x = 1\n    else:\n        x = 2\n    return x\n\ndef f3() -> int:\n    try:\n        pass\n    except:\n        x = 1\n    else:\n        pass\n    return x  # E: Name \"x\" may be undefined\n\ndef f4() -> int:\n    try:\n        x = 1\n    except:\n        x = 2\n    else:\n        pass\n    return x\n\ndef f5() -> int:\n    try:\n        pass\n    except:\n        x = 1\n    else:\n        return 1\n    return x\n[builtins fixtures/exception.pyi]\n\n[case testNoReturn]\n# flags: --enable-error-code possibly-undefined\n\nfrom typing import NoReturn\ndef fail() -> NoReturn:\n    assert False\n\ndef f() -> None:\n    if int():\n        x = 1\n    elif int():\n        x = 2\n        y = 3\n    else:\n        # This has a NoReturn type, so we can skip it.\n        fail()\n    z = y  # E: Name \"y\" may be undefined\n    z = x\n\n[case testDictComprehension]\n# flags: --enable-error-code possibly-undefined\n\ndef f() -> None:\n    for _ in [1, 2]:\n        key = 2\n        val = 2\n\n    x = (\n        key,  # E: Name \"key\" may be undefined\n        val,  # E: Name \"val\" may be undefined\n    )\n\n    d = [(0, \"a\"), (1, \"b\")]\n    {val: key for key, val in d}\n[builtins fixtures/dict.pyi]\n\n[case testWithStmt]\n# flags: --enable-error-code possibly-undefined\nfrom contextlib import contextmanager\n\n@contextmanager\ndef ctx(*args):\n    yield 1\n\ndef f() -> None:\n    if int():\n        a = b = 1\n        x = 1\n\n    with ctx() as a, ctx(a) as b, ctx(x) as x:  # E: Name \"x\" may be undefined\n        c = a\n        c = b\n    d = a\n    d = b\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachable]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\nimport typing\n\ndef f0() -> None:\n    if typing.TYPE_CHECKING:\n        x = 1\n    elif int():\n        y = 1\n    else:\n        y = 2\n    a = x\n\ndef f1() -> None:\n    if not typing.TYPE_CHECKING:\n        pass\n    else:\n        z = 1\n    a = z\n\ndef f2() -> None:\n    if typing.TYPE_CHECKING:\n        x = 1\n    else:\n        y = x\n[typing fixtures/typing-medium.pyi]\n\n[case testUsedBeforeDef]\n# flags: --enable-error-code used-before-def\n\ndef f0() -> None:\n    x = y  # E: Name \"y\" is used before definition\n    y: int = 1\n\ndef f2() -> None:\n    if int():\n        pass\n    else:\n        # No used-before-def error.\n        y = z  # E: Name \"z\" is not defined\n\n    def inner2() -> None:\n        z = 0\n\ndef f3() -> None:\n    if int():\n        pass\n    else:\n        y = z  # E: Name \"z\" is used before definition\n    z: int = 2\n\ndef f4() -> None:\n    if int():\n        pass\n    else:\n        y = z  # E: Name \"z\" is used before definition\n        x = z  # E: Name \"z\" is used before definition\n    z: int = 2\n\n[case testUsedBeforeDefImportsBasicImportNoError]\n# flags: --enable-error-code used-before-def --enable-error-code possibly-undefined --disable-error-code no-redef\nimport foo  # type: ignore\n\na = foo  # No error.\nfoo: int = 1\n\n[case testUsedBeforeDefImportsDotImport]\n# flags: --enable-error-code used-before-def --enable-error-code possibly-undefined --disable-error-code no-redef\nimport x.y  # type: ignore\n\na = y  # E: Name \"y\" is used before definition\ny: int = 1\n\nb = x  # No error.\nx: int = 1\n\nc = x.y  # No error.\nx: int = 1\n\n[case testUsedBeforeDefImportBasicRename]\n# flags: --enable-error-code used-before-def --disable-error-code=no-redef\nimport x.y as z  # type: ignore\nfrom typing import Any\n\na = z  # No error.\nz: int = 1\n\na = x  # E: Name \"x\" is used before definition\nx: int = 1\n\na = y  # E: Name \"y\" is used before definition\ny: int = 1\n\n[case testUsedBeforeDefImportFrom]\n# flags: --enable-error-code used-before-def --disable-error-code no-redef\nfrom foo import x  # type: ignore\n\na = x  # No error.\nx: int = 1\n\n[case testUsedBeforeDefImportFromRename]\n# flags: --enable-error-code used-before-def --disable-error-code no-redef\nfrom foo import x as y  # type: ignore\n\na = y  # No error.\ny: int = 1\n\na = x  # E: Name \"x\" is used before definition\nx: int = 1\n\n[case testUsedBeforeDefFunctionDeclarations]\n# flags: --enable-error-code used-before-def\n\ndef f0() -> None:\n    def inner() -> None:\n        pass\n\n    inner()  # No error.\n    inner = lambda: None\n\n[case testUsedBeforeDefBuiltinsFunc]\n# flags: --enable-error-code used-before-def\n\ndef f0() -> None:\n    s = type(123)  # E: Name \"type\" is used before definition\n    type = \"abc\"\n    a = type\n\ndef f1() -> None:\n    s = type(123)\n\n[case testUsedBeforeDefBuiltinsGlobal]\n# flags: --enable-error-code used-before-def\n\ns = type(123)\ntype = \"abc\"\na = type\n\n[case testUsedBeforeDefBuiltinsClass]\n# flags: --enable-error-code used-before-def\n\nclass C:\n    s = type\n    type = s\n\n[case testUsedBeforeDefBuiltinsGenerator]\n# flags: --enable-error-code used-before-def\n\ndef f0() -> None:\n    _ = [type for type in [type(\"a\"), type(1)]]\n\n[case testUsedBeforeDefBuiltinsMultipass]\n# flags: --enable-error-code used-before-def\n\n# When doing multiple passes, mypy resolves references slightly differently.\n# In this case, it would refer the earlier `type` call to the range class defined below.\n_type = type  # No error\n_C = C  # E: Name \"C\" is used before definition\nclass type: pass\nclass C: pass\n\n[case testUsedBeforeDefImplicitModuleAttrs]\n# flags: --enable-error-code used-before-def\na = __name__  # No error.\n__name__ = \"abc\"\n\n[case testUntypedDef]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\n\ndef f():\n    if int():\n        x = 0\n    z = y  # No used-before-def error because def is untyped.\n    y = x  # No possibly-undefined error because def is untyped.\n\n[case testUntypedDefCheckUntypedDefs]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def --check-untyped-defs\n\ndef f():\n    if int():\n        x = 0\n    z = y  # E: Name \"y\" is used before definition\n    y: int = x  # E: Name \"x\" may be undefined\n\n[case testClassBody]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def\n\nclass A:\n    # The following should not only trigger an error from semantic analyzer, but not the used-before-def check.\n    y = x + 1  # E: Name \"x\" is not defined\n    x = 0\n    # Same as above but in a loop, which should trigger a possibly-undefined error.\n    for _ in [1, 2, 3]:\n        b = a + 1  # E: Name \"a\" is not defined\n        a = 0\n\n\nclass B:\n    if int():\n        x = 0\n    else:\n        # This type of check is not caught by the semantic analyzer. If we ever update it to catch such issues,\n        # we should make sure that errors are not double-reported.\n        y = x  # E: Name \"x\" is used before definition\n    for _ in [1, 2, 3]:\n        if int():\n            a = 0\n        else:\n            # Same as above but in a loop.\n            b = a  # E: Name \"a\" may be undefined\n\n[case testUnreachableCausingMissingTypeMap]\n# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def --no-warn-unreachable\n# Regression test for https://github.com/python/mypy/issues/15958\nfrom typing import Union, NoReturn\n\ndef assert_never(__x: NoReturn) -> NoReturn: ...\n\ndef foo(x: Union[int, str]) -> None:\n    if isinstance(x, str):\n        f = \"foo\"\n    elif isinstance(x, int):\n        f = \"bar\"\n    else:\n        assert_never(x)\n    f  # OK\n[builtins fixtures/tuple.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[[MyHashable], 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[Union[int, P[Any, Any]], Union[P[Any, Any], str]]\") \\\n                                           # N: Following member(s) of \"C\" have conflicts: \\\n                                           # N:     attr1: expected \"Union[int, P[Any, Any]]\", got \"int\" \\\n                                           # N:     attr2: expected \"Union[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[Union[str, P[Any, Any]], Union[P[Any, Any], int]]\")\nmain:18: note: Following member(s) of \"C\" have conflicts:\nmain:18: note:     Expected:\nmain:18: note:         def attr1(self) -> Union[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) -> Union[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: This usage of this covariant type variable is unsafe as an input parameter. \\\n                                     # N: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\n        pass\n    def other(self) -> T_contra:  # E: This usage of this contravariant type variable is unsafe as a return type. \\\n                                  # N: If you are using the value in a 'variance safe' way (not storing or retrieving values), this error could be ignored\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: Union[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) -> Optional[int]\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: str) -> Optional[str]\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-- 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)  # E: \"f\" does not return a value (it only ever returns None)\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):\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 P1.attr2\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 \"Union[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 \"Union[C1, C2]\"; expected \"P1\"\nf1(y)\nf1(z)\nf2(x) # E: Argument 1 to \"f2\" has incompatible type \"Union[C1, C2]\"; expected \"P2\"\nf2(z) # E: Argument 1 to \"f2\" has incompatible type \"Union[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 = B # 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]\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) # Unreachable\nif isinstance(c, P):\n    reveal_type(c) # N: Revealed type is \"__main__.C\"\nelse:\n    reveal_type(c) # 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) # Unreachable\nif isinstance(c1i, P):\n    reveal_type(c1i) # N: Revealed type is \"__main__.C1[builtins.int] & __main__.P\"\nelse:\n    reveal_type(c1i) # N: Revealed type is \"__main__.C1[builtins.int]\"\n\nc1s: C1[str]\nif isinstance(c1s, P1):\n    reveal_type(c1s) # 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__.C2 & __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 \"Callable[[Arg(int, 'x')], 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 \"Callable[[int, VarArg(str)], int]\" \\\n                  # N: \"Bad1.__call__\" has type \"Callable[[Arg(int, 'x'), VarArg(int)], int]\"\ncall_soon(Bad2()) # E: Argument 1 to \"call_soon\" has incompatible type \"Bad2\"; expected \"Callable[[int, VarArg(str)], int]\" \\\n                  # N: \"Bad2.__call__\" has type \"Callable[[Arg(int, 'y'), VarArg(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 \"Optional[A]\"\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_extensions import Protocol\nfrom typing import Generic, 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: Optional[str] = ..., **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 \"Callable[[int, VarArg(str)], None]\"; expected \"Caller\" \\\n           # N: \"Caller.__call__\" has type \"Callable[[Arg(str, 'x'), VarArg(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 \"Callable[[Arg(T, 'x')], 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 \"Callable[[Arg(int, 'x')], 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[[Union[int, str]], Union[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 \"Callable[[int, VarArg(str)], None]\", variable has type \"Caller\") \\\n                  # N: \"Caller.__call__\" has type \"Callable[[Arg(str, 'x'), VarArg(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 \"Callable[[Arg(str, 'x')], 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: Following member(s) of \"Bad\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def __call__(self, x: str) -> None \\\n         # N:     Got: \\\n         # N:         def __call__(self, zzz: str) -> None \\\n         # N: \"One.__call__\" has type \"Callable[[Arg(str, 'x')], 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 SupportsInt, SupportsAbs, TypeVar\nfrom typing_extensions import Literal, Final\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_extensions 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: --nonlocal-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\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 --nonlocal-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: --nonlocal-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(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(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(Any, int, /) -> int \\\n         # N:         @overload \\\n         # N:         def foo(Any, 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(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(T, /) -> T \\\n         # N:     Got: \\\n         # N:         def [T] foo(self: T) -> Union[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 __init__(x: int, y: str) -> C \\\n         # N: \"P.__call__\" has type \"Callable[[Arg(int, 'x'), Arg(int, 'y')], 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 __init__(x: int, y: str) -> C \\\n         # N: \"P.__call__\" has type \"Callable[[Arg(int, 'x'), Arg(int, 'y')], 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 __init__(app: str) -> C \\\n          # N: \"P.__call__\" has type \"Callable[[Arg(int, 'app')], 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(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(T, /) -> T \\\n         # N:     Got: \\\n         # N:         def [T] foo(self: T) -> Union[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 \"Callable[[Arg(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 __init__(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 __init__(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_extensions 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 type argument 1 of \"f\"\n\ndef g4(a: Input[bytes], b: Output[str]) -> None:\n    f(a, b)  # E: Cannot infer type argument 1 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"
  },
  {
    "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]\nm: object\n\nmatch m:\n    case 1:\n        reveal_type(m)  # N: Revealed type is \"Literal[1]\"\n\n[case testMatchLiteralPatternAlreadyNarrower-skip]\nm: bool\n\nmatch m:\n    case 1:\n        reveal_type(m)  # This should probably be unreachable, but isn't detected as such.\n[builtins fixtures/primitives.pyi]\n\n[case testMatchLiteralPatternUnreachable]\n# primitives are needed because otherwise mypy doesn't see that int and str are incompatible\nm: int\n\nmatch m:\n    case \"str\":\n        reveal_type(m)\n[builtins fixtures/primitives.pyi]\n\n-- Value Pattern --\n\n[case testMatchValuePatternNarrows]\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]\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]\nimport b\n\nclass A: ...\nm: A\n\nmatch m:\n    case b.b:\n        reveal_type(m)  # N: Revealed type is \"__main__.A & b.B\"\n[file b.py]\nclass B: ...\nb: B\n\n[case testMatchValuePatternUnreachable]\n# primitives are needed because otherwise mypy doesn't see that int and str are incompatible\nimport b\n\nm: int\n\nmatch m:\n    case b.b:\n        reveal_type(m)\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[Union[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 testMatchSequencePatternWithInvalidClassPattern]\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]:  # E: Expected type in class pattern; found \"Type[__main__.Example]\"\n        reveal_type(value)  # E: Cannot determine type of \"value\" \\\n                            # N: Revealed type is \"Any\"\n        reveal_type(rest)  # N: Revealed type is \"builtins.list[__main__.Example]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequenceUnion-skip]\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# 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# 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)\n    case {b.b: v2}:\n        reveal_type(v2)\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-- Mapping patterns currently do not narrow --\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)  # E: Cannot determine type of \"y\" \\\n                        # N: Revealed type is \"Any\"\n\nmatch m:\n    case xyz(z=x):  # E: Name \"xyz\" is not defined\n        reveal_type(x)  # E: Cannot determine type of \"x\" \\\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 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__.B & __main__.A\"\n    case A(i, j):\n        reveal_type(m)  # N: Revealed type is \"__main__.B & __main__.A\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternNonexistentKeyword]\nclass A: ...\n\nm: object\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\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]\na = 1\nm: object\n\nmatch m:\n    case a(i, j):  # E: Expected type in class pattern; found \"builtins.int\"\n        reveal_type(i)\n        reveal_type(j)\n\n[case testMatchClassPatternAny]\nfrom typing import Any\n\nFoo: Any\nm: object\n\nmatch m:\n    case Foo():\n        pass\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 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 \"Union[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 \"Union[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 \"Union[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 \"Union[Literal[1], Literal['foo']]\"\n\n[case testMatchOrPatterCapturesMissing]\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.object\"\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 \"typing.Iterable[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 \"Union[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 \"Union[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-xfail]\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 \"Union[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 \"builtins.str & 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__.A & __main__.B\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testMatchUnreachablePatternGuard]\nm: str\n\nmatch m:\n    case a if isinstance(a, int):\n        reveal_type(a)\n[builtins fixtures/isinstancelist.pyi]\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.object\"\n        reveal_type(m)  # N: Revealed type is \"Union[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 Union, Sequence, Tuple\nfrom typing_extensions import Literal\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[Union[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[Union[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], Union[Literal['a'], Literal['b']]]\"\n    case _:\n        reveal_type(m5)  # N: Revealed type is \"Tuple[Literal[2], Union[Literal['a'], Literal['b']]]\"\n\nmatch m5:\n    case (1, \"a\"):\n        reveal_type(m5)  # N: Revealed type is \"Tuple[Literal[1], Literal['a']]\"\n    case _:\n        reveal_type(m5)  # N: Revealed type is \"Tuple[Union[Literal[1], Literal[2]], Union[Literal['a'], Literal['b']]]\"\n\n[builtins fixtures/tuple.pyi]\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            reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.gold]\"\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 \"Union[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\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-skip]\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 \"Literal[__main__.Medal.gold]\"\n    case _:\n        reveal_type(m)  # N: Revealed type is \"__main__.Medal\"\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 \"Union[builtins.str, Literal[False]]\"\n[builtins fixtures/tuple.pyi]\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-skip]\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__.A & __main__.B\"\n        case C() as y:\n            reveal_type(y)  # N: Revealed type is \"__main__.A & __main__.C\"\n    reveal_type(y)  # N: Revealed type is \"Union[__main__.A & __main__.B, __main__.A & __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 \"Union[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 testMatchUnionTwoTuplesNoCrash]\nvar: tuple[int, int] | tuple[str, str]\n\n# TODO: we can infer better here.\nmatch var:\n    case (42, a):\n        reveal_type(a)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    case (\"yes\", b):\n        reveal_type(b)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchNamedAndKeywordsAreTheSame]\nfrom typing import Generic, TypeVar, Union\nfrom typing_extensions import Final\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    match x := returns_a():\n        case A():\n            reveal_type(x.a)  # N: Revealed type is \"builtins.int\"\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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[str]\", 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 \"Optional[List[str]]\", 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 \"Optional[str]\", 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 \"Union[builtins.int, builtins.bytes]\"\n    return 0\n\n[builtins fixtures/primitives.pyi]\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[Union[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_extensions 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)  # N: Revealed type is \"def () -> Tuple[Literal['test']]\"\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 \"Union[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 \"Union[int, str]\", variable has type \"Callable[[], str]\")\n            pass\n[builtins fixtures/dict.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[Union[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[Union[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] __init__(self) -> MyClass[None, None] \\\n                                         # N:     def [T1, T2] __init__(self, Type[T1], /) -> MyClass[T1, None] \\\n                                         # N:     def [T1, T2] __init__(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://kotlinisland.github.io/basedmypy/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 \"Callable[[VarArg(int), NamedArg(int, 'y')], int]\", variable has type \"Callable[[VarArg(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"
  },
  {
    "path": "test-data/unit/check-python312.test",
    "content": "[case testPEP695TypeAliasBasic]\ntype MyInt = int\n\ndef f(x: MyInt) -> MyInt:\n    return reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ntype MyList[T] = list[T]\n\ndef g(x: MyList[int]) -> MyList[int]:\n    return reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\ntype MyInt2 = int\n\ndef h(x: MyInt2) -> MyInt2:\n    return reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695Class]\nclass MyGen[T]:\n    def __init__(self, x: T) -> None:\n        self.x = x\n\ndef f(x: MyGen[int]):\n    reveal_type(x.x)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695Function]\ndef f[T](x: T) -> T:\n    return reveal_type(x)  # N: Revealed type is \"T`-1\"\n\nreveal_type(f(1))  # N: Revealed type is \"builtins.int\"\n\nasync def g[T](x: T) -> T:\n    return reveal_type(x)  # N: Revealed type is \"T`-1\"\n\nreveal_type(g(1))  # E: Value of type \"Coroutine[Any, Any, int]\" must be used \\\n                   # N: Are you missing an await? \\\n                   # N: Revealed type is \"typing.Coroutine[Any, Any, builtins.int]\"\n\n[case testPEP695TypeVarBasic]\nfrom typing import Callable\ntype Alias1[T: int] = list[T]\ntype Alias2[**P] = Callable[P, int]\ntype Alias3[*Ts] = tuple[*Ts]\n\nclass Cls1[T: int]: ...\nclass Cls2[**P]: ...\nclass Cls3[*Ts]: ...\n\ndef func1[T: int](x: T) -> T: ...\ndef func2[**P](x: Callable[P, int]) -> Callable[P, str]: ...\ndef func3[*Ts](x: tuple[*Ts]) -> tuple[int, *Ts]: ...\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeAliasType]\nfrom typing import Callable, TypeAliasType, TypeVar, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\nTestType = TypeAliasType(\"TestType\", int | str)\nx: TestType = 42\ny: TestType = 'a'\nz: TestType = object()  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"Union[int, str]\")\n\nBadAlias1 = TypeAliasType(\"BadAlias1\", tuple[*Ts])  # E: TypeVarTuple \"Ts\" is not included in type_params\nba1: BadAlias1[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(ba1)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n\nBadAlias2 = TypeAliasType(\"BadAlias2\", Callable[[*Ts], str])  # E: TypeVarTuple \"Ts\" is not included in type_params\nba2: BadAlias2[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(ba2)  # N: Revealed type is \"def (*Any) -> builtins.str\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695IncompleteFeatureIsAcceptedButHasNoEffect]\n# mypy: enable-incomplete-feature=NewGenericSyntax\ndef f[T](x: T) -> T:\n    return x\nreveal_type(f(1))  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695GenericFunctionSyntax]\ndef ident[TV](x: TV) -> TV:\n    y: TV = x\n    y = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"TV\")\n    return x\n\nreveal_type(ident(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(ident('x'))  # N: Revealed type is \"builtins.str\"\n\na: TV  # E: Name \"TV\" is not defined\n\ndef tup[T, S](x: T, y: S) -> tuple[T, S]:\n    reveal_type((x, y))  # N: Revealed type is \"Tuple[T`-1, S`-2]\"\n    return (x, y)\n\nreveal_type(tup(1, 'x'))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695GenericClassSyntax]\nclass C[T]:\n    x: T\n\n    def __init__(self, x: T) -> None:\n        self.x = x\n\n    def ident(self, x: T) -> T:\n        y: T = x\n        if int():\n            return self.x\n        else:\n            return y\n\nreveal_type(C(\"x\"))  # N: Revealed type is \"__main__.C[builtins.str]\"\nc: C[int] = C(1)\nreveal_type(c.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.ident(1))  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695GenericMethodInGenericClass]\nclass C[T]:\n    def m[S](self, x: S) -> T | S: ...\n\na: C[int] = C[object]()  # E: Incompatible types in assignment (expression has type \"C[object]\", variable has type \"C[int]\")\nb: C[object] = C[int]()\n\nreveal_type(C[str]().m(1))  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n\n[case testPEP695InferVarianceSimpleFromMethod]\nclass Invariant[T]:\n    def f(self, x: T) -> None:\n        pass\n\n    def g(self) -> T | None:\n        return None\n\na: Invariant[object]\nb: Invariant[int]\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"Invariant[int]\", variable has type \"Invariant[object]\")\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"Invariant[object]\", variable has type \"Invariant[int]\")\n\nclass Covariant[T]:\n    def g(self) -> T | None:\n        return None\n\nc: Covariant[object]\nd: Covariant[int]\nif int():\n    c = d\nif int():\n    d = c  # E: Incompatible types in assignment (expression has type \"Covariant[object]\", variable has type \"Covariant[int]\")\n\nclass Contravariant[T]:\n    def f(self, x: T) -> None:\n        pass\n\ne: Contravariant[object]\nf: Contravariant[int]\nif int():\n    e = f  # E: Incompatible types in assignment (expression has type \"Contravariant[int]\", variable has type \"Contravariant[object]\")\nif int():\n    f = e\n\n[case testPEP695InferVarianceSimpleFromAttribute]\nclass Invariant1[T]:\n    def __init__(self, x: T) -> None:\n        self.x = x\n\na: Invariant1[object]\nb: Invariant1[int]\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"Invariant1[int]\", variable has type \"Invariant1[object]\")\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"Invariant1[object]\", variable has type \"Invariant1[int]\")\n\nclass Invariant2[T]:\n    def __init__(self) -> None:\n        self.x: list[T] = []\n\na2: Invariant2[object]\nb2: Invariant2[int]\nif int():\n    a2 = b2  # E: Incompatible types in assignment (expression has type \"Invariant2[int]\", variable has type \"Invariant2[object]\")\nif int():\n    b2 = a2  # E: Incompatible types in assignment (expression has type \"Invariant2[object]\", variable has type \"Invariant2[int]\")\n\nclass Invariant3[T]:\n    def __init__(self) -> None:\n        self.x: T | None = None\n\na3: Invariant3[object]\nb3: Invariant3[int]\nif int():\n    a3 = b3  # E: Incompatible types in assignment (expression has type \"Invariant3[int]\", variable has type \"Invariant3[object]\")\nif int():\n    b3 = a3  # E: Incompatible types in assignment (expression has type \"Invariant3[object]\", variable has type \"Invariant3[int]\")\n\n[case testPEP695InferVarianceRecursive]\nclass Invariant[T]:\n    def f(self, x: Invariant[T]) -> Invariant[T]:\n        return x\n\nclass Covariant[T]:\n    def f(self) -> Covariant[T]:\n        return self\n\nclass Contravariant[T]:\n    def f(self, x: Contravariant[T]) -> None:\n        pass\n\na: Invariant[object]\nb: Invariant[int]\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"Invariant[int]\", variable has type \"Invariant[object]\")\nif int():\n    b = a\n\nc: Covariant[object]\nd: Covariant[int]\nif int():\n    c = d\nif int():\n    d = c  # E: Incompatible types in assignment (expression has type \"Covariant[object]\", variable has type \"Covariant[int]\")\n\ne: Contravariant[object]\nf: Contravariant[int]\nif int():\n    e = f  # E: Incompatible types in assignment (expression has type \"Contravariant[int]\", variable has type \"Contravariant[object]\")\nif int():\n    f = e\n\n[case testPEP695InferVarianceInFrozenDataclass]\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Covariant[T]:\n    x: T\n\ncov1: Covariant[float] = Covariant[int](1)\ncov2: Covariant[int] = Covariant[float](1)  # E: Incompatible types in assignment (expression has type \"Covariant[float]\", variable has type \"Covariant[int]\")\n\n@dataclass(frozen=True)\nclass Invariant[T]:\n    x: list[T]\n\ninv1: Invariant[float] = Invariant[int]([1])  # E: Incompatible types in assignment (expression has type \"Invariant[int]\", variable has type \"Invariant[float]\")\ninv2: Invariant[int] = Invariant[float]([1])  # E: Incompatible types in assignment (expression has type \"Invariant[float]\", variable has type \"Invariant[int]\")\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695InferVarianceCalculateOnDemand]\nclass Covariant[T]:\n    def __init__(self) -> None:\n        self.x = [1]\n\n    def f(self) -> None:\n        c = Covariant[int]()\n        # We need to know that T is covariant here\n        self.g(c)\n        c2 = Covariant[object]()\n        self.h(c2)  # E: Argument 1 to \"h\" of \"Covariant\" has incompatible type \"Covariant[object]\"; expected \"Covariant[int]\"\n\n    def g(self, x: Covariant[object]) -> None: pass\n    def h(self, x: Covariant[int]) -> None: pass\n\n[case testPEP695InferVarianceNotReadyWhenNeeded]\nclass Covariant[T]:\n    def f(self) -> None:\n        c = Covariant[int]()\n        # We need to know that T is covariant here\n        self.g(c)\n        c2 = Covariant[object]()\n        self.h(c2)  # E: Argument 1 to \"h\" of \"Covariant\" has incompatible type \"Covariant[object]\"; expected \"Covariant[int]\"\n\n    def g(self, x: Covariant[object]) -> None: pass\n    def h(self, x: Covariant[int]) -> None: pass\n\n    def __init__(self) -> None:\n        self.x = [1]\n\nclass Invariant[T]:\n    def f(self) -> None:\n        c = Invariant(1)\n        # We need to know that T is invariant here, and for this we need the type\n        # of self.x, which won't be available on the first type checking pass,\n        # since __init__ is defined later in the file. In this case we fall back\n        # covariance.\n        self.g(c)\n        c2 = Invariant(object())\n        self.h(c2)  # E: Argument 1 to \"h\" of \"Invariant\" has incompatible type \"Invariant[object]\"; expected \"Invariant[int]\"\n\n    def g(self, x: Invariant[object]) -> None: pass\n    def h(self, x: Invariant[int]) -> None: pass\n\n    def __init__(self, x: T) -> None:\n        self.x = x\n\n# Now we should have the variance correct.\na: Invariant[object]\nb: Invariant[int]\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"Invariant[int]\", variable has type \"Invariant[object]\")\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"Invariant[object]\", variable has type \"Invariant[int]\")\n\n[case testPEP695InferVarianceNotReadyForJoin]\nclass Invariant[T]:\n    def f(self) -> None:\n        # Assume covariance if variance us not ready\n        reveal_type([Invariant(1), Invariant(object())]) \\\n            # N: Revealed type is \"builtins.list[__main__.Invariant[builtins.object]]\"\n\n    def __init__(self, x: T) -> None:\n        self.x = x\n\nreveal_type([Invariant(1), Invariant(object())])   # N: Revealed type is \"builtins.list[builtins.object]\"\n\n[case testPEP695InferVarianceNotReadyForMeet]\nfrom typing import TypeVar, Callable\n\nS = TypeVar(\"S\")\ndef c(a: Callable[[S], None], b: Callable[[S], None]) -> S: ...\n\ndef a1(x: Invariant[int]) -> None: pass\ndef a2(x: Invariant[object]) -> None: pass\n\nclass Invariant[T]:\n    def f(self) -> None:\n        reveal_type(c(a1, a2))  # N: Revealed type is \"__main__.Invariant[builtins.int]\"\n\n    def __init__(self, x: T) -> None:\n        self.x = x\n\nreveal_type(c(a1, a2))  # N: Revealed type is \"Never\"\n\n[case testPEP695InferVarianceUnderscorePrefix]\nclass Covariant1[T]:\n    def __init__(self, x: T) -> None:\n        self._x = x\n\n    @property\n    def x(self) -> T:\n        return self._x\n\nco1_1: Covariant1[float] = Covariant1[int](1)\nco1_2: Covariant1[int] = Covariant1[float](1)  # E: Incompatible types in assignment (expression has type \"Covariant1[float]\", variable has type \"Covariant1[int]\")\n\nclass Covariant2[T]:\n    def __init__(self, x: T) -> None:\n        self.__foo_bar = x\n\n    @property\n    def x(self) -> T:\n        return self.__foo_bar\n\nco2_1: Covariant2[float] = Covariant2[int](1)\nco2_2: Covariant2[int] = Covariant2[float](1)  # E: Incompatible types in assignment (expression has type \"Covariant2[float]\", variable has type \"Covariant2[int]\")\n\nclass Invariant1[T]:\n    def __init__(self, x: T) -> None:\n        self._x = x\n\n    # Methods behave differently from attributes\n    def _f(self, x: T) -> None: ...\n\n    @property\n    def x(self) -> T:\n        return self._x\n\ninv1_1: Invariant1[float] = Invariant1[int](1)  # E: Incompatible types in assignment (expression has type \"Invariant1[int]\", variable has type \"Invariant1[float]\")\ninv1_2: Invariant1[int] = Invariant1[float](1)  # E: Incompatible types in assignment (expression has type \"Invariant1[float]\", variable has type \"Invariant1[int]\")\n\nclass Invariant2[T]:\n    def __init__(self, x: T) -> None:\n        # Dunders are special\n        self.__x__ = x\n\n    @property\n    def x(self) -> T:\n        return self.__x__\n\ninv2_1: Invariant2[float] = Invariant2[int](1)  # E: Incompatible types in assignment (expression has type \"Invariant2[int]\", variable has type \"Invariant2[float]\")\ninv2_2: Invariant2[int] = Invariant2[float](1)  # E: Incompatible types in assignment (expression has type \"Invariant2[float]\", variable has type \"Invariant2[int]\")\n\nclass Invariant3[T]:\n    def __init__(self, x: T) -> None:\n        self._x = Invariant1(x)\n\n    @property\n    def x(self) -> T:\n        return self._x._x\n\ninv3_1: Invariant3[float] = Invariant3[int](1)  # E: Incompatible types in assignment (expression has type \"Invariant3[int]\", variable has type \"Invariant3[float]\")\ninv3_2: Invariant3[int] = Invariant3[float](1)  # E: Incompatible types in assignment (expression has type \"Invariant3[float]\", variable has type \"Invariant3[int]\")\n[builtins fixtures/property.pyi]\n\n[case testPEP695InferVarianceWithInheritedSelf]\nfrom typing import overload, Self, TypeVar, Generic\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass C(Generic[T]):\n    def f(self, x: T) -> Self: ...\n    def g(self) -> T: ...\n\nclass D[T1, T2](C[T1]):\n    def m(self, x: T2) -> None: ...\n\na1: D[int, int] = D[int, object]()\na2: D[int, object] = D[int, int]()  # E: Incompatible types in assignment (expression has type \"D[int, int]\", variable has type \"D[int, object]\")\na3: D[int, int] = D[object, object]()  # E: Incompatible types in assignment (expression has type \"D[object, object]\", variable has type \"D[int, int]\")\na4: D[object, int] = D[int, object]()  # E: Incompatible types in assignment (expression has type \"D[int, object]\", variable has type \"D[object, int]\")\n\n[case testPEP695InferVarianceWithReturnSelf]\nfrom typing import Self, overload\n\nclass Cov[T]:\n    def f(self) -> Self: ...\n\na1: Cov[int] = Cov[float]()  # E: Incompatible types in assignment (expression has type \"Cov[float]\", variable has type \"Cov[int]\")\na2: Cov[float] = Cov[int]()\n\nclass Contra[T]:\n    def f(self) -> Self: ...\n    def g(self, x: T) -> None: ...\n\nb1: Contra[int] = Contra[float]()\nb2: Contra[float] = Contra[int]()  # E: Incompatible types in assignment (expression has type \"Contra[int]\", variable has type \"Contra[float]\")\n\nclass Cov2[T]:\n    @overload\n    def f(self, x): ...\n    @overload\n    def f(self) -> Self: ...\n    def f(self, x=None): ...\n\nc1: Cov2[int] = Cov2[float]()  # E: Incompatible types in assignment (expression has type \"Cov2[float]\", variable has type \"Cov2[int]\")\nc2: Cov2[float] = Cov2[int]()\n\nclass Contra2[T]:\n    @overload\n    def f(self, x): ...\n    @overload\n    def f(self) -> Self: ...\n    def f(self, x=None): ...\n\n    def g(self, x: T) -> None: ...\n\nd1: Contra2[int] = Contra2[float]()\nd2: Contra2[float] = Contra2[int]()  # E: Incompatible types in assignment (expression has type \"Contra2[int]\", variable has type \"Contra2[float]\")\n\n[case testPEP695InheritInvariant]\nclass Invariant[T]:\n    x: T\n\nclass Subclass[T](Invariant[T]):\n    pass\n\nx: Invariant[int]\ny: Invariant[object]\nif int():\n    x = y  # E: Incompatible types in assignment (expression has type \"Invariant[object]\", variable has type \"Invariant[int]\")\nif int():\n    y = x  # E: Incompatible types in assignment (expression has type \"Invariant[int]\", variable has type \"Invariant[object]\")\n\na: Subclass[int]\nb: Subclass[object]\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"Subclass[object]\", variable has type \"Subclass[int]\")\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"Subclass[int]\", variable has type \"Subclass[object]\")\n\n[case testPEP695InheritanceMakesInvariant]\nclass Covariant[T]:\n    def f(self) -> T:\n        ...\n\nclass Subclass[T](Covariant[list[T]]):\n    pass\n\nx: Covariant[int] = Covariant[object]()  # E: Incompatible types in assignment (expression has type \"Covariant[object]\", variable has type \"Covariant[int]\")\ny: Covariant[object] = Covariant[int]()\n\na: Subclass[int] = Subclass[object]()  # E: Incompatible types in assignment (expression has type \"Subclass[object]\", variable has type \"Subclass[int]\")\nb: Subclass[object] = Subclass[int]()  # E: Incompatible types in assignment (expression has type \"Subclass[int]\", variable has type \"Subclass[object]\")\n\n[case testPEP695InheritCoOrContravariant]\nclass Contravariant[T]:\n    def f(self, x: T) -> None: pass\n\nclass CovSubclass[T](Contravariant[T]):\n    pass\n\na: CovSubclass[int] = CovSubclass[object]()\nb: CovSubclass[object] = CovSubclass[int]()  # E: Incompatible types in assignment (expression has type \"CovSubclass[int]\", variable has type \"CovSubclass[object]\")\n\nclass Covariant[T]:\n    def f(self) -> T: ...\n\nclass CoSubclass[T](Covariant[T]):\n    pass\n\nc: CoSubclass[int] = CoSubclass[object]()  # E: Incompatible types in assignment (expression has type \"CoSubclass[object]\", variable has type \"CoSubclass[int]\")\nd: CoSubclass[object] = CoSubclass[int]()\n\nclass InvSubclass[T](Covariant[T]):\n    def g(self, x: T) -> None: pass\n\ne: InvSubclass[int] = InvSubclass[object]()  # E: Incompatible types in assignment (expression has type \"InvSubclass[object]\", variable has type \"InvSubclass[int]\")\nf: InvSubclass[object] = InvSubclass[int]()  # E: Incompatible types in assignment (expression has type \"InvSubclass[int]\", variable has type \"InvSubclass[object]\")\n\n[case testPEP695FinalAttribute]\nfrom typing import Final\n\nclass C[T]:\n    def __init__(self, x: T) -> None:\n        self.x: Final = x\n\na: C[int] = C[object](1)  # E: Incompatible types in assignment (expression has type \"C[object]\", variable has type \"C[int]\")\nb: C[object] = C[int](1)\n\n[case testPEP695TwoTypeVariables]\nclass C[T, S]:\n    def f(self, x: T) -> None: ...\n    def g(self) -> S: ...\n\na: C[int, int] = C[object, int]()\nb: C[object, int] = C[int, int]()  # E: Incompatible types in assignment (expression has type \"C[int, int]\", variable has type \"C[object, int]\")\nc: C[int, int] = C[int, object]()  # E: Incompatible types in assignment (expression has type \"C[int, object]\", variable has type \"C[int, int]\")\nd: C[int, object] = C[int, int]()\n\n[case testPEP695Properties]\nclass R[T]:\n    @property\n    def p(self) -> T: ...\n\nclass RW[T]:\n    @property\n    def p(self) -> T: ...\n    @p.setter\n    def p(self, x: T) -> None: ...\n\na: R[int] = R[object]()  # E: Incompatible types in assignment (expression has type \"R[object]\", variable has type \"R[int]\")\nb: R[object] = R[int]()\nc: RW[int] = RW[object]()  # E: Incompatible types in assignment (expression has type \"RW[object]\", variable has type \"RW[int]\")\nd: RW[object] = RW[int]()  # E: Incompatible types in assignment (expression has type \"RW[int]\", variable has type \"RW[object]\")\n[builtins fixtures/property.pyi]\n\n[case testPEP695Protocol]\nfrom typing import Protocol\n\nclass PContra[T](Protocol):\n    def f(self, x: T) -> None: ...\n\nPContra()  # E: Cannot instantiate protocol class \"PContra\"\na: PContra[int]\nb: PContra[object]\nif int():\n    a = b\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"PContra[int]\", variable has type \"PContra[object]\")\n\nclass PCov[T](Protocol):\n    def f(self) -> T: ...\n\nPCov()  # E: Cannot instantiate protocol class \"PCov\"\nc: PCov[int]\nd: PCov[object]\nif int():\n    c = d  # E: Incompatible types in assignment (expression has type \"PCov[object]\", variable has type \"PCov[int]\")\nif int():\n    d = c\n\nclass PInv[T](Protocol):\n    def f(self, x: T) -> T: ...\n\nPInv()  # E: Cannot instantiate protocol class \"PInv\"\ne: PInv[int]\nf: PInv[object]\nif int():\n    e = f  # E: Incompatible types in assignment (expression has type \"PInv[object]\", variable has type \"PInv[int]\")\nif int():\n    f = e  # E: Incompatible types in assignment (expression has type \"PInv[int]\", variable has type \"PInv[object]\")\n\n[case testPEP695TypeAlias]\nclass C[T]: pass\nclass D[T, S]: pass\n\ntype A[S] = C[S]\n\na: A[int]\nreveal_type(a)  # N: Revealed type is \"__main__.C[builtins.int]\"\n\ntype A2[T] = C[C[T]]\na2: A2[str]\nreveal_type(a2)  # N: Revealed type is \"__main__.C[__main__.C[builtins.str]]\"\n\ntype A3[T, S] = D[S, C[T]]\na3: A3[int, str]\nreveal_type(a3)  # N: Revealed type is \"__main__.D[builtins.str, __main__.C[builtins.int]]\"\n\ntype A4 = int | str\na4: A4\nreveal_type(a4)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasNotValidAsBaseClass]\nfrom typing import TypeAlias\n\nimport m\n\ntype A1 = int\nclass Bad1(A1):  # E: Type alias defined using \"type\" statement not valid as base class\n    pass\n\ntype A2[T] = list[T]\nclass Bad2(A2[int]):  # E: Type alias defined using \"type\" statement not valid as base class\n    pass\n\nclass Bad3(m.A1):  # E: Type alias defined using \"type\" statement not valid as base class\n    pass\n\nclass Bad4(m.A2[int]):  # E: Type alias defined using \"type\" statement not valid as base class\n    pass\n\nB1 = int\nB2 = list\nB3: TypeAlias = int\nclass Good1(B1): pass\nclass Good2(B2[int]): pass\nclass Good3(list[A1]): pass\nclass Good4(list[A2[int]]): pass\nclass Good5(B3): pass\n\n[file m.py]\ntype A1 = str\ntype A2[T] = list[T]\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasWithUnusedTypeParams]\ntype A[T] = int\na: A[str]\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695TypeAliasForwardReference1]\ntype A[T] = C[T]\n\na: A[int]\nreveal_type(a)  # N: Revealed type is \"__main__.C[builtins.int]\"\n\nclass C[T]: pass\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasForwardReference2]\ntype X = C\ntype A = X\n\na: A\nreveal_type(a)  # N: Revealed type is \"__main__.C\"\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeAliasForwardReference3]\ntype X = D\ntype A = C[X]\n\na: A\nreveal_type(a)  # N: Revealed type is \"__main__.C[__main__.D]\"\n\nclass C[T]: pass\nclass D: pass\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasForwardReference4]\ntype A = C\n\nclass D(A):  # E: Type alias defined using \"type\" statement not valid as base class\n    pass\n\nclass C: pass\n\nx: C = D()\ny: D = C()  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\n\n[case testPEP695TypeAliasForwardReference5]\ntype A = str\ntype B[T] = C[T]\nclass C[T]: pass\na: A\nb: B[int]\nc: C[str]\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\nreveal_type(b)  # N: Revealed type is \"__main__.C[builtins.int]\"\nreveal_type(c)  # N: Revealed type is \"__main__.C[builtins.str]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasWithUndefineName]\ntype A[T] = XXX  # E: Name \"XXX\" is not defined\na: A[int]\nreveal_type(a)  # N: Revealed type is \"Any\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasInvalidType]\ntype A = int | 1  # E: Invalid type: try using Literal[1] instead?\n\na: A\nreveal_type(a)  # N: Revealed type is \"Union[builtins.int, Literal[1]]\"\ntype B = int + str  # E: Invalid type alias: expression is not a valid type\nb: B\nreveal_type(b)  # N: Revealed type is \"Any\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeAliasBoundForwardReference]\ntype B[T: Foo] = list[T]\nclass Foo: pass\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695UpperBound]\nclass D:\n    x: int\nclass E(D): pass\n\nclass C[T: D]: pass\n\na: C[D]\nb: C[E]\nreveal_type(a)  # N: Revealed type is \"__main__.C[__main__.D]\"\nreveal_type(b)  # N: Revealed type is \"__main__.C[__main__.E]\"\n\nc: C[int]  # E: Type argument \"int\" of \"C\" must be a subtype of \"D\"\n\ndef f[T: D](a: T) -> T:\n    reveal_type(a.x)  # N: Revealed type is \"builtins.int\"\n    return a\n\nreveal_type(f(D()))  # N: Revealed type is \"__main__.D\"\nreveal_type(f(E()))  # N: Revealed type is \"__main__.E\"\nf(1)  # E: Value of type variable \"T\" of \"f\" cannot be \"int\"\n\n[case testPEP695UpperBoundForwardReference1]\nclass C[T: D]: pass\n\na: C[D]\nb: C[E]\nreveal_type(a)  # N: Revealed type is \"__main__.C[__main__.D]\"\nreveal_type(b)  # N: Revealed type is \"__main__.C[__main__.E]\"\n\nc: C[int]  # E: Type argument \"int\" of \"C\" must be a subtype of \"D\"\n\nclass D: pass\nclass E(D): pass\n\n[case testPEP695UpperBoundForwardReference2]\ntype A = D\nclass C[T: A]: pass\n\nclass D: pass\nclass E(D): pass\n\na: C[D]\nb: C[E]\nreveal_type(a)  # N: Revealed type is \"__main__.C[__main__.D]\"\nreveal_type(b)  # N: Revealed type is \"__main__.C[__main__.E]\"\n\nc: C[int]  # E: Type argument \"int\" of \"C\" must be a subtype of \"D\"\n\n[case testPEP695UpperBoundForwardReference3]\nclass D[T]: pass\nclass E[T](D[T]): pass\n\ntype A = D[X]\n\nclass C[T: A]: pass\n\nclass X: pass\n\na: C[D[X]]\nb: C[E[X]]\nreveal_type(a)  # N: Revealed type is \"__main__.C[__main__.D[__main__.X]]\"\nreveal_type(b)  # N: Revealed type is \"__main__.C[__main__.E[__main__.X]]\"\n\nc: C[D[int]]  # E: Type argument \"D[int]\" of \"C\" must be a subtype of \"D[X]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695UpperBoundForwardReference4]\ndef f[T: D](a: T) -> T:\n    reveal_type(a.x)  # N: Revealed type is \"builtins.int\"\n    return a\n\nclass D:\n    x: int\nclass E(D): pass\n\nreveal_type(f(D()))  # N: Revealed type is \"__main__.D\"\nreveal_type(f(E()))  # N: Revealed type is \"__main__.E\"\nf(1)  # E: Value of type variable \"T\" of \"f\" cannot be \"int\"\n\n[case testPEP695UpperBoundUndefinedName]\nclass C[T: XX]:  # E: Name \"XX\" is not defined\n    pass\n\na: C[int]\n\ndef f[T: YY](x: T) -> T:  # E: Name \"YY\" is not defined\n    return x\nreveal_type(f)  # N: Revealed type is \"def [T <: Any] (x: T`-1) -> T`-1\"\n\n[case testPEP695UpperBoundWithMultipleParams]\nclass C[T, S: int]: pass\nclass D[A: int, B]: pass\n\ndef f[T: int, S: int | str](x: T, y: S) -> T | S:\n    return x\n\nC[str, int]()\nC[str, str]()  # E: Value of type variable \"S\" of \"C\" cannot be \"str\"\nD[int, str]()\nD[str, str]()  # E: Value of type variable \"A\" of \"D\" cannot be \"str\"\nf(1, 1)\nu: int | str\nf(1, u)\nf('x', None)  # E: Value of type variable \"T\" of \"f\" cannot be \"str\" \\\n              # E: Value of type variable \"S\" of \"f\" cannot be \"None\"\n\n[case testPEP695InferVarianceOfTupleType]\nclass Cov[T](tuple[int, str]):\n    def f(self) -> T: pass\n\nclass Cov2[T](tuple[T, T]):\n    pass\n\nclass Contra[T](tuple[int, str]):\n    def f(self, x: T) -> None: pass\n\na: Cov[object] = Cov[int]()\nb: Cov[int] = Cov[object]()  # E: Incompatible types in assignment (expression has type \"Cov[object]\", variable has type \"Cov[int]\")\n\nc: Cov2[object] = Cov2[int]()\nd: Cov2[int] = Cov2[object]()  # E: Incompatible types in assignment (expression has type \"Cov2[object]\", variable has type \"Cov2[int]\")\n\ne: Contra[int] = Contra[object]()\nf: Contra[object] = Contra[int]()  # E: Incompatible types in assignment (expression has type \"Contra[int]\", variable has type \"Contra[object]\")\n[builtins fixtures/tuple-simple.pyi]\n\n[case testPEP695ValueRestriction]\ndef f[T: (int, str)](x: T) -> T:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\" \\\n                    # N: Revealed type is \"builtins.str\"\n    return x\n\nreveal_type(f(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(f('x'))  # N: Revealed type is \"builtins.str\"\nf(None)  # E: Value of type variable \"T\" of \"f\" cannot be \"None\" \\\n         # N: \"T\" of \"f\" is a constrained type variable, it is not generic\n\nclass C[T: (object, None)]: pass\n\na: C[object]\nb: C[None]\nc: C[int]  # E: Value of type variable \"T\" of \"C\" cannot be \"int\" \\\n           # N: \"T\" of \"C\" is a constrained type variable, it is not generic\n\n[case testPEP695ValueRestrictionForwardReference]\nclass C[T: (int, D)]:\n    def __init__(self, x: T) -> None:\n        a = x\n        if int():\n            a = 'x'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\") \\\n                     # E: Incompatible types in assignment (expression has type \"str\", variable has type \"D\")\n        self.x: T = x\n\nreveal_type(C(1).x)  # N: Revealed type is \"builtins.int\"\nC(None)  # E: Value of type variable \"T\" of \"C\" cannot be \"None\" \\\n         # N: \"T\" of \"C\" is a constrained type variable, it is not generic\n\nclass D: pass\n\nC(D())\n\n[case testPEP695ValueRestrictionUndefinedName]\nclass C[T: (int, XX)]:  # E: Name \"XX\" is not defined\n    pass\n\ndef f[S: (int, YY)](x: S) -> S:  # E: Name \"YY\" is not defined\n    return x\n\n[case testPEP695ParamSpec]\nfrom typing import Callable\n\ndef g[**P](f: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None:\n    f(*args, **kwargs)\n    f(1, *args, **kwargs)  # E: Argument 1 has incompatible type \"int\"; expected \"P.args\"\n\ndef h(x: int, y: str) -> None: pass\n\ng(h, 1, y='x')\ng(h, 1, x=1)  # E: \"g\" gets multiple values for keyword argument \"x\" \\\n              # E: Missing positional argument \"y\" in call to \"g\"\n\nclass C[**P, T]:\n    def m(self, *args: P.args, **kwargs: P.kwargs) -> T: ...\n\na: C[[int, str], None]\nreveal_type(a)  # N: Revealed type is \"__main__.C[[builtins.int, builtins.str], None]\"\nreveal_type(a.m)  # N: Revealed type is \"def (builtins.int, builtins.str)\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695ParamSpecTypeAlias]\nfrom typing import Callable\n\ntype C[**P] = Callable[P, int]\n\nf: C[[str, int | None]]\nreveal_type(f)  # N: Revealed type is \"def (builtins.str, Union[builtins.int, None]) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeVarTuple]\ndef f[*Ts](t: tuple[*Ts]) -> tuple[*Ts]:\n    reveal_type(t)  # N: Revealed type is \"Tuple[Unpack[Ts`-1]]\"\n    return t\n\nreveal_type(f((1, 'x')))  # N: Revealed type is \"Tuple[Literal[1]?, Literal['x']?]\"\na: tuple[int, ...]\nreveal_type(f(a))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nclass C[T, *Ts]:\n    pass\n\nb: C[int, str, None]\nreveal_type(b)  # N: Revealed type is \"__main__.C[builtins.int, builtins.str, None]\"\nc: C[str]\nreveal_type(c)  # N: Revealed type is \"__main__.C[builtins.str]\"\nb = c  # E: Incompatible types in assignment (expression has type \"C[str]\", variable has type \"C[int, str, None]\")\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeVarTupleAlias]\nfrom typing import Callable\n\ntype C[*Ts] = tuple[*Ts, int]\n\na: C[str, None]\nreveal_type(a)  # N: Revealed type is \"Tuple[builtins.str, None, builtins.int]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695IncrementalFunction]\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nimport b\nreveal_type(b.f(1))\nreveal_type(b.g(1, 'x'))\nb.g('x', 'x')\nb.g(1, 2)\n\n[file b.py]\ndef f[T](x: T) -> T:\n    return x\n\ndef g[T: int, S: (str, None)](x: T, y: S) -> T | S:\n    return x\n\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.int\"\ntmp/a.py:3: note: Revealed type is \"Union[builtins.int, builtins.str]\"\ntmp/a.py:4: error: Value of type variable \"T\" of \"g\" cannot be \"str\"\ntmp/a.py:5: error: Value of type variable \"S\" of \"g\" cannot be \"int\"\ntmp/a.py:5: note: \"S\" of \"g\" is a constrained type variable, it is not generic\n\n[case testPEP695IncrementalClass]\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nfrom b import C, D\nx: C[int]\nreveal_type(x)\n\nclass N(int): pass\nclass SS(str): pass\n\ny1: D[int, str]\ny2: D[N, str]\ny3: D[int, None]\ny4: D[int, None]\ny5: D[int, SS]  # Error\ny6: D[object, str]  # Error\n\n[file b.py]\nclass C[T]: pass\n\nclass D[T: int, S: (str, None)]:\n    pass\n\n[out2]\ntmp/a.py:3: note: Revealed type is \"b.C[builtins.int]\"\ntmp/a.py:12: error: Value of type variable \"S\" of \"D\" cannot be \"SS\"\ntmp/a.py:12: note: \"S\" of \"D\" is a constrained type variable, it is not generic\ntmp/a.py:13: error: Type argument \"object\" of \"D\" must be a subtype of \"int\"\n\n[case testPEP695IncrementalParamSpecAndTypeVarTuple]\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nfrom b import C, D\nx1: C[()]\nx2: C[int]\nx3: C[int, str]\ny: D[[int, str]]\nreveal_type(y.m)\n\n[file b.py]\nclass C[*Ts]: pass\nclass D[**P]:\n    def m(self, *args: P.args, **kwargs: P.kwargs) -> None: pass\n\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:6: note: Revealed type is \"def (builtins.int, builtins.str)\"\n\n[case testPEP695IncrementalTypeAlias]\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nfrom b import A, B\na: A\nreveal_type(a)\nb: B[int]\nreveal_type(b)\n\n[file b.py]\ntype A = str\nclass Foo[T]: pass\ntype B[T] = Foo[T]\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n[out2]\ntmp/a.py:3: note: Revealed type is \"builtins.str\"\ntmp/a.py:5: note: Revealed type is \"b.Foo[builtins.int]\"\n\n[case testPEP695UndefinedNameInGenericFunction]\ndef f[T](x: T) -> T:\n    return unknown()  # E: Name \"unknown\" is not defined\n\nclass C:\n    def m[T](self, x: T) -> T:\n        return unknown()  # E: Name \"unknown\" is not defined\n\n[case testPEP695FunctionTypeVarAccessInFunction]\nfrom typing import cast\n\nclass C:\n    def m[T](self, x: T) -> T:\n        y: T = x\n        reveal_type(y)  # N: Revealed type is \"T`-1\"\n        return cast(T, y)\n\nreveal_type(C().m(1))  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695ScopingBasics]\nT = 1\n\ndef f[T](x: T) -> T:\n    T = 'a'\n    reveal_type(T)  # N: Revealed type is \"builtins.str\"\n    return x\n\nreveal_type(T)  # N: Revealed type is \"builtins.int\"\n\nclass C[T]:\n    T = 1.2\n    reveal_type(T)  # N: Revealed type is \"builtins.float\"\n\nreveal_type(T)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695ClassScoping]\nclass C:\n    class D: pass\n\n    def m[T: D](self, x: T, y: D) -> T:\n        return x\n\nC().m(C.D(), C.D())\nC().m(1, C.D())  # E: Value of type variable \"T\" of \"m\" of \"C\" cannot be \"int\"\n\n[case testPEP695NestedGenericFunction]\ndef f[T](x: T) -> T:\n    reveal_type(f(x))  # N: Revealed type is \"T`-1\"\n    reveal_type(f(1))  # N: Revealed type is \"builtins.int\"\n\n    def ff(x: T) -> T:\n        y: T = x\n        return y\n    reveal_type(ff(x))  # N: Revealed type is \"T`-1\"\n    ff(1)  # E: Argument 1 to \"ff\" has incompatible type \"int\"; expected \"T\"\n\n    def g[S](a: S) -> S:\n        ff(a)  # E: Argument 1 to \"ff\" has incompatible type \"S\"; expected \"T\"\n        return a\n    reveal_type(g(1))  # N: Revealed type is \"builtins.int\"\n    reveal_type(g(x))  # N: Revealed type is \"T`-1\"\n\n    def h[S](a: S) -> S:\n        return a\n    reveal_type(h(1))  # N: Revealed type is \"builtins.int\"\n    reveal_type(h(x))  # N: Revealed type is \"T`-1\"\n    return x\n\n[case testPEP695NonLocalAndGlobal]\ndef f() -> None:\n    T = 1\n    def g[T](x: T) -> T:\n        nonlocal T  # E: nonlocal binding not allowed for type parameter \"T\"\n        T = 'x'  # E: \"T\" is a type variable and only valid in type context\n        return x\n    reveal_type(T)  # N: Revealed type is \"builtins.int\"\n\ndef g() -> None:\n    a = 1\n    def g[T](x: T) -> T:\n        nonlocal a\n        a = 'x'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        return x\n\nx = 1\n\ndef h[T](a: T) -> T:\n    global x\n    x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    return a\n\nclass C[T]:\n    def m[S](self, a: S) -> S:\n        global x\n        x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        return a\n\n[case testPEP695ArgumentDefault]\nfrom typing import cast\n\ndef f[T](\n    x: T =\n        T  # E: Name \"T\" is not defined \\\n           # E: Incompatible default for argument \"x\" (default has type \"TypeVar\", argument has type \"T\")\n) -> T:\n    return x\n\ndef g[T](x: T = cast(T, None)) -> T:  # E: Name \"T\" is not defined\n    return x\n\nclass C:\n    def m[T](self, x: T = cast(T, None)) -> T:  # E: Name \"T\" is not defined\n        return x\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695ListComprehension]\nfrom typing import cast\n\ndef f[T](x: T) -> T:\n    b = [cast(T, a) for a in [1, 2]]\n    reveal_type(b)  # N: Revealed type is \"builtins.list[T`-1]\"\n    return x\n\n[case testPEP695ReuseNameInSameScope]\nclass C[T]:\n    def m[S](self, x: S, y: T) -> S | T:\n        return x\n\n    def m2[S](self, x: S, y: T) -> S | T:\n        return x\n\nclass D[T]:\n    pass\n\ndef f[T](x: T) -> T:\n    return x\n\ndef g[T](x: T) -> T:\n    def nested[S](y: S) -> S:\n        return y\n    def nested2[S](y: S) -> S:\n        return y\n    return x\n\n[case testPEP695NestedScopingSpecialCases]\n# This is adapted from PEP 695\nS = 0\n\ndef outer1[S]() -> None:\n    S = 1\n    T = 1\n\n    def outer2[T]() -> None:\n        def inner1() -> None:\n            nonlocal S\n            nonlocal T  # E: nonlocal binding not allowed for type parameter \"T\"\n\n        def inner2() -> None:\n            global S\n\n[case testPEP695ScopingWithBaseClasses]\n# This is adapted from PEP 695\nclass Outer:\n    class Private:\n        pass\n\n    # If the type parameter scope was like a traditional scope,\n    # the base class 'Private' would not be accessible here.\n    class Inner[T](Private, list[T]):\n        pass\n\n    # Likewise, 'Inner' would not be available in these type annotations.\n    def method1[T](self, a: Inner[T]) -> Inner[T]:\n        return a\n\n[case testPEP695RedefineTypeParameterInScope]\nclass C[T]:\n    def m[T](self, x: T) -> T:  # E: \"T\" already defined as a type parameter\n        return x\n    def m2(self) -> None:\n        def nested[T](x: T) -> T:  # E: \"T\" already defined as a type parameter\n            return x\n\ndef f[S, S](x: S) -> S:  # E: \"S\" already defined as a type parameter\n    return x\n\n[case testPEP695ClassDecorator]\nfrom typing import Any\n\nT = 0\n\ndef decorator(x: str) -> Any: ...\n\n@decorator(T)  # E: Argument 1 to \"decorator\" has incompatible type \"int\"; expected \"str\"\nclass C[T]:\n    pass\n\n[case testPEP695RecursiceTypeAlias]\ntype A = str | list[A]\na: A\nreveal_type(a)  # N: Revealed type is \"Union[builtins.str, builtins.list[...]]\"\n\nclass C[T]: pass\n\ntype B[T] = C[T] | list[B[T]]\nb: B[int]\nreveal_type(b)  # N: Revealed type is \"Union[__main__.C[builtins.int], builtins.list[...]]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695BadRecursiveTypeAlias]\ntype A = A  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n            # E: Cannot resolve name \"A\" (possible cyclic definition)\ntype B = B | int  # E: Invalid recursive alias: a union item of itself\na: A\nreveal_type(a)  # N: Revealed type is \"Any\"\nb: B\nreveal_type(b)  # N: Revealed type is \"Any\"\n[builtins fixtures/type.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695RecursiveTypeAliasForwardReference]\ndef f(a: A) -> None:\n    if isinstance(a, str):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"__main__.C[Union[builtins.str, __main__.C[...]]]\"\n\ntype A = str | C[A]\n\nclass C[T]: pass\n\nf('x')\nf(C[str]())\nf(C[C[str]]())\nf(1)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"A\"\nf(C[int]())  # E: Argument 1 to \"f\" has incompatible type \"C[int]\"; expected \"A\"\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695InvalidGenericOrProtocolBaseClass]\nfrom typing import Generic, Protocol, TypeVar\n\nS = TypeVar(\"S\")\n\nclass C[T](Generic[T]):  # E: Generic[...] base class is redundant\n    pass\nclass C2[T](Generic[S]): # E: Generic[...] base class is redundant\n    pass\n\na: C[int]\nb: C2[int, str]\n\nclass P[T](Protocol[T]):  # E: No arguments expected for \"Protocol\" base class\n    pass\nclass P2[T](Protocol[S]):  # E: No arguments expected for \"Protocol\" base class\n    pass\n\n[case testPEP695CannotUseTypeVarFromOuterClass]\nclass ClassG[V]:\n    # This used to crash\n    class ClassD[T: dict[str, V]]:  # E: Name \"V\" is not defined\n        ...\n[builtins fixtures/dict.pyi]\n\n[case testPEP695MixNewAndOldStyleGenerics]\nfrom typing import TypeVar\n\nS = TypeVar(\"S\")\nU = TypeVar(\"U\")\n\ndef f[T](x: T, y: S) -> T | S: ...  # E: All type parameters should be declared (\"S\" not declared)\ndef g[T](x: S, y: U) -> T | S | U: ...  # E: All type parameters should be declared (\"S\", \"U\" not declared)\n\ndef h[S: int](x: S) -> S:\n   a: int = x\n   return x\n\nclass C[T]:\n    def m[X, S](self, x: S, y: U) -> X | S | U: ...  # E: All type parameters should be declared (\"U\" not declared)\n    def m2(self, x: T, y: S) -> T | S: ...\n\nclass D[T](C[S]):  # E: All type parameters should be declared (\"S\" not declared)\n    pass\n\n[case testPEP695MixNewAndOldStyleTypeVarTupleAndParamSpec]\nfrom typing import TypeVarTuple, ParamSpec, Callable\nTs = TypeVarTuple(\"Ts\")\nP = ParamSpec(\"P\")\n\ndef f[T](x: T, f: Callable[P, None]  # E: All type parameters should be declared (\"P\" not declared)\n        ) -> Callable[P, T]: ...\ndef g[T](x: T, f: tuple[*Ts]  # E: All type parameters should be declared (\"Ts\" not declared)\n        ) -> tuple[T, *Ts]: ...\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695MixNewAndOldStyleGenericsInTypeAlias]\nfrom typing import TypeVar, ParamSpec, TypeVarTuple, Callable\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\nP = ParamSpec(\"P\")\n\ntype A = list[T]  # E: All type parameters should be declared (\"T\" not declared)\na: A[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(a)   # N: Revealed type is \"builtins.list[Any]\"\n\ntype B = tuple[*Ts]  # E: All type parameters should be declared (\"Ts\" not declared)\ntype C = Callable[P, None]  # E: All type parameters should be declared (\"P\" not declared)\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695NonGenericAliasToGenericClass]\nclass C[T]: pass\ntype A = C\nx: C\ny: A\nreveal_type(x)  # N: Revealed type is \"__main__.C[Any]\"\nreveal_type(y)  # N: Revealed type is \"__main__.C[Any]\"\nz: A[int]  # E: Bad number of arguments for type alias, expected 0, given 1\n\n[case testPEP695SelfType]\nfrom typing import Self\n\nclass C:\n    @classmethod\n    def m[T](cls, x: T) -> tuple[Self, T]:\n        return cls(), x\n\nclass D(C):\n    pass\n\nreveal_type(C.m(1))  # N: Revealed type is \"Tuple[__main__.C, builtins.int]\"\nreveal_type(D.m(1))  # N: Revealed type is \"Tuple[__main__.D, builtins.int]\"\n\nclass E[T]:\n    def m(self) -> Self:\n        return self\n\n    def mm[S](self, x: S) -> tuple[Self, S]:\n        return self, x\n\nclass F[T](E[T]):\n    pass\n\nreveal_type(E[int]().m())  # N: Revealed type is \"__main__.E[builtins.int]\"\nreveal_type(E[int]().mm(b'x'))  # N: Revealed type is \"Tuple[__main__.E[builtins.int], builtins.bytes]\"\nreveal_type(F[str]().m())  # N: Revealed type is \"__main__.F[builtins.str]\"\nreveal_type(F[str]().mm(b'x'))  # N: Revealed type is \"Tuple[__main__.F[builtins.str], builtins.bytes]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695CallAlias]\nclass C:\n    def __init__(self, x: str) -> None: ...\ntype A = C\n\nclass D[T]: pass\ntype B[T] = D[T]\n\nreveal_type(A)  # N: Revealed type is \"typing.TypeAliasType\"\nreveal_type(B)  # N: Revealed type is \"typing.TypeAliasType\"\nreveal_type(B[int])  # N: Revealed type is \"typing.TypeAliasType\"\n\nA(1)  # E: \"TypeAliasType\" not callable\nB[int]()  # E: \"TypeAliasType\" not callable\n\nA2 = C\nB2 = D\nA2(1)  # E: Argument 1 to \"C\" has incompatible type \"int\"; expected \"str\"\nB2[int]()\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695IncrementalTypeAliasKinds]\nimport a\n\n[file a.py]\nfrom b import A\n\n[file a.py.2]\nfrom b import A, B, C\nA()\nB()\nC()\n\n[file b.py]\nfrom typing_extensions import TypeAlias\ntype A = int\nB = int\nC: TypeAlias = int\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n[out2]\ntmp/a.py:2: error: \"TypeAliasType\" not callable\n\n[case testPEP695TypeAliasBoundAndValueChecking]\nfrom typing import Any, cast\n\nclass C: pass\nclass D(C): pass\n\ntype A[T: C] = list[T]\na1: A\nreveal_type(a1)  # N: Revealed type is \"builtins.list[Any]\"\na2: A[Any]\na3: A[C]\na4: A[D]\na5: A[object]  # E: Type argument \"object\" of \"A\" must be a subtype of \"C\"\na6: A[int]  # E: Type argument \"int\" of \"A\" must be a subtype of \"C\"\n\nx1 = cast(A[C], a1)\nx2 = cast(A[None], a1)  # E: Type argument \"None\" of \"A\" must be a subtype of \"C\"\n\ntype A2[T: (int, C)] = list[T]\nb1: A2\nreveal_type(b1)  # N: Revealed type is \"builtins.list[Any]\"\nb2: A2[Any]\nb3: A2[int]\nb4: A2[C]\nb5: A2[D]  # E: Value of type variable \"T\" of \"A2\" cannot be \"D\" \\\n           # N: \"T\" of \"A2\" is a constrained type variable, it is not generic\nb6: A2[object]  # E: Value of type variable \"T\" of \"A2\" cannot be \"object\" \\\n                # N: \"T\" of \"A2\" is a constrained type variable, it is not generic\n\nlist[A2[int]]()\nlist[A2[None]]()  # E: Invalid type argument value for \"A2\" \\\n                  # N: \"T\" of \"A2\" is a constrained type variable, it is not generic\n\nclass N(int): pass\n\ntype A3[T: C, S: (int, str)] = T | S\nc1: A3[C, int]\nc2: A3[D, str]\nc3: A3[C, N]  # E: Value of type variable \"S\" of \"A3\" cannot be \"N\" \\\n              # N: \"S\" of \"A3\" is a constrained type variable, it is not generic\nc4: A3[int, str]  # E: Type argument \"int\" of \"A3\" must be a subtype of \"C\"\n[builtins fixtures/type.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeAliasInClassBodyOrFunction]\nclass C:\n    type A = int\n    type B[T] = list[T] | None\n    a: A\n    b: B[str]\n\n    def method(self) -> None:\n        v: C.A\n        reveal_type(v)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(C.a)  # N: Revealed type is \"builtins.int\"\nreveal_type(C.b)  # N: Revealed type is \"Union[builtins.list[builtins.str], None]\"\n\nC.A = str  # E: Incompatible types in assignment (expression has type \"Type[str]\", variable has type \"TypeAliasType\")\n\nx: C.A\ny: C.B[int]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"Union[builtins.list[builtins.int], None]\"\n\ndef f() -> None:\n    type A = int\n    type B[T] = list[T] | None\n    a: A\n    reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    def g() -> None:\n        b: B[int]\n        reveal_type(b)  # N: Revealed type is \"Union[builtins.list[builtins.int], None]\"\n\nclass D:\n    def __init__(self) -> None:\n        type A = int\n        self.a: A = 0\n        type B[T] = list[T]\n        self.b: B[int] = [1]\n\nreveal_type(D().a)  # N: Revealed type is \"builtins.int\"\nreveal_type(D().b)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass E[T]:\n    type X = list[T]  # E: All type parameters should be declared (\"T\" not declared)\n\n    def __init__(self) -> None:\n        type A = list[T]  # E: All type parameters should be declared (\"T\" not declared)\n        self.a: A\n\nreveal_type(E[str]().a)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/type.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeAliasInvalidGenericConstraint]\nclass A[T]:\n    class a[S: (int, list[T])]: pass                # E: Name \"T\" is not defined\n    type b[S: (int, list[T])] = S                   # E: TypeVar constraint type cannot be parametrized by type variables\n    def c[S: (int, list[T])](self) -> None: ...     # E: TypeVar constraint type cannot be parametrized by type variables\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeAliasUnboundTypeVarConstraint]\nfrom typing import TypeVar\nT = TypeVar(\"T\")\nclass a[S: (int, list[T])]: pass                # 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)\ntype b[S: (int, list[T])] = S                   # 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)\ndef c[S: (int, list[T])](self) -> None: ...     # 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)\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695RedefineAsTypeAlias1]\nclass C: pass\ntype C = int  # E: Name \"C\" already defined on line 1\n\nA = 0\ntype A = str  # E: Name \"A\" already defined on line 4\nreveal_type(A)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP695RedefineAsTypeAlias2]\nfrom m import D\ntype D = int  # E: Name \"D\" already defined (possibly by an import)\na: D\nreveal_type(a)  # N: Revealed type is \"m.D\"\n[file m.py]\nclass D: pass\n\n[case testPEP695RedefineAsTypeAlias3]\nD = list[\"Forward\"]\ntype D = int  # E: Name \"D\" already defined on line 1\nForward = str\nx: D\nreveal_type(x)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695MultiDefinitionsForTypeAlias]\nif int():\n    type A[T] = list[T]\nelse:\n    type A[T] = str  # E: Name \"A\" already defined on line 2\nx: T  # E: Name \"T\" is not defined\na: A[int]\nreveal_type(a)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695UndefinedNameInAnnotation]\ndef f[T](x: foobar, y: T) -> T: ...  # E: Name \"foobar\" is not defined\nreveal_type(f)  # N: Revealed type is \"def [T] (x: Any, y: T`-1) -> T`-1\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695WrongNumberOfConstrainedTypes]\ntype A[T: ()] = list[T]  # E: Type variable must have at least two constrained types\na: A[int]\nreveal_type(a)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\ntype B[T: (int,)] = list[T]  # E: Type variable must have at least two constrained types\nb: B[str]\nreveal_type(b)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695UsingTypeVariableInOwnBoundOrConstraint]\ntype A[T: list[T]] = str  # E: Name \"T\" is not defined\ntype B[S: (list[S], str)] = str  # E: Name \"S\" is not defined\ntype C[T, S: list[T]] = str  # E: Name \"T\" is not defined\n\ndef f[T: T](x: T) -> T: ...  # E: Name \"T\" is not defined\nclass D[T: T]:  # E: Name \"T\" is not defined\n    pass\n\n[case testPEP695InvalidType]\ndef f[T: 1](x: T) -> T: ...  # E: Invalid type: try using Literal[1] instead?\nclass C[T: (int, (1 + 2))]: pass  # E: Invalid type comment or annotation\ntype A = list[1]  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead? \\\n                  # E: Invalid type: try using Literal[1] instead?\ntype B = (1 + 2)  # E: Invalid type alias: expression is not a valid type\na: A\nreveal_type(a)  # N: Revealed type is \"builtins.list[Literal[1]]\"\nb: B\nreveal_type(b)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695GenericNamedTuple]\nfrom typing import NamedTuple\n\n# Invariant because of the signature of the generated _replace method\nclass N[T](NamedTuple):\n    x: T\n    y: int\n\na: N[object]\nreveal_type(a.x)  # N: Revealed type is \"builtins.object\"\nb: N[int]\nreveal_type(b.x)  # N: Revealed type is \"builtins.int\"\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"N[int]\", variable has type \"N[object]\")\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"N[object]\", variable has type \"N[int]\")\n\nclass M[T: (int, str)](NamedTuple):\n    x: T\n\nc: M[int]\nd: M[str]\ne: M[bool]  # E: Value of type variable \"T\" of \"M\" cannot be \"bool\" \\\n            # N: \"T\" of \"M\" is a constrained type variable, it is not generic\n\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695GenericTypedDict]\nfrom typing import TypedDict\n\nclass D[T](TypedDict):\n    x: T\n    y: int\n\nclass E[T: str](TypedDict):\n    x: T\n    y: int\n\na: D[object]\nreveal_type(a[\"x\"])  # N: Revealed type is \"builtins.object\"\nb: D[int]\nreveal_type(b[\"x\"])  # N: Revealed type is \"builtins.int\"\nc: E[str]\nd: E[int]  # E: Type argument \"int\" of \"E\" must be a subtype of \"str\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testCurrentClassWorksAsBound]\nfrom typing import Protocol\n\nclass Comparable[T: Comparable](Protocol):\n    def compare(self, other: T) -> bool: ...\n\nclass Good:\n    def compare(self, other: Good) -> bool: ...\n\nx: Comparable[Good]\ny: Comparable[int]  # E: Type argument \"int\" of \"Comparable\" must be a subtype of \"Comparable[Any]\"\n\n[case testPEP695TypeAliasWithDifferentTargetTypes]\nimport types  # We need GenericAlias from here, and test stubs don't bring in 'types'\nfrom typing import Any, Callable, List, Literal, TypedDict\n\n# Test that various type expressions don't generate false positives as type alias\n# values, as they are type checked as expressions. There is a similar test case in\n# pythoneval.test that uses typeshed stubs.\n\nclass C[T]: pass\n\nclass TD(TypedDict):\n    x: int\n\ntype A1 = type[int]\ntype A2 = type[int] | None\ntype A3 = None | type[int]\ntype A4 = type[Any]\n\ntype B1[**P, R] = Callable[P, R] | None\ntype B2[**P, R] = None | Callable[P, R]\ntype B3 = Callable[[str], int]\ntype B4 = Callable[..., int]\n\ntype C1 = A1 | None\ntype C2 = None | A1\n\ntype D1 = Any | None\ntype D2 = None | Any\n\ntype E1 = List[int]\ntype E2 = List[int] | None\ntype E3 = None | List[int]\n\ntype F1 = Literal[1]\ntype F2 = Literal['x'] | None\ntype F3 = None | Literal[True]\n\ntype G1 = tuple[int, Any]\ntype G2 = tuple[int, Any] | None\ntype G3 = None | tuple[int, Any]\n\ntype H1 = TD\ntype H2 = TD | None\ntype H3 = None | TD\n\ntype I1 = C[int]\ntype I2 = C[Any] | None\ntype I3 = None | C[TD]\n[builtins fixtures/type.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypedDictInlineYesNewStyleAlias]\n# flags: --enable-incomplete-feature=InlineTypedDict\ntype X[T] = {\"item\": T, \"other\": X[T] | None}\nx: X[str]\nreveal_type(x)  # N: Revealed type is \"TypedDict({'item': builtins.str, 'other': Union[..., None]})\"\nif x[\"other\"] is not None:\n    reveal_type(x[\"other\"][\"item\"])  # N: Revealed type is \"builtins.str\"\n\ntype Y[T] = {\"item\": T, **Y[T]}  # E: Overwriting TypedDict field \"item\" while merging\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695UsingIncorrectExpressionsInTypeVariableBound]\ntype X[T: (yield 1)] = Any  # E: Yield expression cannot be used as a type variable bound\ntype Y[T: (yield from [])] = Any # E: Yield expression cannot be used as a type variable bound\ntype Z[T: (a := 1)] = Any  # E: Named expression cannot be used as a type variable bound\ntype K[T: (await 1)] = Any # E: Await expression cannot be used as a type variable bound\n\ntype XNested[T: (1 + (yield 1))] = Any  # E: Yield expression cannot be used as a type variable bound\ntype YNested[T: (1 + (yield from []))] = Any # E: Yield expression cannot be used as a type variable bound\ntype ZNested[T: (1 + (a := 1))] = Any  # E: Named expression cannot be used as a type variable bound\ntype KNested[T: (1 + (await 1))] = Any # E: Await expression cannot be used as a type variable bound\n\nclass FooX[T: (yield 1)]: pass  # E: Yield expression cannot be used as a type variable bound\nclass FooY[T: (yield from [])]: pass  # E: Yield expression cannot be used as a type variable bound\nclass FooZ[T: (a := 1)]: pass  # E: Named expression cannot be used as a type variable bound\nclass FooK[T: (await 1)]: pass  # E: Await expression cannot be used as a type variable bound\n\nclass FooXNested[T: (1 + (yield 1))]: pass  # E: Yield expression cannot be used as a type variable bound\nclass FooYNested[T: (1 + (yield from []))]: pass  # E: Yield expression cannot be used as a type variable bound\nclass FooZNested[T: (1 + (a := 1))]: pass  # E: Named expression cannot be used as a type variable bound\nclass FooKNested[T: (1 + (await 1))]: pass  # E: Await expression cannot be used as a type variable bound\n\ndef foox[T: (yield 1)](): pass  # E: Yield expression cannot be used as a type variable bound\ndef fooy[T: (yield from [])](): pass  # E: Yield expression cannot be used as a type variable bound\ndef fooz[T: (a := 1)](): pass  # E: Named expression cannot be used as a type variable bound\ndef fook[T: (await 1)](): pass  # E: Await expression cannot be used as a type variable bound\n\ndef foox_nested[T: (1 + (yield 1))](): pass  # E: Yield expression cannot be used as a type variable bound\ndef fooy_nested[T: (1 + (yield from []))](): pass  # E: Yield expression cannot be used as a type variable bound\ndef fooz_nested[T: (1 + (a := 1))](): pass  # E: Named expression cannot be used as a type variable bound\ndef fook_nested[T: (1 +(await 1))](): pass  # E: Await expression cannot be used as a type variable bound\n\n[case testPEP695UsingIncorrectExpressionsInTypeAlias]\ntype X = (yield 1)  # E: Yield expression cannot be used within a type alias\ntype Y = (yield from []) # E: Yield expression cannot be used within a type alias\ntype Z = (a := 1)  # E: Named expression cannot be used within a type alias\ntype K = (await 1)  # E: Await expression cannot be used within a type alias\n\ntype XNested = (1 + (yield 1))  # E: Yield expression cannot be used within a type alias\ntype YNested = (1 + (yield from [])) # E: Yield expression cannot be used within a type alias\ntype ZNested = (1 + (a := 1))  # E: Named expression cannot be used within a type alias\ntype KNested = (1 + (await 1))  # E: Await expression cannot be used within a type alias\n\n[case testPEP695TypeAliasAndAnnotated]\nfrom typing_extensions import Annotated, Annotated as _Annotated\nimport typing_extensions as t\n\ndef ann(*args): ...\n\ntype A = Annotated[int, ann()]\ntype B = Annotated[int | str, ann((1, 2))]\ntype C = _Annotated[int, ann()]\ntype D = t.Annotated[str, ann()]\n\nx: A\ny: B\nz: C\nzz: D\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(z)  # N: Revealed type is \"builtins.int\"\nreveal_type(zz)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695NestedGenericClass1]\nclass C[T]:\n    def f(self) -> T: ...\n\nclass A:\n    class B[Q]:\n        def __init__(self, a: Q) -> None:\n            self.a = a\n\n        def f(self) -> Q:\n            return self.a\n\n        def g(self, x: Q) -> None: ...\n\n    b: B[str]\n\nx: A.B[int]\nx.g(\"x\")  # E: Argument 1 to \"g\" of \"B\" has incompatible type \"str\"; expected \"int\"\nreveal_type(x.a)  # N: Revealed type is \"builtins.int\"\nreveal_type(x)  # N: Revealed type is \"__main__.A.B[builtins.int]\"\nreveal_type(A.b)  # N: Revealed type is \"__main__.A.B[builtins.str]\"\n\n[case testPEP695NestedGenericClass2]\nclass A:\n    def m(self) -> None:\n        class B[T]:\n            def f(self) -> T: ...\n        x: B[int]\n        reveal_type(x.f())  # N: Revealed type is \"builtins.int\"\n        self.a = B[str]()\n\nreveal_type(A().a)  # N: Revealed type is \"__main__.B@3[builtins.str]\"\nreveal_type(A().a.f())  # N: Revealed type is \"builtins.str\"\n\n[case testPEP695NestedGenericClass3]\nclass C[T]:\n    def f(self) -> T: ...\n    class D[S]:\n        x: T  # E: Name \"T\" is not defined\n        def g(self) -> S: ...\n\na: C[int]\nreveal_type(a.f())  # N: Revealed type is \"builtins.int\"\nb: C.D[str]\nreveal_type(b.g())  # N: Revealed type is \"builtins.str\"\n\nclass E[T]:\n    class F[T]:  # E: \"T\" already defined as a type parameter\n        x: T\n\nc: E.F[int]\n\n[case testPEP695NestedGenericClass4]\nclass A:\n    class B[T]:\n        def __get__(self, instance: A, owner: type[A]) -> T:\n            return None  # E: Incompatible return value type (got \"None\", expected \"T\")\n    f = B[int]()\n\na = A()\nv = a.f\n\n[case testPEP695VarianceInheritedFromBaseWithExplicitVariance]\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass ParentInvariant(Generic[T]):\n    pass\n\nclass Invariant1[T](ParentInvariant[T]):\n    pass\n\na1: Invariant1[int] = Invariant1[float]()  # E: Incompatible types in assignment (expression has type \"Invariant1[float]\", variable has type \"Invariant1[int]\")\na2: Invariant1[float] = Invariant1[int]()  # E: Incompatible types in assignment (expression has type \"Invariant1[int]\", variable has type \"Invariant1[float]\")\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\nclass ParentContravariant(Generic[T_contra]):\n    pass\n\nclass Contravariant[T](ParentContravariant[T]):\n    pass\n\nb1: Contravariant[int] = Contravariant[float]()\nb2: Contravariant[float] = Contravariant[int]()  # E: Incompatible types in assignment (expression has type \"Contravariant[int]\", variable has type \"Contravariant[float]\")\n\nclass Invariant2[T](ParentContravariant[T]):\n    def f(self) -> T: ...\n\nc1: Invariant2[int] = Invariant2[float]()  # E: Incompatible types in assignment (expression has type \"Invariant2[float]\", variable has type \"Invariant2[int]\")\nc2: Invariant2[float] = Invariant2[int]()  # E: Incompatible types in assignment (expression has type \"Invariant2[int]\", variable has type \"Invariant2[float]\")\n\nclass Multi[T, S](ParentInvariant[T], ParentContravariant[S]):\n    pass\n\nd1: Multi[int, str] = Multi[float, str]()  # E: Incompatible types in assignment (expression has type \"Multi[float, str]\", variable has type \"Multi[int, str]\")\nd2: Multi[float, str] = Multi[int, str]()  # E: Incompatible types in assignment (expression has type \"Multi[int, str]\", variable has type \"Multi[float, str]\")\nd3: Multi[str, int] = Multi[str, float]()\nd4: Multi[str, float] = Multi[str, int]()  # E: Incompatible types in assignment (expression has type \"Multi[str, int]\", variable has type \"Multi[str, float]\")\n\n[case testPEP695MultipleNestedGenericClass1]\n# flags: --enable-incomplete-feature=NewGenericSyntax\nclass A:\n    class B:\n        class C:\n            class D[Q]:\n                def g(self, x: Q): ...\n            d: D[str]\n\nx: A.B.C.D[int]\nx.g('a') # E: Argument 1 to \"g\" of \"D\" has incompatible type \"str\"; expected \"int\"\nreveal_type(x)  # N: Revealed type is \"__main__.A.B.C.D[builtins.int]\"\nreveal_type(A.B.C.d)  # N: Revealed type is \"__main__.A.B.C.D[builtins.str]\"\n\n[case testPEP695MultipleNestedGenericClass2]\n# flags: --enable-incomplete-feature=NewGenericSyntax\nclass A:\n    class B:\n        def m(self) -> None:\n            class C[T]:\n                def f(self) -> T: ...\n            x: C[int]\n            reveal_type(x.f())  # N: Revealed type is \"builtins.int\"\n            self.a = C[str]()\n\nreveal_type(A().B().a) # N: Revealed type is \"__main__.C@5[builtins.str]\"\n\n[case testPEP695MultipleNestedGenericClass3]\n# flags: --enable-incomplete-feature=NewGenericSyntax\nclass A:\n    class C[T]:\n        def f(self) -> T: ...\n        class D[S]:\n            x: T  # E: Name \"T\" is not defined\n            def g(self) -> S: ...\n\na: A.C[int]\nreveal_type(a.f())  # N: Revealed type is \"builtins.int\"\nb: A.C.D[str]\nreveal_type(b.g())  # N: Revealed type is \"builtins.str\"\n\nclass B:\n    class E[T]:\n        class F[T]:  # E: \"T\" already defined as a type parameter\n            x: T\n\nc: B.E.F[int]\n\n[case testPEP695MultipleNestedGenericClass4]\n# flags: --enable-incomplete-feature=NewGenericSyntax\nclass Z:\n    class A:\n        class B[T]:\n            def __get__(self, instance: Z.A, owner: type[Z.A]) -> T:\n                return None  # E: Incompatible return value type (got \"None\", expected \"T\")\n        f = B[int]()\n\na = Z.A()\nv = a.f\n\n[case testPEP695MultipleNestedGenericClass5]\n# flags: --enable-incomplete-feature=NewGenericSyntax\nfrom a.b.c import d\nx: d.D.E.F.G[int]\nx.g('a') # E: Argument 1 to \"g\" of \"G\" has incompatible type \"str\"; expected \"int\"\nreveal_type(x)  # N: Revealed type is \"a.b.c.d.D.E.F.G[builtins.int]\"\nreveal_type(d.D.E.F.d)  # N: Revealed type is \"a.b.c.d.D.E.F.G[builtins.str]\"\n\n[file a/b/c/d.py]\nclass D:\n    class E:\n        class F:\n            class G[Q]:\n                def g(self, x: Q): ...\n            d: G[str]\n\n[case testTypeAliasNormalization]\nfrom collections.abc import Callable\nfrom typing import Unpack\nfrom typing_extensions import TypeAlias\n\ntype RK_function_args = tuple[float, int]\ntype RK_functionBIS = Callable[[Unpack[RK_function_args], int], int]\n\ndef ff(a: float, b: int, c: int) -> int:\n    return 2\n\nbis: RK_functionBIS = ff\nres: int = bis(1.0, 2, 3)\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.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[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\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]: ...\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 \\\n                                    # E: Invalid type: try using Literal[2] instead?\nclass ClassP4[**P = [2, int]]: ...  # E: Invalid type: try using Literal[2] instead?\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: ...\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 \\\n                                       # E: Invalid type: try using Literal[2] instead?\ndef g4[**P = [2, int]]() -> None: ...  # E: Invalid type: try using Literal[2] instead?\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 subtype of the bound 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 \\\n                                              # E: Invalid type: try using Literal[2] instead?\ntype TB4[**P = [2, int]] = Callable[P, None]  # E: Invalid type: try using Literal[2] instead?\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/tuple.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"
  },
  {
    "path": "test-data/unit/check-python38.test",
    "content": "[case testDecoratedClassLine]\ndef d(c): ...\n@d\n\nclass C: ...\nclass C: ...  # E: Name \"C\" already defined on line 4\n\n[case testDecoratedFunctionLine]\n# flags: --disallow-untyped-defs\ndef d(f): ...  # type: ignore\n@d\n\ndef f(): ...  # E: Function is missing a return type annotation \\\n              # N: Use \"-> None\" if function does not return a value\n\n[case testIgnoreDecoratedFunction1]\n# flags: --disallow-untyped-defs --warn-unused-ignores\ndef d(f): ...  # type: ignore\n@d\n# type: ignore  # E: Unused \"type: ignore\" comment\ndef f(): ...  # type: ignore\n\n[case testIgnoreDecoratedFunction2]\n# flags: --disallow-untyped-defs\ndef d(f): ...  # type: ignore\n@d\n\ndef f(): ...  # type: ignore\n\n[case testIgnoreScopeIssue1032]\ndef f(a: int): ...\nf(\n    1,\n    2,\n)  # type: ignore\n\n[case testIgnoreScopeNested1]\ndef g(x: str) -> str: ...\ndef f(a: int) -> int: ...\nf(\n    f(\n        g(\n            \"IGNORE\"\n        )  # type: ignore\n    )\n)\n\n[case testIgnoreScopeNested2]\n[\n    \"IGNORE\"  # type: ignore\n    &\n    \"IGNORE\",\n]\n[builtins fixtures/list.pyi]\n\n[case testIgnoreScopeNested3]\n{\n    \"IGNORE\"\n    |  # type: ignore\n    \"IGNORE\",\n}\n[builtins fixtures/set.pyi]\n\n[case testIgnoreScopeNested4]\n{\n    None: \"IGNORE\"\n    ^\n    \"IGNORE\",  # type: ignore\n}\n[builtins fixtures/dict.pyi]\n\n[case testIgnoreScopeNestedNonOverlapping]\ndef f(x: int): ...\ndef g(x: int): ...\n(\n    f(\"ERROR\"),  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n    g(\"IGNORE\"),  # type: ignore\n    f(\"ERROR\"),  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n)\n[builtins fixtures/tuple.pyi]\n\n[case testIgnoreScopeNestedOverlapping]\ndef f(x: int): ...\ndef g(x: int): ...\n(\n    f(\"ERROR\"), g(  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n        \"IGNORE\"  # type: ignore\n    ), f(\"ERROR\"),  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n)\n[builtins fixtures/tuple.pyi]\n\n[case testIgnoreScopeUnused1]\n# flags: --warn-unused-ignores\n(  # type: ignore  # E: Unused \"type: ignore\" comment\n    \"IGNORE\"  # type: ignore  # E: Unused \"type: ignore\" comment\n    +  # type: ignore  # E: Unused \"type: ignore\" comment\n    0  # type: ignore\n)  # type: ignore  # E: Unused \"type: ignore\" comment\n[builtins fixtures/primitives.pyi]\n\n[case testIgnoreScopeUnused2]\n# flags: --warn-unused-ignores\n(  # type: ignore  # E: Unused \"type: ignore\" comment\n    \"IGNORE\"\n    -  # type: ignore\n    0  # type: ignore  # E: Unused \"type: ignore\" comment\n)  # type: ignore  # E: Unused \"type: ignore\" comment\n\n[case testIgnoreScopeUnused3]\n# flags: --warn-unused-ignores\n(  # type: ignore  # E: Unused \"type: ignore\" comment\n    \"IGNORE\"\n    /\n    0  # type: ignore\n)  # type: ignore  # E: Unused \"type: ignore\" comment\n\n[case testPEP570ArgTypesMissing]\n# flags: --disallow-untyped-defs\ndef f(arg, /) -> None: ...  # E: Function is missing a type annotation for one or more arguments\n\n[case testPEP570ArgTypesBadDefault]\ndef f(arg: int = \"ERROR\", /) -> None: ...  # E: Incompatible default for argument \"arg\" (default has type \"str\", argument has type \"int\")\n\n[case testPEP570ArgTypesDefault]\ndef f(arg: int = 0, /) -> None:\n    reveal_type(arg)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP570ArgTypesRequired]\ndef f(arg: int, /) -> None:\n    reveal_type(arg)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP570Required]\ndef f(arg: int, /) -> None: ...  # N: \"f\" defined here\nf(1)\nf(\"ERROR\")  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\nf(arg=1)  # E: Unexpected keyword argument \"arg\" for \"f\"\nf(arg=\"ERROR\")  # E: Unexpected keyword argument \"arg\" for \"f\"\n\n[case testPEP570Default]\ndef f(arg: int = 0, /) -> None: ...  # N: \"f\" defined here\nf()\nf(1)\nf(\"ERROR\")  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\nf(arg=1)  # E: Unexpected keyword argument \"arg\" for \"f\"\nf(arg=\"ERROR\")  # E: Unexpected keyword argument \"arg\" for \"f\"\n\n[case testPEP570Calls]\n# flags: --no-strict-optional\nfrom typing import Any, Dict\ndef f(p, /, p_or_kw, *, kw) -> None: ...  # N: \"f\" defined here\nd = None # type: Dict[Any, Any]\nf(0, 0, 0)  # E: Too many positional arguments for \"f\"\nf(0, 0, kw=0)\nf(0, p_or_kw=0, kw=0)\nf(p=0, p_or_kw=0, kw=0)  # E: Unexpected keyword argument \"p\" for \"f\"\nf(0, **d)\nf(**d)  # E: Missing positional argument \"p_or_kw\" in call to \"f\"\n[builtins fixtures/dict.pyi]\n\n[case testPEP570Signatures1]\ndef f(p1: bytes, p2: float, /, p_or_kw: int, *, kw: str) -> None:\n    reveal_type(p1)  # N: Revealed type is \"builtins.bytes\"\n    reveal_type(p2)  # N: Revealed type is \"builtins.float\"\n    reveal_type(p_or_kw)  # N: Revealed type is \"builtins.int\"\n    reveal_type(kw)  # N: Revealed type is \"builtins.str\"\n\n[case testPEP570Signatures2]\ndef f(p1: bytes, p2: float = 0.0, /, p_or_kw: int = 0, *, kw: str) -> None:\n    reveal_type(p1)  # N: Revealed type is \"builtins.bytes\"\n    reveal_type(p2)  # N: Revealed type is \"builtins.float\"\n    reveal_type(p_or_kw)  # N: Revealed type is \"builtins.int\"\n    reveal_type(kw)  # N: Revealed type is \"builtins.str\"\n\n[case testPEP570Signatures3]\ndef f(p1: bytes, p2: float = 0.0, /, *, kw: int) -> None:\n    reveal_type(p1)  # N: Revealed type is \"builtins.bytes\"\n    reveal_type(p2)  # N: Revealed type is \"builtins.float\"\n    reveal_type(kw)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP570Signatures4]\ndef f(p1: bytes, p2: int = 0, /) -> None:\n    reveal_type(p1)  # N: Revealed type is \"builtins.bytes\"\n    reveal_type(p2)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP570Signatures5]\ndef f(p1: bytes, p2: float, /, p_or_kw: int) -> None:\n    reveal_type(p1)  # N: Revealed type is \"builtins.bytes\"\n    reveal_type(p2)  # N: Revealed type is \"builtins.float\"\n    reveal_type(p_or_kw)  # N: Revealed type is \"builtins.int\"\n\n[case testPEP570Signatures6]\ndef f(p1: bytes, p2: float, /) -> None:\n    reveal_type(p1)  # N: Revealed type is \"builtins.bytes\"\n    reveal_type(p2)  # N: Revealed type is \"builtins.float\"\n\n[case testPEP570Unannotated]\ndef f(arg, /): ...  # N: \"f\" defined here\ng = lambda arg, /: arg\ndef h(arg=0, /): ...  # N: \"h\" defined here\ni = lambda arg=0, /: arg\n\nf(1)\ng(1)\nh()\nh(1)\ni()\ni(1)\nf(arg=0)  # E: Unexpected keyword argument \"arg\" for \"f\"\ng(arg=0)  # E: Unexpected keyword argument \"arg\"\nh(arg=0)  # E: Unexpected keyword argument \"arg\" for \"h\"\ni(arg=0)  # E: Unexpected keyword argument \"arg\"\n\n[case testWalrus]\nfrom typing import NamedTuple, Optional, List\nfrom typing_extensions import Final\n\nif a := 2:\n    reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\nwhile b := \"x\":\n    reveal_type(b)  # N: Revealed type is \"builtins.str\"\n\nl = [y2 := 1, y2 + 2, y2 + 3]\nreveal_type(y2)  # N: Revealed type is \"builtins.int\"\nreveal_type(l)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nfiltered_data = [y3 for x in l if (y3 := a) is not None]\nreveal_type(filtered_data)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(y3)  # N: Revealed type is \"builtins.int\"\n\nd = {'a': (a2 := 1), 'b': a2 + 1, 'c': a2 + 2}\nreveal_type(d)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\nreveal_type(a2)  # N: Revealed type is \"builtins.int\"\n\nd2 = {(prefix := 'key_') + 'a': (start_val := 1), prefix + 'b': start_val + 1, prefix + 'c': start_val + 2}\nreveal_type(d2)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\nreveal_type(prefix)  # N: Revealed type is \"builtins.str\"\nreveal_type(start_val)  # N: Revealed type is \"builtins.int\"\n\nfiltered_dict = {k: new_v for k, v in [('a', 1), ('b', 2), ('c', 3)] if (new_v := v + 1) == 2}\nreveal_type(filtered_dict)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\nreveal_type(new_v)  # N: Revealed type is \"builtins.int\"\n\ndef f(x: int = (c := 4)) -> int:\n    if a := 2:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    while b := \"x\":\n        reveal_type(b)  # N: Revealed type is \"builtins.str\"\n\n    x = (y := 1) + (z := 2)\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\n    reveal_type(z)  # N: Revealed type is \"builtins.int\"\n\n    l = [y2 := 1, y2 + 2, y2 + 3]\n    reveal_type(y2)  # N: Revealed type is \"builtins.int\"\n    reveal_type(l)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n    filtered_data = [y3 for x in l if (y3 := a) is not None]\n    reveal_type(filtered_data)  # N: Revealed type is \"builtins.list[builtins.int]\"\n    reveal_type(y3)  # N: Revealed type is \"builtins.int\"\n\n    d = {'a': (a2 := 1), 'b': a2 + 1, 'c': a2 + 2}\n    reveal_type(d)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n    reveal_type(a2)  # N: Revealed type is \"builtins.int\"\n\n    d2 = {(prefix := 'key_') + 'a': (start_val := 1), prefix + 'b': start_val + 1, prefix + 'c': start_val + 2}\n    reveal_type(d2)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n    reveal_type(prefix)  # N: Revealed type is \"builtins.str\"\n    reveal_type(start_val)  # N: Revealed type is \"builtins.int\"\n\n    filtered_dict = {k: new_v for k, v in [('a', 1), ('b', 2), ('c', 3)] if (new_v := v + 1) == 2}\n    reveal_type(filtered_dict)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n    reveal_type(new_v)  # N: Revealed type is \"builtins.int\"\n\n    # https://www.python.org/dev/peps/pep-0572/#exceptional-cases\n    (y4 := 3)\n    reveal_type(y4)  # N: Revealed type is \"builtins.int\"\n\n    y5 = (y6 := 3)\n    reveal_type(y5)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y6)  # N: Revealed type is \"builtins.int\"\n\n    f(x=(y7 := 3))\n    reveal_type(y7)  # N: Revealed type is \"builtins.int\"\n\n    reveal_type((lambda: (y8 := 3) and y8)())  # N: Revealed type is \"builtins.int\"\n    y8  # E: Name \"y8\" is not defined\n\n    y7 = 1.0  # E: Incompatible types in assignment (expression has type \"float\", variable has type \"int\")\n    if y7 := \"x\":  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        pass\n\n    # Just make sure we don't crash on this sort of thing.\n    if NT := NamedTuple(\"NT\", [(\"x\", int)]):  # E: \"int\" not callable\n        z2: NT  # E: Variable \"NT\" is not valid as a type \\\n                # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n    if Alias := int:  # E: Function \"Alias\" could always be true in boolean context\n        z3: Alias  # E: Variable \"Alias\" is not valid as a type \\\n                   # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n    if (reveal_type(y9 := 3) and   # N: Revealed type is \"Literal[3]?\"\n            reveal_type(y9)):       # N: Revealed type is \"builtins.int\"\n        reveal_type(y9)            # N: Revealed type is \"builtins.int\"\n\n    return (y10 := 3) + y10\n\nreveal_type(c)  # N: Revealed type is \"builtins.int\"\n\ndef check_final() -> None:\n    x: Final = 3\n\n    if x := 4:  # E: Cannot assign to final name \"x\"\n        pass\n\ndef check_binder(x: Optional[int], y: Optional[int], z: Optional[int], a: Optional[int],\n                 b: Optional[int]) -> None:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, None]\"\n\n    (x := 1)\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n    if x or (y := 1):\n        reveal_type(y)  # N: Revealed type is \"Union[builtins.int, None]\"\n\n    if x and (y := 1):\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\n    if (a := 1) and x:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n    if (b := 1) or x:\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n    if z := 1:\n        reveal_type(z)  # N: Revealed type is \"builtins.int\"\n\ndef check_partial() -> None:\n    x = None\n    if bool() and (x := 2):\n        pass\n\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, None]\"\n\ndef check_narrow(x: Optional[int], s: List[int]) -> None:\n    if (y := x):\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\n    if (y := x) is not None:\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\n    if (y := x) == 10:\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\n    if (y := x) in s:\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\n    if isinstance((y := x), int):\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\nclass AssignmentExpressionsClass:\n    x = (y := 1) + (z := 2)\n    reveal_type(z)  # N: Revealed type is \"builtins.int\"\n\n    l = [x2 := 1, 2, 3]\n    reveal_type(x2)  # N: Revealed type is \"builtins.int\"\n\n    def __init__(self) -> None:\n        reveal_type(self.z)  # N: Revealed type is \"builtins.int\"\n\n        l = [z2 := 1, z2 + 2, z2 + 3]\n        reveal_type(z2)  # N: Revealed type is \"builtins.int\"\n        reveal_type(l)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n        filtered_data = [z3 for x in l if (z3 := 1) is not None]\n        reveal_type(filtered_data)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(z3)  # N: Revealed type is \"builtins.int\"\n\n# Assignment expressions from inside the class should not escape the class scope.\nreveal_type(x2)  # E: Name \"x2\" is not defined  # N: Revealed type is \"Any\"\nreveal_type(z2)  # E: Name \"z2\" is not defined  # N: Revealed type is \"Any\"\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testWalrusConditionalTypeBinder]\nfrom typing import Tuple, Union\nfrom typing_extensions import Literal\n\nclass Good:\n    @property\n    def is_good(self) -> Literal[True]: ...\n\nclass Bad:\n    @property\n    def is_good(self) -> Literal[False]: ...\n\ndef get_thing() -> Union[Good, Bad]: ...\n\nif (thing := get_thing()).is_good:\n    reveal_type(thing)  # N: Revealed type is \"__main__.Good\"\nelse:\n    reveal_type(thing)  # N: Revealed type is \"__main__.Bad\"\n\ndef get_things() -> Union[Tuple[Good], Tuple[Bad]]: ...\n\nif (things := get_things())[0].is_good:\n    reveal_type(things)  # N: Revealed type is \"Tuple[__main__.Good]\"\nelse:\n    reveal_type(things)  # N: Revealed type is \"Tuple[__main__.Bad]\"\n[builtins fixtures/list.pyi]\n\n[case testWalrusConditionalTypeCheck]\nfrom typing import Optional\n\nmaybe_str: Optional[str]\n\nif (is_str := maybe_str is not None):\n    reveal_type(is_str)  # N: Revealed type is \"Literal[True]\"\n    reveal_type(maybe_str)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(is_str)  # N: Revealed type is \"Literal[False]\"\n    reveal_type(maybe_str)  # N: Revealed type is \"None\"\n\nreveal_type(maybe_str)  # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/bool.pyi]\n\n[case testWalrusConditionalTypeCheck2]\nfrom typing import Optional\n\nmaybe_str: Optional[str]\n\nif (x := maybe_str) is not None:\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(maybe_str)  # N: Revealed type is \"Union[builtins.str, None]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"None\"\n    reveal_type(maybe_str)  # N: Revealed type is \"Union[builtins.str, None]\"\n\nreveal_type(maybe_str)  # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/bool.pyi]\n\n[case testWalrusPartialTypes]\nfrom typing import List\n\ndef check_partial_list() -> None:\n    if (x := []):  # E: Need type annotation for \"x\" (hint: \"x: List[<type>] = ...\")\n        pass\n\n    y: List[str]\n    if (y := []):\n        pass\n\n    if (z := []):\n        z.append(3)\n    reveal_type(z)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testWalrusAssignmentAndConditionScopeForLiteral]\n# flags: --warn-unreachable\n\nif (x := 0):\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[0]\"\n\nreveal_type(x)  # N: Revealed type is \"Literal[0]\"\n\n[case testWalrusAssignmentAndConditionScopeForProperty]\n# flags: --warn-unreachable\n\nfrom typing_extensions import Literal\n\nclass PropertyWrapper:\n    @property\n    def f(self) -> str: ...\n    @property\n    def always_false(self) -> Literal[False]: ...\n\nwrapper = PropertyWrapper()\n\nif x := wrapper.f:\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal['']\"\n\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n\nif y := wrapper.always_false:\n    reveal_type(y)  # E: Statement is unreachable\nelse:\n    reveal_type(y)  # N: Revealed type is \"Literal[False]\"\n\nreveal_type(y)  # N: Revealed type is \"Literal[False]\"\n[builtins fixtures/property.pyi]\n\n[case testWalrusAssignmentAndConditionScopeForFunction]\n# flags: --warn-unreachable\n\nfrom typing_extensions import Literal\n\ndef f() -> str: ...\n\nif x := f():\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal['']\"\n\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef always_false() -> Literal[False]: ...\n\nif y := always_false():\n    reveal_type(y)  # E: Statement is unreachable\nelse:\n    reveal_type(y)  # N: Revealed type is \"Literal[False]\"\n\nreveal_type(y)  # N: Revealed type is \"Literal[False]\"\n\ndef always_false_with_parameter(x: int) -> Literal[False]: ...\n\nif z := always_false_with_parameter(5):\n    reveal_type(z)  # E: Statement is unreachable\nelse:\n    reveal_type(z)  # N: Revealed type is \"Literal[False]\"\n\nreveal_type(z)  # N: Revealed type is \"Literal[False]\"\n[builtins fixtures/tuple.pyi]\n\n[case testWalrusExpr]\ndef func() -> None:\n    foo = Foo()\n    if x := foo.x:\n        pass\n\nclass Foo:\n    def __init__(self) -> None:\n        self.x = 123\n\n[case testWalrusTypeGuard]\nfrom typing_extensions import TypeGuard\ndef is_float(a: object) -> TypeGuard[float]: pass\ndef 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[builtins fixtures/tuple.pyi]\n\n[case testWalrusRedefined]\ndef foo() -> None:\n    x = 0\n    [x := x + y for y in [1, 2, 3]]\n[builtins fixtures/dict.pyi]\n\n[case testWalrusUsedBeforeDef]\nclass C:\n    def f(self, c: 'C') -> None: pass\n\n(x := C()).f(y)  # E: Cannot determine type of \"y\"  # E: Name \"y\" is used before definition\n(y := C()).f(y)\n\n[case testOverloadWithPositionalOnlySelf]\nfrom typing import overload, Optional\n\nclass Foo:\n    @overload\n    def f(self, a: str, /) -> None: ...\n\n    @overload\n    def f(self, *, b: bool = False) -> None: ...\n\n    def f(self, a: Optional[str] = None, /, *, b: bool = False) -> None:  # E: Overloaded function implementation does not accept all possible arguments of signature 2\n        ...\n\nclass Bar:\n    @overload\n    def f(self, a: str, /) -> None: ...\n\n    @overload  # Notice `/` in sig below:\n    def f(self, /, *, b: bool = False) -> None: ...\n\n    def f(self, a: Optional[str] = None, /, *, b: bool = False) -> None:\n        ...\n[builtins fixtures/bool.pyi]\n\n[case testOverloadPositionalOnlyErrorMessage]\nfrom typing import overload\n\n@overload\ndef foo(a: int, /): ...\n@overload\ndef foo(a: str): ...\ndef foo(a): ...\n\nfoo(a=1)\n[out]\nmain:9: error: No overload variant of \"foo\" matches argument type \"int\"\nmain:9: note: Possible overload variants:\nmain:9: note:     def foo(int, /) -> Any\nmain:9: note:     def foo(a: str) -> Any\n\n[case testOverloadPositionalOnlyErrorMessageAllTypes]\nfrom typing import overload\n\n@overload\ndef foo(a: int, /, b: int, *, c: int): ...\n@overload\ndef foo(a: str, b: int, *, c: int): ...\ndef foo(a, b, *, c): ...\n\nfoo(a=1)\n[out]\nmain:9: error: No overload variant of \"foo\" matches argument type \"int\"\nmain:9: note: Possible overload variants:\nmain:9: note:     def foo(int, /, b: int, *, c: int) -> Any\nmain:9: note:     def foo(a: str, b: int, *, c: int) -> Any\n\n[case testOverloadPositionalOnlyErrorMessageMultiplePosArgs]\nfrom typing import overload\n\n@overload\ndef foo(a: int, b: int, c: int, /, d: str): ...\n@overload\ndef foo(a: str, b: int, c: int, d: str): ...\ndef foo(a, b, c, d): ...\n\nfoo(a=1)\n[out]\nmain:9: error: No overload variant of \"foo\" matches argument type \"int\"\nmain:9: note: Possible overload variants:\nmain:9: note:     def foo(int, int, int, /, d: str) -> Any\nmain:9: note:     def foo(a: str, b: int, c: int, d: str) -> Any\n\n[case testOverloadPositionalOnlyErrorMessageMethod]\nfrom typing import overload\n\nclass Some:\n    @overload\n    def foo(self, __a: int): ...\n    @overload\n    def foo(self, a: float, /): ...\n    @overload\n    def foo(self, a: str): ...\n    def foo(self, a): ...\n\nSome().foo(a=1)\n[out]\nmain:12: error: No overload variant of \"foo\" of \"Some\" matches argument type \"int\"\nmain:12: note: Possible overload variants:\nmain:12: note:     def foo(self, int, /) -> Any\nmain:12: note:     def foo(self, float, /) -> Any\nmain:12: note:     def foo(self, a: str) -> Any\n\n[case testOverloadPositionalOnlyErrorMessageClassMethod]\nfrom typing import overload\n\nclass Some:\n    @overload\n    @classmethod\n    def foo(cls, __a: int): ...\n    @overload\n    @classmethod\n    def foo(cls, a: float, /): ...\n    @overload\n    @classmethod\n    def foo(cls, a: str): ...\n    @classmethod\n    def foo(cls, a): ...\n\nSome.foo(a=1)\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:16: error: No overload variant of \"foo\" of \"Some\" matches argument type \"int\"\nmain:16: note: Possible overload variants:\nmain:16: note:     def foo(cls, int, /) -> Any\nmain:16: note:     def foo(cls, float, /) -> Any\nmain:16: note:     def foo(cls, a: str) -> Any\n\n[case testUnpackWithDuplicateNamePositionalOnly]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\ndef foo(name: str, /, **kwargs: Unpack[Person]) -> None:  # Allowed\n    ...\n[builtins fixtures/dict.pyi]\n\n[case testPossiblyUndefinedWithAssignmentExpr]\n# flags: --enable-error-code possibly-undefined\ndef f1() -> None:\n    d = {0: 1}\n    if int():\n        x = 1\n\n    if (x := d[x]) is None:  # E: Name \"x\" may be undefined\n        y = x\n    z = x\n[builtins fixtures/dict.pyi]\n\n[case testNarrowOnSelfInGeneric]\nfrom typing import Generic, TypeVar, Optional\n\nT = TypeVar(\"T\", int, str)\n\nclass C(Generic[T]):\n    x: Optional[T]\n    def meth(self) -> Optional[T]:\n        if (y := self.x) is not None:\n            reveal_type(y)\n        return None\n[out]\nmain:9: note: Revealed type is \"builtins.int\"\nmain:9: note: Revealed type is \"builtins.str\"\n\n[case testTypeGuardWithPositionalOnlyArg]\nfrom typing_extensions import TypeGuard\n\ndef typeguard(x: object, /) -> TypeGuard[int]:\n    ...\n\nn: object\nif typeguard(n):\n    reveal_type(n)\n[builtins fixtures/tuple.pyi]\n[out]\nmain:8: note: Revealed type is \"builtins.int\"\n\n[case testTypeGuardKeywordFollowingWalrus]\nfrom typing import cast\nfrom typing_extensions import TypeGuard\n\ndef typeguard(x: object) -> TypeGuard[int]:\n    ...\n\nif typeguard(x=(n := cast(object, \"hi\"))):\n    reveal_type(n)\n[builtins fixtures/tuple.pyi]\n[out]\nmain:8: note: Revealed type is \"builtins.int\"\n\n[case testNoCrashOnAssignmentExprClass]\nclass C:\n    [(j := i) for i in [1, 2, 3]]  # E: Assignment expression within a comprehension cannot be used in a class body\n[builtins fixtures/list.pyi]\n\n[case testNarrowedVariableInNestedModifiedInWalrus]\nfrom typing import Optional\n\ndef walrus_with_nested_error(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 \"Optional[str]\", expected \"str\")\n    if x := None:\n        pass\n    nested()\n\ndef walrus_with_nested_ok(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x\n    if y := x:\n        pass\n    nested()\n\n[case testIgnoreWholeModule]\n# flags: --warn-unused-ignores\n# type: ignore\nIGNORE # type: ignore\n\n[case testUnusedIgnoreVersionCheck]\n# flags: --warn-unused-ignores\nimport sys\n\nif sys.version_info < (3, 6):\n    42  # type: ignore\nelse:\n    42  # type: ignore  # E: Unused \"type: ignore\" comment\n[builtins fixtures/ops.pyi]\n\n[case testDictExpressionErrorLocations]\n# flags: --pretty\nfrom typing import Dict\n\nother: Dict[str, str]\ndct: Dict[str, int] = {\"a\": \"b\", **other}\n[builtins fixtures/dict.pyi]\n[out]\nmain:5: error: Dict entry 0 has incompatible type \"str\": \"str\"; expected \"str\": \"int\"\n    dct: Dict[str, int] = {\"a\": \"b\", **other}\n                           ^~~~~~~~\nmain:5: error: Unpacked dict entry 1 has incompatible type \"Dict[str, str]\"; expected \"SupportsKeysAndGetItem[str, int]\"\n    dct: Dict[str, int] = {\"a\": \"b\", **other}\n                                       ^~~~~\n\n[case testWalrusAssignmentEmptyCollection]\nfrom typing import List\n\ny: List[int]\nif (y := []):\n    reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n"
  },
  {
    "path": "test-data/unit/check-python39.test",
    "content": "[case testGivingSameKeywordArgumentTwice]\n# This test was originally in check-kwargs.test\n# Python 3.9's new parser started producing a different error message here. Since this isn't the\n# most important test, to deal with this we'll only run this test with Python 3.9 and later.\nimport typing\ndef f(a: 'A', b: 'B') -> None: pass\nclass A: pass\nclass B: pass\nf(a=A(), b=B(), a=A()) # E: \"f\" gets multiple values for keyword argument \"a\"\n\n\n[case testPEP614]\nfrom typing import Callable, List\n\ndecorator_list: List[Callable[..., Callable[[int], str]]]\n@decorator_list[0]\ndef f(x: float) -> float: ...\nreveal_type(f)  # N: Revealed type is \"def (builtins.int) -> builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testStarredExpressionsInForLoop]\n# flags: --python-version 3.9\n\na = b = c = [1, 2, 3]\nfor x in *a, *b, *c:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-recursive-types.test",
    "content": "-- Tests checking that basic functionality works\n\n[case testRecursiveAliasBasic]\nfrom typing import Dict, List, Union, TypeVar, Sequence\n\nJSON = Union[str, List[JSON], Dict[str, JSON]]\n\ny: JSON = [\"foo\", {\"bar\": \"baz\"}]\nreveal_type(y)  # N: Revealed type is \"builtins.list[Union[builtins.str, builtins.list[...], builtins.dict[builtins.str, ...]]]\"\n\nx: JSON\n\nreveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.list[...], builtins.dict[builtins.str, ...]]\"\nif isinstance(x, list):\n    x = x[0]\n\nclass Bad: ...\nx = [\"foo\", {\"bar\": [Bad()]}]  # E: List item 0 has incompatible type \"Bad\"; expected \"Union[str, List[JSON], Dict[str, JSON]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasBasicGenericSubtype]\nfrom typing import Union, TypeVar, Sequence, List\n\nT = TypeVar(\"T\")\n\nNested = Sequence[Union[T, Nested[T]]]\n\nclass Bad: ...\nx: Nested[int]\ny: Nested[Bad]\nx = y  # E: Incompatible types in assignment (expression has type \"Nested[Bad]\", variable has type \"Nested[int]\")\n\nNestedOther = Sequence[Union[T, Nested[T]]]\n\nxx: Nested[int]\nyy: NestedOther[bool]\nxx = yy  # OK\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasBasicGenericInference]\nfrom typing import Union, TypeVar, Sequence, List\n\nT = TypeVar(\"T\")\n\nNested = Sequence[Union[T, Nested[T]]]\n\ndef flatten(arg: Nested[T]) -> List[T]:\n    res: List[T] = []\n    for item in arg:\n        if isinstance(item, Sequence):\n            res.extend(flatten(item))\n        else:\n            res.append(item)\n    return res\n\nreveal_type(flatten([1, [2, [3]]]))  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass Bad: ...\nx: Nested[int] = [1, [2, [3]]]\nx = [1, [Bad()]]  # E: List item 0 has incompatible type \"Bad\"; expected \"Union[int, Nested[int]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasGenericInferenceNested]\nfrom typing import Union, TypeVar, Sequence, List\n\nT = TypeVar(\"T\")\nclass A: ...\nclass B(A): ...\n\nNested = Sequence[Union[T, Nested[T]]]\n\ndef flatten(arg: Nested[T]) -> List[T]: ...\nreveal_type(flatten([[B(), B()]]))  # N: Revealed type is \"builtins.list[__main__.B]\"\nreveal_type(flatten([[[[B()]]]]))  # N: Revealed type is \"builtins.list[__main__.B]\"\nreveal_type(flatten([[B(), [[B()]]]]))  # N: Revealed type is \"builtins.list[__main__.B]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasNewStyleSupported]\nfrom test import A\n\nx: A\nif isinstance(x, list):\n    reveal_type(x[0])  # N: Revealed type is \"Union[builtins.int, builtins.list[Union[builtins.int, builtins.list[...]]]]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[file test.pyi]\nA = int | list[A]\n[builtins fixtures/isinstancelist.pyi]\n\n-- Tests duplicating some existing type alias tests with recursive aliases enabled\n\n[case testRecursiveAliasesMutual]\n# flags: --disable-error-code used-before-def\nfrom typing import Type, Callable, Union\n\nA = Union[B, int]\nB = Callable[[C], int]\nC = Type[A]\nx: A\nreveal_type(x)  # N: Revealed type is \"Union[def (Union[Type[def (...) -> builtins.int], Type[builtins.int]]) -> builtins.int, builtins.int]\"\n\n[case testRecursiveAliasesProhibited-skip]\nfrom typing import Type, Callable, Union\n\nA = Union[B, int]\nB = Union[A, int]\nC = Type[C]\n\n[case testRecursiveAliasImported]\nimport lib\nx: lib.A\nreveal_type(x)  # N: Revealed type is \"builtins.list[builtins.list[...]]\"\n\n[file lib.pyi]\nfrom typing import List\nfrom other import B\nA = List[B]\n\n[file other.pyi]\nfrom typing import List\nfrom lib import A\nB = List[A]\n[builtins fixtures/list.pyi]\n\n[case testRecursiveAliasViaBaseClass]\n# flags: --disable-error-code used-before-def\nfrom typing import List\n\nx: B\nB = List[C]\nclass C(B): 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 testRecursiveAliasViaBaseClass2]\n# flags: --disable-error-code used-before-def\nfrom typing import NewType, List\n\nx: D\nreveal_type(x[0][0])  # N: Revealed type is \"__main__.C\"\n\nD = List[C]\nC = NewType('C', B)\n\nclass B(D):\n    pass\n[builtins fixtures/list.pyi]\n\n[case testRecursiveAliasViaBaseClass3]\nfrom typing import List, Generic, TypeVar, NamedTuple\nT = TypeVar('T')\n\nclass C(A, B):\n    pass\nclass G(Generic[T]): pass\nA = G[C]\nclass B(NamedTuple):\n    x: int\n\ny: C\nreveal_type(y.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y[0])  # N: Revealed type is \"builtins.int\"\nx: A\nreveal_type(x)  # N: Revealed type is \"__main__.G[Tuple[builtins.int, fallback=__main__.C]]\"\n[builtins fixtures/list.pyi]\n\n[case testRecursiveAliasViaBaseClassImported]\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 testRecursiveAliasViaNamedTuple]\nfrom typing import List, NamedTuple, Union\n\nExp = Union['A', 'B']\nclass A(NamedTuple('A', [('attr', List[Exp])])): pass\nclass B(NamedTuple('B', [('val', object)])): pass\n\ndef my_eval(exp: Exp) -> int:\n    reveal_type(exp) # N: Revealed type is \"Union[Tuple[builtins.list[...], fallback=__main__.A], Tuple[builtins.object, fallback=__main__.B]]\"\n    if isinstance(exp, A):\n        my_eval(exp[0][0])\n        return my_eval(exp.attr[0])\n    if isinstance(exp, B):\n        return exp.val  # E: Incompatible return value type (got \"object\", expected \"int\")\n    return 0\n\nmy_eval(A([B(1), B(2)]))\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasesSimplifiedUnion]\nfrom typing import Sequence, TypeVar, Union\n\nclass A: ...\nclass B(A): ...\n\nNestedA = Sequence[Union[A, NestedA]]\nNestedB = Sequence[Union[B, NestedB]]\na: NestedA\nb: NestedB\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\ndef union(a: T, b: S) -> Union[T, S]: ...\n\nx: int\ny = union(a, b)\nx = y  # E: Incompatible types in assignment (expression has type \"Sequence[Union[A, NestedA]]\", variable has type \"int\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasesJoins]\nfrom typing import Sequence, TypeVar, Union\n\nclass A: ...\nclass B(A): ...\n\nNestedA = Sequence[Union[A, NestedA]]\nNestedB = Sequence[Union[B, NestedB]]\na: NestedA\nb: NestedB\nla: Sequence[Sequence[A]]\nlb: Sequence[Sequence[B]]\n\nT = TypeVar(\"T\")\ndef join(a: T, b: T) -> T: ...\nx: int\n\ny1 = join(a, b)\nx = y1  # E: Incompatible types in assignment (expression has type \"Sequence[Union[A, NestedA]]\", variable has type \"int\")\ny2 = join(a, lb)\nx = y2  # E: Incompatible types in assignment (expression has type \"Sequence[Union[A, NestedA]]\", variable has type \"int\")\ny3 = join(la, b)\nx = y3  # E: Incompatible types in assignment (expression has type \"Sequence[Union[Sequence[A], B, NestedB]]\", variable has type \"int\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasesRestrictions]\nfrom typing import Sequence, Mapping, Union\n\nA = Sequence[Union[int, A]]\nB = Mapping[int, Union[int, B]]\n\nx: int\ny: Union[A, B]\nif isinstance(y, Sequence):\n    x = y  # E: Incompatible types in assignment (expression has type \"Sequence[Union[int, A]]\", variable has type \"int\")\nelse:\n    x = y  # E: Incompatible types in assignment (expression has type \"Mapping[int, Union[int, B]]\", variable has type \"int\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasesRestrictions2]\nfrom typing import Sequence, Union\n\nclass A: ...\nclass B(A): ...\n\nNestedA = Sequence[Union[A, NestedA]]\nNestedB = Sequence[Union[B, NestedB]]\n\na: NestedA\nb: NestedB\naa: NestedA\n\nx: int\nx = a  # E: Incompatible types in assignment (expression has type \"NestedA\", variable has type \"int\")\na = b\nx = a  # E: Incompatible types in assignment (expression has type \"Sequence[Union[B, NestedB]]\", variable has type \"int\")\nb = aa  # E: Incompatible types in assignment (expression has type \"NestedA\", variable has type \"NestedB\")\nif isinstance(b[0], Sequence):\n    a = b[0]\n    x = a  # E: Incompatible types in assignment (expression has type \"Sequence[Union[B, NestedB]]\", variable has type \"int\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasWithRecursiveInstance]\nfrom typing import Sequence, Union, TypeVar\n\nclass A: ...\nT = TypeVar(\"T\")\nNested = Sequence[Union[T, Nested[T]]]\nclass B(Sequence[B]): ...\n\na: Nested[A]\naa: Nested[A]\nb: B\na = b  # OK\na = [[b]]  # OK\nb = aa  # E: Incompatible types in assignment (expression has type \"Nested[A]\", variable has type \"B\")\n\ndef join(a: T, b: T) -> T: ...\nreveal_type(join(a, b))  # N: Revealed type is \"typing.Sequence[Union[__main__.A, typing.Sequence[Union[__main__.A, ...]]]]\"\nreveal_type(join(b, a))  # N: Revealed type is \"typing.Sequence[Union[__main__.A, typing.Sequence[Union[__main__.A, ...]]]]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasWithRecursiveInstanceInference]\nfrom typing import Sequence, Union, TypeVar, List\n\nT = TypeVar(\"T\")\nNested = Sequence[Union[T, Nested[T]]]\nclass B(Sequence[B]): ...\n\nnb: Nested[B] = [B(), [B(), [B()]]]\nlb: List[B]\n\ndef foo(x: Nested[T]) -> T: ...\nreveal_type(foo(lb))  # N: Revealed type is \"__main__.B\"\nreveal_type(foo([B(), [B(), [B()]]]))  # N: Revealed type is \"__main__.B\"\n\nNestedInv = List[Union[T, NestedInv[T]]]\nnib: NestedInv[B] = [B(), [B(), [B()]]]\ndef bar(x: NestedInv[T]) -> T: ...\nreveal_type(bar(nib))  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasTopUnion]\nfrom typing import Sequence, Union, TypeVar, List\n\nclass A: ...\nclass B(A): ...\n\nT = TypeVar(\"T\")\nPlainNested = Union[T, Sequence[PlainNested[T]]]\n\nx: PlainNested[A]\ny: PlainNested[B] = [B(), [B(), [B()]]]\nx = y  # OK\n\nxx: PlainNested[B]\nyy: PlainNested[A]\nxx = yy  # E: Incompatible types in assignment (expression has type \"PlainNested[A]\", variable has type \"PlainNested[B]\")\n\ndef foo(arg: PlainNested[T]) -> T: ...\nlb: List[B]\nreveal_type(foo([B(), [B(), [B()]]]))  # N: Revealed type is \"__main__.B\"\nreveal_type(foo(lb))  # N: Revealed type is \"__main__.B\"\nreveal_type(foo(xx))  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasInferenceExplicitNonRecursive]\nfrom typing import Sequence, Union, TypeVar, List\n\nT = TypeVar(\"T\")\nNested = Sequence[Union[T, Nested[T]]]\nPlainNested = Union[T, Sequence[PlainNested[T]]]\n\ndef foo(x: Nested[T]) -> T: ...\ndef bar(x: PlainNested[T]) -> T: ...\n\nclass A: ...\na: A\nla: List[A]\nlla: List[Union[A, List[A]]]\nllla: List[Union[A, List[Union[A, List[A]]]]]\n\nreveal_type(foo(la))  # N: Revealed type is \"__main__.A\"\nreveal_type(foo(lla))  # N: Revealed type is \"__main__.A\"\nreveal_type(foo(llla))  # N: Revealed type is \"__main__.A\"\n\nreveal_type(bar(a))  # N: Revealed type is \"__main__.A\"\nreveal_type(bar(la))  # N: Revealed type is \"__main__.A\"\nreveal_type(bar(lla))  # N: Revealed type is \"__main__.A\"\nreveal_type(bar(llla))  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRecursiveAliasesWithOptional]\nfrom typing import Optional, Sequence\n\nA = Sequence[Optional[A]]\nx: A\ny: str = x[0]  # E: Incompatible types in assignment (expression has type \"Optional[A]\", variable has type \"str\")\n\n[case testRecursiveAliasesProhibitBadAliases]\n# flags: --disable-error-code used-before-def\nfrom typing import Union, Type, List, TypeVar\n\nNR = List[int]\nNR2 = Union[NR, NR]\nNR3 = Union[NR, Union[NR2, NR2]]\n\nT = TypeVar(\"T\")\nNRG = Union[int, T]\nNR4 = NRG[str]\nNR5 = Union[NRG[int], NR4]\n\nA = Union[B, int]  # E: Invalid recursive alias: a union item of itself\nB = Union[int, A]  # Error reported above\ndef f() -> A: ...\nreveal_type(f())  # N: Revealed type is \"Any\"\n\nG = Union[T, G[T]]  # E: Invalid recursive alias: a union item of itself\nGL = Union[T, GL[List[T]]]  # E: Invalid recursive alias: a union item of itself \\\n                            # E: Invalid recursive alias: type variable nesting on right hand side\ndef g() -> G[int]: ...\nreveal_type(g())  # N: Revealed type is \"Any\"\n\ndef local() -> None:\n    L = List[Union[int, L]]  # E: Cannot resolve name \"L\" (possible cyclic definition) \\\n                             # N: Recursive types are not allowed at function scope \\\n                             # E: Cannot resolve name \"L\" (possible cyclic definition) \\\n                             # N: Recursive types are not allowed at function scope\n    x: L\n    reveal_type(x)  # N: Revealed type is \"builtins.list[Union[builtins.int, Any]]\"\n\nS = Type[S]  # E: Type[...] can't contain \"Type[...]\"\nU = Type[Union[int, U]]  # E: Type[...] can't contain \"Union[Type[...], Type[...]]\" \\\n                         # E: Type[...] can't contain \"Type[...]\"\nx: U\nreveal_type(x)  # N: Revealed type is \"Type[Any]\"\n\nD = List[F[List[T]]]  # E: Invalid recursive alias: type variable nesting on right hand side\nF = D[T]  # Error reported above\nE = List[E[E[T]]]  # E: Invalid recursive alias: type variable nesting on right hand side\nd: D\nreveal_type(d)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testBasicRecursiveNamedTuple]\nfrom typing import NamedTuple, Optional\n\nNT = NamedTuple(\"NT\", [(\"x\", Optional[NT]), (\"y\", int)])\nnt: NT\nreveal_type(nt)  # N: Revealed type is \"Tuple[Union[..., None], builtins.int, fallback=__main__.NT]\"\nreveal_type(nt.x)  # N: Revealed type is \"Union[Tuple[Union[..., None], builtins.int, fallback=__main__.NT], None]\"\nreveal_type(nt[0])  # N: Revealed type is \"Union[Tuple[Union[..., None], builtins.int, fallback=__main__.NT], None]\"\ny: str\nif nt.x is not None:\n    y = nt.x[0]  # E: Incompatible types in assignment (expression has type \"Optional[NT]\", variable has type \"str\")\n[builtins fixtures/tuple.pyi]\n\n[case testBasicRecursiveNamedTupleSpecial]\nfrom typing import NamedTuple, TypeVar, Tuple\n\nNT = NamedTuple(\"NT\", [(\"x\", NT), (\"y\", int)])\nnt: NT\nreveal_type(nt)  # N: Revealed type is \"Tuple[..., builtins.int, fallback=__main__.NT]\"\nreveal_type(nt.x)  # N: Revealed type is \"Tuple[..., builtins.int, fallback=__main__.NT]\"\nreveal_type(nt[0])  # N: Revealed type is \"Tuple[Tuple[..., builtins.int, fallback=__main__.NT], builtins.int, fallback=__main__.NT]\"\ny: str\nif nt.x is not None:\n    y = nt.x[0]  # E: Incompatible types in assignment (expression has type \"NT\", variable has type \"str\")\n\nT = TypeVar(\"T\")\ndef f(a: T, b: T) -> T: ...\ntnt: Tuple[NT]\n\n# TODO: these should be tuple[object] instead.\nreveal_type(f(nt, tnt))  # N: Revealed type is \"builtins.tuple[Any, ...]\"\nreveal_type(f(tnt, nt))  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testBasicRecursiveNamedTupleClass]\nfrom typing import NamedTuple, Optional\n\nclass NT(NamedTuple):\n    x: Optional[NT]\n    y: int\n\nnt: NT\nreveal_type(nt)  # N: Revealed type is \"Tuple[Union[..., None], builtins.int, fallback=__main__.NT]\"\nreveal_type(nt.x)  # N: Revealed type is \"Union[Tuple[Union[..., None], builtins.int, fallback=__main__.NT], None]\"\nreveal_type(nt[0])  # N: Revealed type is \"Union[Tuple[Union[..., None], builtins.int, fallback=__main__.NT], None]\"\ny: str\nif nt.x is not None:\n    y = nt.x[0]  # E: Incompatible types in assignment (expression has type \"Optional[NT]\", variable has type \"str\")\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveRegularTupleClass]\nfrom typing import Tuple\n\nx: B\nclass B(Tuple[B, int]):\n    x: int\n\nb, _ = x\nreveal_type(b.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveTupleClassesNewType]\nfrom typing import Tuple, NamedTuple, NewType\n\nx: C\nclass B(Tuple[B, int]):\n    x: int\nC = NewType(\"C\", B)\nb, _ = x\nreveal_type(b)  # N: Revealed type is \"Tuple[..., builtins.int, fallback=__main__.B]\"\nreveal_type(b.x)  # N: Revealed type is \"builtins.int\"\n\ny: CNT\nclass BNT(NamedTuple):\n    x: CNT\n    y: int\nCNT = NewType(\"CNT\", BNT)\nbnt, _ = y\nreveal_type(bnt.y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n-- Tests duplicating some existing named tuple tests with recursive aliases enabled\n\n[case testMutuallyRecursiveNamedTuples]\n# flags: --disable-error-code used-before-def\n\nfrom typing import Tuple, NamedTuple, TypeVar, Union\n\nA = NamedTuple('A', [('x', str), ('y', Tuple[B, ...])])\nclass B(NamedTuple):\n    x: A\n    y: int\n\nn: A\nreveal_type(n) # N: Revealed type is \"Tuple[builtins.str, builtins.tuple[Tuple[..., builtins.int, fallback=__main__.B], ...], fallback=__main__.A]\"\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\ndef foo(arg: Tuple[T, S]) -> Union[T, S]: ...\nx = foo(n)\ny: str = x  # E: Incompatible types in assignment (expression has type \"Union[str, Tuple[B, ...]]\", variable has type \"str\")\n[builtins fixtures/tuple.pyi]\n\n[case testMutuallyRecursiveNamedTuplesJoin]\nfrom typing import NamedTuple, Tuple\n\nclass B(NamedTuple):\n    x: Tuple[A, int]\n    y: int\n\nA = NamedTuple('A', [('x', str), ('y', B)])\nn: B\nm: A\ns: str = n.x  # E: Incompatible types in assignment (expression has type \"Tuple[A, int]\", variable has type \"str\")\nreveal_type(m[0]) # N: Revealed type is \"builtins.str\"\nlst = [m, n]\n\n# Unfortunately, join of two recursive types is not very precise.\nreveal_type(lst[0]) # N: Revealed type is \"builtins.object\"\n\n# These just should not crash\nlst1 = [m]\nlst2 = [m, m]\nlst3 = [m, m, m]\n[builtins fixtures/tuple.pyi]\n\n[case testMutuallyRecursiveNamedTuplesClasses]\nfrom typing import NamedTuple, Tuple\n\nclass B(NamedTuple):\n    x: A\n    y: int\nclass A(NamedTuple):\n    x: str\n    y: B\n\nn: A\ns: str = n.y[0]  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"str\")\n\nm: B\nn = m.x\nn = n.y.x\n\nt: Tuple[str, B]\nt = n\nt = m  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"Tuple[str, B]\")\n[builtins fixtures/tuple.pyi]\n\n[case testMutuallyRecursiveNamedTuplesCalls]\n# flags: --disable-error-code used-before-def\nfrom typing import NamedTuple\n\nB = NamedTuple('B', [('x', A), ('y', int)])\nA = NamedTuple('A', [('x', str), ('y', 'B')])\nn: A\ndef f(m: B) -> None: pass\nreveal_type(n) # N: Revealed type is \"Tuple[builtins.str, Tuple[..., builtins.int, fallback=__main__.B], fallback=__main__.A]\"\nreveal_type(f) # N: Revealed type is \"def (m: Tuple[Tuple[builtins.str, ..., fallback=__main__.A], builtins.int, fallback=__main__.B])\"\nf(n)  # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"B\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoRecursiveTuplesAtFunctionScope]\nfrom typing import NamedTuple, Tuple\ndef foo() -> None:\n    class B(NamedTuple):\n        x: B  # E: Cannot resolve name \"B\" (possible cyclic definition) \\\n              # N: Recursive types are not allowed at function scope\n        y: int\n    b: B\n    reveal_type(b)  # N: Revealed type is \"Tuple[Any, builtins.int, fallback=__main__.B@3]\"\n[builtins fixtures/tuple.pyi]\n\n[case testBasicRecursiveGenericNamedTuple]\nfrom typing import Generic, NamedTuple, TypeVar, Union\n\nT = TypeVar(\"T\", covariant=True)\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: Union[T, NT[T]]\n\nclass A: ...\nclass B(A): ...\n\nnti: NT[int] = NT(key=0, value=NT(key=1, value=A()))  # E: Argument \"value\" to \"NT\" has incompatible type \"A\"; expected \"Union[int, NT[int]]\"\nreveal_type(nti)  # N: Revealed type is \"Tuple[builtins.int, Union[builtins.int, ...], fallback=__main__.NT[builtins.int]]\"\n\nnta: NT[A]\nntb: NT[B]\nnta = ntb  # OK, covariance\nntb = nti  # E: Incompatible types in assignment (expression has type \"NT[int]\", variable has type \"NT[B]\")\n\ndef last(arg: NT[T]) -> T: ...\nreveal_type(last(ntb))  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/tuple.pyi]\n\n[case testBasicRecursiveTypedDictClass]\nfrom typing import TypedDict\n\nclass TD(TypedDict):\n    x: int\n    y: TD\n\ntd: TD\nreveal_type(td)  # N: Revealed type is \"TypedDict('__main__.TD', {'x': builtins.int, 'y': ...})\"\ns: str = td[\"y\"]  # E: Incompatible types in assignment (expression has type \"TD\", variable has type \"str\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testBasicRecursiveTypedDictCall]\nfrom typing import TypedDict\n\nTD = TypedDict(\"TD\", {\"x\": int, \"y\": TD})\ntd: TD\nreveal_type(td)  # N: Revealed type is \"TypedDict('__main__.TD', {'x': builtins.int, 'y': ...})\"\n\nTD2 = TypedDict(\"TD2\", {\"x\": int, \"y\": TD2})\ntd2: TD2\nTD3 = TypedDict(\"TD3\", {\"x\": str, \"y\": TD3})\ntd3: TD3\n\ntd = td2\ntd = td3  # E: Incompatible types in assignment (expression has type \"TD3\", variable has type \"TD\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testBasicRecursiveTypedDictExtending]\nfrom typing import TypedDict\n\nclass TDA(TypedDict):\n    xa: int\n    ya: TD\n\nclass TDB(TypedDict):\n    xb: int\n    yb: TD\n\nclass TD(TDA, TDB):\n    a: TDA\n    b: TDB\n\ntd: TD\nreveal_type(td)  # N: Revealed type is \"TypedDict('__main__.TD', {'xb': builtins.int, 'yb': ..., 'xa': builtins.int, 'ya': ..., 'a': TypedDict('__main__.TDA', {'xa': builtins.int, 'ya': ...}), 'b': TypedDict('__main__.TDB', {'xb': builtins.int, 'yb': ...})})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecursiveTypedDictCreation]\nfrom typing import TypedDict, Optional\n\nclass TD(TypedDict):\n    x: int\n    y: Optional[TD]\n\ntd: TD = {\"x\": 0, \"y\": None}\ntd2: TD = {\"x\": 0, \"y\": {\"x\": 1, \"y\": {\"x\": 2, \"y\": None}}}\n\nitd = TD(x=0, y=None)\nitd2 = TD(x=0, y=TD(x=0, y=TD(x=0, y=None)))\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecursiveTypedDictMethods]\nfrom typing import TypedDict\n\nclass TD(TypedDict, total=False):\n    x: int\n    y: TD\n\ntd: TD\ntd[\"y\"] = {\"x\": 0, \"y\": {}}\ntd[\"y\"] = {\"x\": 0, \"y\": {\"x\": 0, \"y\": 42}}  # E: Incompatible types (expression has type \"int\", TypedDict item \"y\" has type \"TD\")\n\nreveal_type(td.get(\"y\"))  # N: Revealed type is \"Union[TypedDict('__main__.TD', {'x'?: builtins.int, 'y'?: TypedDict('__main__.TD', {'x'?: builtins.int, 'y'?: ...})}), None]\"\ns: str = td.get(\"y\")  # E: Incompatible types in assignment (expression has type \"Optional[TD]\", variable has type \"str\")\n\ntd.update({\"x\": 0, \"y\": {\"x\": 1, \"y\": {}}})\ntd.update({\"x\": 0, \"y\": {\"x\": 1, \"y\": {\"x\": 2, \"y\": 42}}})  # E: Incompatible types (expression has type \"int\", TypedDict item \"y\" has type \"TD\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecursiveTypedDictSubtyping]\nfrom typing import TypedDict\n\nclass TDA1(TypedDict):\n    x: int\n    y: TDA1\nclass TDA2(TypedDict):\n    x: int\n    y: TDA2\nclass TDB(TypedDict):\n    x: str\n    y: TDB\n\ntda1: TDA1\ntda2: TDA2\ntdb: TDB\ndef fa1(arg: TDA1) -> None: ...\ndef fa2(arg: TDA2) -> None: ...\ndef fb(arg: TDB) -> None: ...\n\nfa1(tda2)\nfa2(tda1)\nfb(tda1)  # E: Argument 1 to \"fb\" has incompatible type \"TDA1\"; expected \"TDB\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecursiveTypedDictJoin]\nfrom typing import TypedDict, TypeVar\n\nclass TDA1(TypedDict):\n    x: int\n    y: TDA1\nclass TDA2(TypedDict):\n    x: int\n    y: TDA2\nclass TDB(TypedDict):\n    x: str\n    y: TDB\n\ntda1: TDA1\ntda2: TDA2\ntdb: TDB\n\nT = TypeVar(\"T\")\ndef f(x: T, y: T) -> T: ...\n# Join for recursive types is very basic, but just add tests that we don't crash.\nreveal_type(f(tda1, tda2))  # N: Revealed type is \"TypedDict({'x': builtins.int, 'y': TypedDict('__main__.TDA1', {'x': builtins.int, 'y': ...})})\"\nreveal_type(f(tda1, tdb))  # N: Revealed type is \"TypedDict({})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testBasicRecursiveGenericTypedDict]\nfrom typing import TypedDict, TypeVar, Generic, Optional, List\n\nT = TypeVar(\"T\")\nclass Tree(TypedDict, Generic[T], total=False):\n    value: T\n    left: Tree[T]\n    right: Tree[T]\n\ndef collect(arg: Tree[T]) -> List[T]: ...\n\nreveal_type(collect({\"left\": {\"right\": {\"value\": 0}}}))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecursiveGenericTypedDictExtending]\nfrom typing import TypedDict, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\n\nclass TD(TypedDict, Generic[T]):\n    val: T\n    other: STD[T]\nclass STD(TD[T]):\n    sval: T\n    one: TD[T]\n\nstd: STD[str]\nreveal_type(std)  # N: Revealed type is \"TypedDict('__main__.STD', {'val': builtins.str, 'other': ..., 'sval': builtins.str, 'one': TypedDict('__main__.TD', {'val': builtins.str, 'other': ...})})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecursiveClassLevelAlias]\nfrom typing import Union, Sequence\n\nclass A:\n    Children = Union[Sequence['Children'], 'A', None]\nx: A.Children\nreveal_type(x)  # N: Revealed type is \"Union[typing.Sequence[...], __main__.A, None]\"\n\nclass B:\n    Foo = Sequence[Bar]\n    Bar = Sequence[Foo]\ny: B.Foo\nreveal_type(y)  # N: Revealed type is \"typing.Sequence[typing.Sequence[...]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashOnRecursiveTupleFallback]\nfrom typing import Union, Tuple\n\nTree1 = Union[str, Tuple[Tree1]]\nTree2 = Union[str, Tuple[Tree2, Tree2]]\nTree3 = Union[str, Tuple[Tree3, Tree3, Tree3]]\n\ndef test1() -> Tree1:\n    return 42  # E: Incompatible return value type (got \"int\", expected \"Union[str, Tuple[Tree1]]\")\ndef test2() -> Tree2:\n    return 42  # E: Incompatible return value type (got \"int\", expected \"Union[str, Tuple[Tree2, Tree2]]\")\ndef test3() -> Tree3:\n    return 42  # E: Incompatible return value type (got \"int\", expected \"Union[str, Tuple[Tree3, Tree3, Tree3]]\")\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveDoubleUnionNoCrash]\nfrom typing import Tuple, Union, Callable, Sequence\n\nK = Union[int, Tuple[Union[int, K]]]\nL = Union[int, Callable[[], Union[int, L]]]\nM = Union[int, Sequence[Union[int, M]]]\n\nx: K\nx = x\ny: L\ny = y\nz: M\nz = z\n\nx = y  # E: Incompatible types in assignment (expression has type \"L\", variable has type \"K\")\nz = x  # OK\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveInstanceInferenceNoCrash]\nfrom typing import Sequence, TypeVar, Union\n\nclass C(Sequence[C]): ...\n\nT = TypeVar(\"T\")\ndef foo(x: T) -> C: ...\n\nNested = Union[C, Sequence[Nested]]\nx: Nested = foo(42)\n\n[case testNoRecursiveExpandInstanceUnionCrash]\nfrom typing import List, Union\n\nclass Tag(List[Union[Tag, List[Tag]]]): ...\nTag()\n\n[case testNoRecursiveExpandInstanceUnionCrashGeneric]\nfrom typing import Generic, Iterable, TypeVar, Union\n\nValueT = TypeVar(\"ValueT\")\nclass Recursive(Iterable[Union[ValueT, Recursive[ValueT]]]):\n    pass\n\nclass Base(Generic[ValueT]):\n    def __init__(self, element: ValueT):\n        pass\nclass Sub(Base[Union[ValueT, Recursive[ValueT]]]):\n    pass\n\nx: Iterable[str]\nreveal_type(Sub)  # N: Revealed type is \"def [ValueT] (element: Union[ValueT`1, __main__.Recursive[ValueT`1]]) -> __main__.Sub[ValueT`1]\"\nreveal_type(Sub(x))  # N: Revealed type is \"__main__.Sub[typing.Iterable[builtins.str]]\"\n\n[case testNoRecursiveExpandInstanceUnionCrashInference]\n# flags: --disable-error-code used-before-def\nfrom typing import TypeVar, Union, Generic, List\n\nT = TypeVar(\"T\")\nInList = Union[T, InListRecurse[T]]\nclass InListRecurse(Generic[T], List[InList[T]]): ...\n\ndef list_thing(transforming: InList[T]) -> T:\n    ...\nreveal_type(list_thing([5]))  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n[case testRecursiveTypedDictWithList]\nfrom typing import List\nfrom typing_extensions import TypedDict\n\nExample = TypedDict(\"Example\", {\"rec\": List[\"Example\"]})\ne: Example\nreveal_type(e)  # N: Revealed type is \"TypedDict('__main__.Example', {'rec': builtins.list[...]})\"\n[builtins fixtures/dict.pyi]\n\n[case testRecursiveNamedTupleWithList]\nfrom typing import List, NamedTuple\n\nExample = NamedTuple(\"Example\", [(\"rec\", List[\"Example\"])])\ne: Example\nreveal_type(e)  # N: Revealed type is \"Tuple[builtins.list[...], fallback=__main__.Example]\"\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveBoundFunctionScopeNoCrash]\nfrom typing import TypeVar, Union, Dict\n\ndef dummy() -> None:\n    A = Union[str, Dict[str, \"A\"]]  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                                    # N: Recursive types are not allowed at function scope \\\n                                    # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                                    # N: Recursive types are not allowed at function scope\n    T = TypeVar(\"T\", bound=A)\n\n    def bar(x: T) -> T:\n        pass\n    reveal_type(bar)  # N: Revealed type is \"def [T <: Union[builtins.str, builtins.dict[builtins.str, Any]]] (x: T`-1) -> T`-1\"\n[builtins fixtures/dict.pyi]\n\n[case testForwardBoundFunctionScopeWorks]\nfrom typing import TypeVar, Dict\n\ndef dummy() -> None:\n    A = Dict[str, \"B\"]\n    B = Dict[str, str]\n    T = TypeVar(\"T\", bound=A)\n\n    def bar(x: T) -> T:\n        pass\n    reveal_type(bar)  # N: Revealed type is \"def [T <: builtins.dict[builtins.str, builtins.dict[builtins.str, builtins.str]]] (x: T`-1) -> T`-1\"\n[builtins fixtures/dict.pyi]\n\n[case testAliasRecursiveUnpackMultiple]\nfrom typing import Tuple, TypeVar, Optional\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nA = Tuple[T, S, Optional[A[T, S]]]\nx: A[int, str]\n\n*_, last = x\nif last is not None:\n    reveal_type(last)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, Union[Tuple[builtins.int, builtins.str, Union[..., None]], None]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveAliasLiteral]\nfrom typing import Tuple\nfrom typing_extensions import Literal\n\nNotFilter = Tuple[Literal[\"not\"], \"NotFilter\"]\nn: NotFilter\nreveal_type(n[1][1][0])  # N: Revealed type is \"Literal['not']\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashOnRecursiveAliasWithNone]\n# flags: --strict-optional\nfrom typing import Union, Generic, TypeVar, Optional\n\nT = TypeVar(\"T\")\nclass A(Generic[T]): ...\nclass B(Generic[T]): ...\n\nZ = Union[A[Z], B[Optional[Z]]]\nX = Union[A[Optional[X]], B[Optional[X]]]\n\nz: Z\nx: X\nreveal_type(z)  # N: Revealed type is \"Union[__main__.A[...], __main__.B[Union[..., None]]]\"\nreveal_type(x)  # N: Revealed type is \"Union[__main__.A[Union[..., None]], __main__.B[Union[..., None]]]\"\n\n[case testRecursiveTupleFallback1]\nfrom typing import NewType, Tuple, Union\n\nT1 = NewType(\"T1\", str)\nT2 = Tuple[T1, \"T4\", \"T4\"]\nT3 = Tuple[str, \"T4\", \"T4\"]\nT4 = Union[T2, T3]\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveTupleFallback2]\nfrom typing import NewType, Tuple, Union\n\nT1 = NewType(\"T1\", str)\nclass T2(Tuple[T1, \"T4\", \"T4\"]): ...\nT3 = Tuple[str, \"T4\", \"T4\"]\nT4 = Union[T2, T3]\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveTupleFallback3]\nfrom typing import NewType, Tuple, Union\n\nT1 = NewType(\"T1\", str)\nT2 = Tuple[T1, \"T4\", \"T4\"]\nclass T3(Tuple[str, \"T4\", \"T4\"]): ...\nT4 = Union[T2, T3]\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveTupleFallback4]\nfrom typing import NewType, Tuple, Union\n\nT1 = NewType(\"T1\", str)\nclass T2(Tuple[T1, \"T4\", \"T4\"]): ...\nclass T3(Tuple[str, \"T4\", \"T4\"]): ...\nT4 = Union[T2, T3]\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveTupleFallback5]\nfrom typing import Protocol, Tuple, Union\n\nclass Proto(Protocol):\n    def __len__(self) -> int: ...\n\nA = Union[Proto, Tuple[A]]\nta: Tuple[A]\np: Proto\np = ta\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveAliasesWithAnyUnimported]\n# flags: --disallow-any-unimported\nfrom typing import Callable\nfrom bogus import Foo  # type: ignore\n\nA = Callable[[Foo, \"B\"], Foo]  # E: Type alias target becomes \"Callable[[Any, B], Any]\" due to an unfollowed import\nB = Callable[[Foo, A], Foo]  # E: Type alias target becomes \"Callable[[Any, A], Any]\" due to an unfollowed import\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 \"Union[builtins.int, builtins.str]\"\n    y = 1\n    y = g(y)\n    reveal_type(y)  # N: Revealed type is \"Union[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 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\ndef g(): 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        reveal_type(_) # N: Revealed type is \"Any\"\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    # NOTE: '\"int\" not callable' is due to test stubs\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://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases \\\n                               # E: Variable \"y\" is not valid as a type \\\n                               # N: See https://kotlinisland.github.io/basedmypy/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\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: 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.object\"\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 \"Union[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\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 testCallingUnderscoreFunctionIsNotAllowed-skip]\n# Skipped because of https://github.com/python/mypy/issues/11774\ndef _(arg: str) -> None:\n    pass\n\ndef _(arg: int) -> int:\n    return arg\n\n_('a') # E: Calling function named \"_\" is not allowed\n\ny = _(5) # E: Calling function named \"_\" is not allowed\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/check-reports.test",
    "content": "[case testReportBasic]\n# flags: --xml-report out\ndef f(): pass\n\ndef g() -> None: pass\n[outfile out/index.xml]\n<?xml-stylesheet type=\"text/xsl\" href=\"mypy-html.xslt\"?><mypy-report-index name=\"index\"><file module=\"__main__\" name=\"main\" total=\"4\" any=\"1\" empty=\"2\" imprecise=\"0\" precise=\"1\" unanalyzed=\"0\"/></mypy-report-index>\n\n[case testLinePrecisionBasic]\n# flags: --lineprecision-report out\ndef f(): pass\n\ndef g() -> None:\n    a = 1\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      5        2          0    1      2           0\n\n[case testLinePrecisionImpreciseType]\n# flags: --lineprecision-report out\ndef f(x: list) -> None: pass\n[builtins fixtures/list.pyi]\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      2        0          1    0      1           0\n\n[case testLinePrecisionUnanalyzed]\n# flags: --lineprecision-report out\nimport sys\nMYPY = False\nif not MYPY:\n    a = 1\n\ndef f(x: int) -> None:\n    if isinstance(x, str):\n        b = 1\n        c = 1\n[builtins fixtures/isinstance.pyi]\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__     10        5          0    0      2           3\n\n[case testLinePrecisionEmptyLines]\n# flags: --lineprecision-report out\ndef f() -> None:\n    \"\"\"docstring\n\n    long\n    \"\"\"\n    x = 0\n\n    # comment\n    y = 0  # comment (non-empty)\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__     10        3          0    0      7           0\n\n[case testLinePrecisionImportFrom]\n# flags: --lineprecision-report out --ignore-missing-imports\nfrom m import f\nfrom m import g\nfrom bad import foo\nfrom bad import (  # treated as a single line\n    foo2,\n    foo3,\n)\n\n[file m.py]\ndef f(): pass\ndef g() -> None: pass\n\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      8        2          0    2      4           0\nm             2        1          0    1      0           0\n\n[case testLinePrecisionImport]\n# flags: --lineprecision-report out --ignore-missing-imports\nimport m\nimport bad\nimport m, bad\n\n[file m.py]\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      4        1          0    2      1           0\nm             0        0          0    0      0           0\n\n[case testLinePrecisionStarImport]\n# flags: --lineprecision-report out --ignore-missing-imports\nfrom m import *\nfrom bad import *\n\n[file m.py]\ndef f(): pass\ndef g() -> None: pass\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      3        1          0    1      1           0\nm             2        1          0    1      0           0\n\n[case testLinePrecisionRelativeImport]\n# flags: --lineprecision-report out --ignore-missing-imports\nimport a\n\n[file a/__init__.py]\nfrom .m import f\nfrom .bad import g\n\n[file a/m.py]\ndef f(): pass\n\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      2        1          0    0      1           0\na             2        1          0    1      0           0\na.m           1        0          0    1      0           0\n\n[case testLinePrecisionPassStatement]\n# flags: --lineprecision-report out\ndef f() -> None:\n    pass\ndef g():\n    pass\nclass C:\n    pass\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      7        4          0    2      1           0\n\n[case testLinePrecisionBreakAndContinueStatement]\n# flags: --lineprecision-report out\nimport a\nimport b\n\n[file a.py]\ndef f() -> int:\n    while f():\n        break\n    return f()\ndef g():\n    while g():\n        break\n\n[file b.py]\ndef f() -> int:\n    while f():\n        continue\n    return f()\ndef g():\n    while g():\n        continue\n\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      3        2          0    0      1           0\na             7        4          0    3      0           0\nb             7        4          0    3      0           0\n\n[case testLinePrecisionLiterals]\n# flags: --lineprecision-report out\nimport str_lit\nimport bytes_lit\nimport int_lit\nimport float_lit\nimport true_lit\nimport false_lit\nimport none_lit\nimport complex_lit\nimport dots_lit\n\n[file str_lit.py]\ndef f() -> object:\n    return ''\ndef g():\n    return ''\n\n[file bytes_lit.py]\ndef f() -> object:\n    return b''\ndef g():\n    return b''\n\n[file int_lit.py]\ndef f() -> object:\n    return 1\ndef g():\n    return 1\n\n[file float_lit.py]\ndef f() -> object:\n    return 1.1\ndef g():\n    return 1.1\n\n[file true_lit.py]\ndef f() -> object:\n    return True\ndef g():\n    return True\n\n[file false_lit.py]\ndef f() -> object:\n    return False\ndef g():\n    return False\n\n[file none_lit.py]\ndef f() -> object:\n    return None\ndef g():\n    return None\n\n[file complex_lit.py]\ndef f() -> object:\n    return None\ndef g():\n    return None\n\n[file dots_lit.py]\ndef f() -> object:\n    return ...\ndef g():\n    return ...\n\n[outfile out/lineprecision.txt]\nName         Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n----------------------------------------------------------------\n__main__        10        9          0    0      1           0\nbytes_lit        4        2          0    2      0           0\ncomplex_lit      4        2          0    2      0           0\ndots_lit         4        2          0    2      0           0\nfalse_lit        4        2          0    2      0           0\nfloat_lit        4        2          0    2      0           0\nint_lit          4        2          0    2      0           0\nnone_lit         4        2          0    2      0           0\nstr_lit          4        2          0    2      0           0\ntrue_lit         4        2          0    2      0           0\n\n[case testLinePrecisionIfStatement]\n# flags: --lineprecision-report out\nif int():\n    x = 1\nelse:  # This is treated as empty\n    x = 2\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      5        3          0    0      2           0\n\n[case testLinePrecisionCallAnyArg]\n# flags: --lineprecision-report out\nfrom m import f\ndef g() -> None:\n    f(1)  # Precise\n    f(1, 2)  # Any\n[file m.py]\nfrom typing import Any\ndef f(x: int, y: Any = 0) -> None:\n    pass\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      5        3          0    1      1           0\nm             3        2          0    1      0           0\n\n[case testLinePrecisionCallImpreciseArg]\n# flags: --lineprecision-report out\nfrom m import f\ndef g() -> None:\n    f(1)  # Precise\n    f(1, [2])  # Imprecise\n[file m.py]\nfrom typing import List, Any\ndef f(x: int, y: List[Any] = []) -> None:\n    pass\n[builtins fixtures/list.pyi]\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      5        3          1    0      1           0\nm             3        2          1    0      0           0\n\n[case testLinePrecisionCallAnyArgWithKeywords]\n# flags: --lineprecision-report out\nfrom m import f\ndef g() -> None:\n    f(x=1)  # Precise\n    f(x=1, z=1)  # Precise\n    f(z=1, x=1)  # Precise\n    f(y=1)  # Any\n    f(y=1, x=1)  # Any\n[file m.py]\nfrom typing import Any\ndef f(x: int = 0, y: Any = 0, z: int = 0) -> None:\n    pass\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      8        5          0    2      1           0\nm             3        2          0    1      0           0\n\n[case testLinePrecisionCallAnyMethodArg]\n# flags: --lineprecision-report out\nfrom m import C\ndef g(c: C) -> None:\n    c.f(1)  # Precise\n    c.f(1, 2)  # Any\n[file m.py]\nfrom typing import Any\nclass C:\n    def f(self, x: int, y: Any = 0) -> None:\n        pass\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      5        3          0    1      1           0\nm             4        3          0    1      0           0\n\n[case testLinePrecisionCallAnyConstructorArg]\n# flags: --lineprecision-report out\nfrom m import C\ndef g() -> None:\n    C(1)  # Precise\n    C(1, 2)  # Any\n[file m.py]\nfrom typing import Any\nclass C:\n    def __init__(self, x: int, y: Any = 0) -> None:\n        pass\n[outfile out/lineprecision.txt]\nName      Lines  Precise  Imprecise  Any  Empty  Unanalyzed\n-------------------------------------------------------------\n__main__      5        3          0    1      1           0\nm             4        3          0    1      0           0\n"
  },
  {
    "path": "test-data/unit/check-selftype.test",
    "content": "[case testSelfTypeInstance]\nfrom typing import TypeVar\n\nT = TypeVar('T', bound='A', covariant=True)\n\nclass A:\n    def copy(self: T) -> T: pass\n\nclass B(A):\n    pass\n\nreveal_type(A().copy)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(B().copy)  # N: Revealed type is \"def () -> __main__.B\"\nreveal_type(A().copy())  # N: Revealed type is \"__main__.A\"\nreveal_type(B().copy())  # N: Revealed type is \"__main__.B\"\n\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeStaticAccess]\nfrom typing import TypeVar\n\nT = TypeVar('T', bound='A', covariant=True)\nclass A:\n    def copy(self: T) -> T: pass\n\nclass B(A):\n    pass\n\n# Erased instances appear on reveal_type; unrelated to self type\ndef f(a: A) -> None: pass\nf(A.copy(A()))\nf(A.copy(B()))\nf(B.copy(B()))\n\n# TODO: make it an error\n# f(B.copy(A()))\n\ndef g(a: B) -> None: pass\ng(A.copy(A()))  # E: Argument 1 to \"g\" has incompatible type \"A\"; expected \"B\"\ng(A.copy(B()))\ng(B.copy(B()))\n\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeReturn]\nfrom typing import TypeVar, Type\n\nR = TypeVar('R')\ndef _type(self: R) -> Type[R]: pass\n\nT = TypeVar('T', bound='A', covariant=True)\nclass A:\n    def copy(self: T) -> T:\n        if B():\n            return A()  # E: Incompatible return value type (got \"A\", expected \"T\")\n        elif A():\n            return B()  # E: Incompatible return value type (got \"B\", expected \"T\")\n        reveal_type(_type(self))  # N: Revealed type is \"Type[T`-1]\"\n        return reveal_type(_type(self)())  # N: Revealed type is \"T`-1\"\n\nclass B(A):\n    pass\n\nQ = TypeVar('Q', bound='C', covariant=True)\nclass C:\n    def __init__(self, a: int) -> None: pass\n\n    def copy(self: Q) -> Q:\n        if self:\n            return reveal_type(_type(self)(1))  # N: Revealed type is \"Q`-1\"\n        else:\n            return _type(self)()  # E: Missing positional argument \"a\" in call to \"C\"\n\n\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeClass]\nfrom typing import TypeVar, Type\n\nT = TypeVar('T', bound='A')\n\nclass A:\n    @classmethod\n    def new(cls: Type[T]) -> T:\n        return reveal_type(cls())  # N: Revealed type is \"T`-1\"\n\nclass B(A):\n    pass\n\nQ = TypeVar('Q', bound='C', covariant=True)\nclass C:\n    def __init__(self, a: int) -> None: pass\n\n    @classmethod\n    def new(cls: Type[Q]) -> Q:\n        if cls:\n            return cls(1)\n        else:\n            return cls()  # E: Missing positional argument \"a\" in call to \"C\"\n\n\nreveal_type(A.new)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(B.new)  # N: Revealed type is \"def () -> __main__.B\"\nreveal_type(A.new())  # N: Revealed type is \"__main__.A\"\nreveal_type(B.new())  # N: Revealed type is \"__main__.B\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeOverride]\nfrom typing import TypeVar, cast\n\nT = TypeVar('T', bound='A', covariant=True)\n\nclass A:\n    def copy(self: T) -> T: pass\n\nclass B(A):\n    pass\n\nQ = TypeVar('Q', bound='C', covariant=True)\nclass C(A):\n    def copy(self: Q) -> Q: pass\n\nreveal_type(C().copy)  # N: Revealed type is \"def () -> __main__.C\"\nreveal_type(C().copy())  # N: Revealed type is \"__main__.C\"\nreveal_type(cast(A, C()).copy)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(cast(A, C()).copy())  # N: Revealed type is \"__main__.A\"\n\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeOverrideCompatibility]\nfrom typing import overload, TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]):\n    @overload\n    def f(self: A[int]) -> int: ...\n    @overload\n    def f(self: A[str]) -> str: ...\n    def f(self): ...\n\nclass B(A[T]):\n    @overload\n    def f(self: A[int]) -> int: ...\n    @overload\n    def f(self: A[str]) -> str: ...\n    def f(self): ...\n\nclass B2(A[T]):\n    @overload\n    def f(self: A[int]) -> int: ...\n    @overload\n    def f(self: A[str]) -> str: ...\n    @overload\n    def f(self: A[bytes]) -> bytes: ...\n    def f(self): ...\n\nclass C(A[int]):\n    def f(self) -> int: ...\n\nclass D(A[str]):\n    def f(self) -> int: ...  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                             # N:      Superclass:            \\\n                             # N:          @overload          \\\n                             # N:          def f(self) -> str \\\n                             # N:      Subclass:              \\\n                             # N:          def f(self) -> int\n\nclass E(A[T]):\n    def f(self) -> int: ...  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                             # N:      Superclass:            \\\n                             # N:          @overload          \\\n                             # N:          def f(self) -> int \\\n                             # N:          @overload          \\\n                             # N:          def f(self) -> str \\\n                             # N:      Subclass:              \\\n                             # N:          def f(self) -> int\n\n\nclass F(A[bytes]):\n    # Note there's an argument to be made that this is actually compatible with the supertype\n    def f(self) -> bytes: ...  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                               # N:      Superclass:            \\\n                               # N:          @overload          \\\n                               # N:          def f(self) -> int \\\n                               # N:          @overload          \\\n                               # N:          def f(self) -> str \\\n                               # N:      Subclass:              \\\n                               # N:          def f(self) -> bytes\n\nclass G(A):\n    def f(self): ...\n\nclass H(A[int]):\n    def f(self): ...\n\nclass I(A[int]):\n    def f(*args): ...\n\nclass J(A[int]):\n    def f(self, arg) -> int: ...  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                                  # N:      Superclass:            \\\n                                  # N:          @overload          \\\n                                  # N:          def f(self) -> int \\\n                                  # N:      Subclass:              \\\n                                  # N:          def f(self, arg: Any) -> int\n\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeOverrideCompatibilityGeneric]\nfrom typing import TypeVar, Generic, overload\n\nT = TypeVar(\"T\", str, int, None)\n\nclass A(Generic[T]):\n    @overload\n    def f(self, s: T) -> T: ...\n    @overload\n    def f(self: A[str], s: bytes) -> str: ...\n    def f(self, s: object): ...\n\nclass B(A[int]):\n    def f(self, s: int) -> int: ...\n\nclass C(A[None]):\n    def f(self, s: int) -> int: ...  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                                     # N:      Superclass:            \\\n                                     # N:          @overload          \\\n                                     # N:          def f(self, s: None) -> None \\\n                                     # N:      Subclass:              \\\n                                     # N:          def f(self, s: int) -> int\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeOverrideCompatibilityTypeVar]\nfrom typing import overload, TypeVar, Union\n\nAT = TypeVar(\"AT\", bound=\"A\")\n\nclass A:\n    @overload\n    def f(self: AT, x: int) -> AT: ...\n    @overload\n    def f(self, x: str) -> None: ...\n    @overload\n    def f(self: AT) -> bytes: ...\n    def f(*a, **kw): ...\n\nclass B(A):\n    @overload  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n               # N:      Superclass:                                 \\\n               # N:          @overload                               \\\n               # N:          def f(self, x: int) -> B                \\\n               # N:          @overload                               \\\n               # N:          def f(self, x: str) -> None             \\\n               # N:          @overload                               \\\n               # N:          def f(self) -> bytes                    \\\n               # N:      Subclass:                                   \\\n               # N:          @overload                               \\\n               # N:          def f(self, x: int) -> B                \\\n               # N:          @overload                               \\\n               # N:          def f(self, x: str) -> None\n    def f(self, x: int) -> B: ...\n    @overload\n    def f(self, x: str) -> None: ...\n    def f(*a, **kw): ...\n[builtins fixtures/dict.pyi]\n\n[case testSelfTypeOverrideCompatibilitySelfTypeVar]\nfrom typing import Any, Generic, Self, TypeVar, overload\n\nT_co = TypeVar('T_co', covariant=True)\n\nclass Config(Generic[T_co]):\n\t@overload\n\tdef get(self, instance: None) -> Self: ...\n\t@overload\n\tdef get(self, instance: Any) -> T_co: ...\n\tdef get(self, *a, **kw): ...\n\nclass MultiConfig(Config[T_co]):\n\t@overload\n\tdef get(self, instance: None) -> Self: ...\n\t@overload\n\tdef get(self, instance: Any) -> T_co: ...\n\tdef get(self, *a, **kw): ...\n[builtins fixtures/dict.pyi]\n\n[case testSelfTypeSuper]\nfrom typing import TypeVar, cast\n\nT = TypeVar('T', bound='A', covariant=True)\n\nclass A:\n    def copy(self: T) -> T: pass\n\nQ = TypeVar('Q', bound='B', covariant=True)\nclass B(A):\n    def copy(self: Q) -> Q:\n        reveal_type(self)  # N: Revealed type is \"Q`-1\"\n        reveal_type(super().copy)  # N: Revealed type is \"def () -> Q`-1\"\n        return super().copy()\n\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeRecursiveBinding]\nfrom typing import TypeVar, Callable, Type\n\nT = TypeVar('T', bound='A', covariant=True)\nclass A:\n    # TODO: This is potentially unsafe, as we use T in an argument type\n    def copy(self: T, factory: Callable[[T], T]) -> T:\n        return factory(self)\n\n    @classmethod\n    def new(cls: Type[T], factory: Callable[[T], T]) -> T:\n        reveal_type(cls)   # N: Revealed type is \"Type[T`-1]\"\n        reveal_type(cls())   # N: Revealed type is \"T`-1\"\n        cls(2)  # E: Too many arguments for \"A\"\n        return cls()\n\nclass B(A):\n    pass\n\nreveal_type(A().copy)  # N: Revealed type is \"def (factory: def (__main__.A) -> __main__.A) -> __main__.A\"\nreveal_type(B().copy)  # N: Revealed type is \"def (factory: def (__main__.B) -> __main__.B) -> __main__.B\"\nreveal_type(A.new)  # N: Revealed type is \"def (factory: def (__main__.A) -> __main__.A) -> __main__.A\"\nreveal_type(B.new)  # N: Revealed type is \"def (factory: def (__main__.B) -> __main__.B) -> __main__.B\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeBound]\nfrom typing import TypeVar, Callable, cast\n\nTA = TypeVar('TA', bound='A', covariant=True)\n\nclass A:\n    def copy(self: TA) -> TA:\n        pass\n\nclass C(A):\n    def copy(self: C) -> C:\n        pass\n\nclass D(A):\n   def copy(self: A) -> A:  # E: Return type \"A\" of \"copy\" incompatible with return type \"D\" in supertype \"A\"\n       pass\n\nTB = TypeVar('TB', bound='B', covariant=True)\nclass B(A):\n    x = 1\n    def copy(self: TB) -> TB:\n        reveal_type(self.x)  # N: Revealed type is \"builtins.int\"\n        return cast(TB, None)\n\n[builtins fixtures/bool.pyi]\n\n-- # TODO: fail for this\n-- [case testSelfTypeBare]\n-- from typing import TypeVar, Type\n--\n-- T = TypeVar('T', bound='E')\n--\n-- class E:\n--     def copy(self: T, other: T) -> T: pass\n\n[case testSelfTypeClone]\nfrom typing import TypeVar, Type\nT = TypeVar('T', bound='C')\n\nclass C:\n    def copy(self: T) -> T:\n        return self\n\n    @classmethod\n    def new(cls: Type[T]) -> T:\n        return cls()\n\nclass D(C): pass\n\nreveal_type(D.new)  # N: Revealed type is \"def () -> __main__.D\"\nreveal_type(D().new)  # N: Revealed type is \"def () -> __main__.D\"\nreveal_type(D.new())  # N: Revealed type is \"__main__.D\"\nreveal_type(D().new())  # N: Revealed type is \"__main__.D\"\n\nQ = TypeVar('Q', bound=C)\n\ndef clone(arg: Q) -> Q:\n    reveal_type(arg.copy)  # N: Revealed type is \"def () -> Q`-1\"\n    reveal_type(arg.copy())  # N: Revealed type is \"Q`-1\"\n    reveal_type(arg.new)  # N: Revealed type is \"def () -> Q`-1\"\n    reveal_type(arg.new())  # N: Revealed type is \"Q`-1\"\n    return arg.copy()\n\ndef make(cls: Type[Q]) -> Q:\n    reveal_type(cls.new)  # N: Revealed type is \"def () -> Q`-1\"\n    reveal_type(cls().new)  # N: Revealed type is \"def () -> Q`-1\"\n    reveal_type(cls().new())  # N: Revealed type is \"Q`-1\"\n    return cls.new()\n\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeGeneric]\nfrom typing import TypeVar\n\nT = TypeVar('T', int, str)\n\nclass A:\n    pass\n\nclass B(A):\n    def __init__(self, arg: T) -> None:\n        super(B, self).__init__()\n\n[case testSelfTypeNonsensical]\nfrom typing import TypeVar, Type\n\nT = TypeVar('T', bound=str)\nclass A:\n    def foo(self: T) -> T:   # E: The erased type of self \"builtins.str\" is not a supertype of its class \"__main__.A\"\n        return self\n\n    @classmethod\n    def cfoo(cls: Type[T]) -> T:  # E: The erased type of self \"Type[builtins.str]\" is not a supertype of its class \"Type[__main__.A]\"\n        return cls()\n\nQ = TypeVar('Q', bound='B')\nclass B:\n    def foo(self: Q) -> Q:\n        return self\n\n    @classmethod\n    def cfoo(cls: Type[Q]) -> Q:\n        return cls()\n\nclass C:\n    def foo(self: C) -> C: return self\n\n    @classmethod\n    def cfoo(cls: Type[C]) -> C:\n        return cls()\n\nclass D:\n    def foo(self: Q) -> Q:  # E: The erased type of self \"__main__.B\" is not a supertype of its class \"__main__.D\"\n        return self\n\n    @staticmethod\n    def bar(self: str) -> str:\n        return self\n\n    @classmethod\n    def cfoo(cls: Type[Q]) -> Q:  # E: The erased type of self \"Type[__main__.B]\" is not a supertype of its class \"Type[__main__.D]\"\n        return cls()\n\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeLambdaDefault]\nfrom typing import Callable\nclass C:\n    @classmethod\n    def foo(cls,\n            arg: Callable[[int], str] = lambda a: ''\n            ) -> None:\n        pass\n\n    def bar(self,\n            arg: Callable[[int], str] = lambda a: ''\n            ) -> None:\n        pass\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeNew]\nfrom typing import TypeVar, Type\n\nT = TypeVar('T', bound='A')\nclass A:\n    def __new__(cls: Type[T]) -> T:\n        return cls()\n\n    def __init_subclass__(cls: Type[T]) -> None:\n        pass\n\nclass B:\n    def __new__(cls: Type[T]) -> T:  # E: The erased type of self \"Type[__main__.A]\" is not a supertype of its class \"Type[__main__.B]\"\n        return cls()\n\n    def __init_subclass__(cls: Type[T]) -> None:  # E: The erased type of self \"Type[__main__.A]\" is not a supertype of its class \"Type[__main__.B]\"\n        pass\n\nclass C:\n    def __new__(cls: Type[C]) -> C:\n        return cls()\n\n    def __init_subclass__(cls: Type[C]) -> None:\n        pass\n\nclass D:\n    def __new__(cls: D) -> D:  # E: The erased type of self \"__main__.D\" is not a supertype of its class \"Type[__main__.D]\"\n        return cls\n\n    def __init_subclass__(cls: D) -> None:  # E: The erased type of self \"__main__.D\" is not a supertype of its class \"Type[__main__.D]\"\n        pass\n\nclass E:\n    def __new__(cls) -> E:\n        reveal_type(cls)  # N: Revealed type is \"Type[__main__.E]\"\n        return cls()\n\n    def __init_subclass__(cls) -> None:\n        reveal_type(cls)  # N: Revealed type is \"Type[__main__.E]\"\n\n[case testSelfTypeNew_explicit]\nfrom typing import TypeVar, Type\n\nT = TypeVar('T', bound='A')\nclass A:\n    @staticmethod\n    def __new__(cls: Type[T]) -> T:\n        return cls()\n\n    @classmethod\n    def __init_subclass__(cls: Type[T]) -> None:\n        pass\n\nclass B:\n    @staticmethod\n    def __new__(cls: Type[T]) -> T:  # E: The erased type of self \"Type[__main__.A]\" is not a supertype of its class \"Type[__main__.B]\"\n        return cls()\n\n    @classmethod\n    def __init_subclass__(cls: Type[T]) -> None:  # E: The erased type of self \"Type[__main__.A]\" is not a supertype of its class \"Type[__main__.B]\"\n        pass\n\nclass C:\n    @staticmethod\n    def __new__(cls: Type[C]) -> C:\n        return cls()\n\n    @classmethod\n    def __init_subclass__(cls: Type[C]) -> None:\n        pass\n\nclass D:\n    @staticmethod\n    def __new__(cls: D) -> D:  # E: The erased type of self \"__main__.D\" is not a supertype of its class \"Type[__main__.D]\"\n        return cls\n\n    @classmethod\n    def __init_subclass__(cls: D) -> None:  # E: The erased type of self \"__main__.D\" is not a supertype of its class \"Type[__main__.D]\"\n        pass\n\nclass E:\n    @staticmethod\n    def __new__(cls) -> E:\n        reveal_type(cls)  # N: Revealed type is \"Type[__main__.E]\"\n        return cls()\n\n    @classmethod\n    def __init_subclass__(cls) -> None:\n        reveal_type(cls)  # N: Revealed type is \"Type[__main__.E]\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypePropertyUnion]\nfrom typing import Union\nclass A:\n    @property\n    def f(self: A) -> int: pass\n\nclass B:\n    @property\n    def f(self: B) -> int: pass\nx: Union[A, B]\nreveal_type(x.f)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeProperSupertypeAttribute]\nfrom typing import Callable, TypeVar, ClassVar\nfrom types import FunctionType\nclass K: pass\nT = TypeVar('T', bound=K)\nclass A(K):\n    @property\n    def g(self: K) -> int: return 0\n    @property\n    def gt(self: T) -> T: return self\n    f: ClassVar[\"FunctionType[[object], int]\"]\n    ft: ClassVar[\"FunctionType[[T], T]\"]\n\nclass B(A):\n    pass\n\nreveal_type(A().g)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().gt)  # N: Revealed type is \"__main__.A\"\nreveal_type(A().f())  # N: Revealed type is \"builtins.int\"\nreveal_type(A().ft())  # N: Revealed type is \"__main__.A\"\nreveal_type(B().g)  # N: Revealed type is \"builtins.int\"\nreveal_type(B().gt)  # N: Revealed type is \"__main__.B\"\nreveal_type(B().f())  # N: Revealed type is \"builtins.int\"\nreveal_type(B().ft())  # N: Revealed type is \"__main__.B\"\n\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeProperSupertypeAttributeTuple]\nfrom typing import Callable, TypeVar, Tuple, ClassVar\nfrom types import FunctionType\nT = TypeVar('T')\nclass A(Tuple[int, int]):\n    @property\n    def g(self: object) -> int: return 0\n    @property\n    def gt(self: T) -> T: return self\n    f: ClassVar[\"FunctionType[[object], int]\"]\n    ft: ClassVar[\"FunctionType[[T], T]\"]\n\nclass B(A):\n    pass\n\nreveal_type(A().g)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().gt)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.A]\"\nreveal_type(A().f())  # N: Revealed type is \"builtins.int\"\nreveal_type(A().ft())  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.A]\"\nreveal_type(B().g)  # N: Revealed type is \"builtins.int\"\nreveal_type(B().gt)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.B]\"\nreveal_type(B().f())  # N: Revealed type is \"builtins.int\"\nreveal_type(B().ft())  # N: Revealed type is \"Tuple[builtins.int, builtins.int, fallback=__main__.B]\"\n\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeProperSupertypeAttributeMeta]\nfrom typing import Callable, TypeVar, Type, ClassVar\nfrom types import FunctionType\nT = TypeVar('T')\nclass A(type):\n    @property\n    def g(cls: object) -> int: return 0\n    @property\n    def gt(cls: T) -> T: return cls\n    f: ClassVar[\"FunctionType[[object], int]\"]\n    ft: ClassVar[\"FunctionType[[T], T]\"]\n\nclass B(A):\n    pass\n\nclass X(metaclass=B):\n    def __init__(self, x: int) -> None: pass\nclass Y(X): pass\nX1: Type[X]\nreveal_type(X.g)  # N: Revealed type is \"builtins.int\"\nreveal_type(X.gt)  # N: Revealed type is \"def (x: builtins.int) -> __main__.X\"\nreveal_type(X.f())  # N: Revealed type is \"builtins.int\"\nreveal_type(X.ft())  # N: Revealed type is \"def (x: builtins.int) -> __main__.X\"\nreveal_type(Y.g)  # N: Revealed type is \"builtins.int\"\nreveal_type(Y.gt)  # N: Revealed type is \"def (x: builtins.int) -> __main__.Y\"\nreveal_type(Y.f())  # N: Revealed type is \"builtins.int\"\nreveal_type(Y.ft())  # N: Revealed type is \"def (x: builtins.int) -> __main__.Y\"\nreveal_type(X1.g)  # N: Revealed type is \"builtins.int\"\nreveal_type(X1.gt)  # N: Revealed type is \"Type[__main__.X]\"\nreveal_type(X1.f())  # N: Revealed type is \"builtins.int\"\nreveal_type(X1.ft())  # N: Revealed type is \"Type[__main__.X]\"\n\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeProperSupertypeAttributeGeneric]\nfrom typing import Callable, TypeVar, Generic, ClassVar\nfrom types import FunctionType\nQ = TypeVar('Q', covariant=True)\nclass K(Generic[Q]):\n    q: Q\nT = TypeVar('T')\nclass A(K[Q]):\n    @property\n    def g(self: K[object]) -> int: return 0\n    @property\n    def gt(self: K[T]) -> T: return self.q\n    f: ClassVar[\"FunctionType[[object], int]\"]\n    ft: ClassVar[\"FunctionType[[T], T]\"]\n\nclass B(A[Q]):\n    pass\na: A[int]\nb: B[str]\nreveal_type(a.g)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.gt)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.f())  # N: Revealed type is \"builtins.int\"\nreveal_type(a.ft())  # N: Revealed type is \"__main__.A[builtins.int]\"\nreveal_type(b.g)  # N: Revealed type is \"builtins.int\"\nreveal_type(b.gt)  # N: Revealed type is \"builtins.str\"\nreveal_type(b.f())  # N: Revealed type is \"builtins.int\"\nreveal_type(b.ft())  # N: Revealed type is \"__main__.B[builtins.str]\"\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeRestrictedMethod]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    def from_item(self: C[str]) -> None: ...\n\ni: C[int]\ns: C[str]\n\ni.from_item()  # E: Invalid self argument \"C[int]\" to attribute function \"from_item\" with type \"Callable[[C[str]], None]\"\ns.from_item()\n\n[case testSelfTypeRestrictedClassMethod]\nfrom typing import TypeVar, Generic, Type\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    @classmethod\n    def from_item(cls: Type[C[str]]) -> None: ...\n\nclass DI(C[int]): ...\nclass DS(C[str]): ...\n\nDI().from_item()  # E: Invalid self argument \"Type[DI]\" to class attribute function \"from_item\" with type \"Callable[[Type[C[str]]], None]\"\nDS().from_item()\nDI.from_item()  # E: Invalid self argument \"Type[DI]\" to attribute function \"from_item\" with type \"Callable[[Type[C[str]]], None]\"\nDS.from_item()\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeRestrictedMethodOverload]\nfrom typing import TypeVar, Generic, overload, Tuple\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    @overload\n    def from_item(self: C[str], item: str) -> None: ...\n    @overload\n    def from_item(self: C[int], item: Tuple[int]) -> None: ...\n    def from_item(self, item):\n        ...\n\nci: C[int]\ncs: C[str]\nreveal_type(ci.from_item)  # N: Revealed type is \"def (item: Tuple[builtins.int])\"\nreveal_type(cs.from_item)  # N: Revealed type is \"def (item: builtins.str)\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeRestrictedMethodOverloadFallback]\nfrom typing import TypeVar, Generic, overload, Callable\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    @overload\n    def from_item(self: C[str]) -> str: ...\n    @overload\n    def from_item(self, converter: Callable[[T], str]) -> str: ...\n    def from_item(self, converter):\n        ...\n\nci: C[int]\ncs: C[str]\nreveal_type(cs.from_item())  # N: Revealed type is \"builtins.str\"\nci.from_item()  # E: Missing positional argument \"converter\" in call to \"from_item\" of \"C\"\n\ndef conv(x: int) -> str: ...\ndef bad(x: str) -> str: ...\nreveal_type(ci.from_item(conv))  # N: Revealed type is \"builtins.str\"\nci.from_item(bad)  # E: Argument 1 to \"from_item\" of \"C\" has incompatible type \"Callable[[str], str]\"; expected \"Callable[[int], str]\"\n\n[case testSelfTypeRestrictedMethodOverloadInit]\nfrom typing import TypeVar\nfrom lib import P, C\n\nreveal_type(P)  # N: Revealed type is \"Overload(def [T] (use_str: Literal[True]) -> lib.P[builtins.str], def [T] (use_str: Literal[False]) -> lib.P[builtins.int])\"\nreveal_type(P(use_str=True))  # N: Revealed type is \"lib.P[builtins.str]\"\nreveal_type(P(use_str=False))  # N: Revealed type is \"lib.P[builtins.int]\"\n\nreveal_type(C)  # N: Revealed type is \"Overload(def [T] (item: T`1, use_tuple: Literal[False]) -> lib.C[T`1], def [T] (item: T`1, use_tuple: Literal[True]) -> lib.C[builtins.tuple[T`1, ...]])\"\nreveal_type(C(0, use_tuple=False))  # N: Revealed type is \"lib.C[builtins.int]\"\nreveal_type(C(0, use_tuple=True))  # N: Revealed type is \"lib.C[builtins.tuple[builtins.int, ...]]\"\n\nT = TypeVar('T')\nclass SubP(P[T]):\n    pass\n\nSubP('no')  # E: No overload variant of \"SubP\" matches argument type \"str\" \\\n            # N: Possible overload variants: \\\n            # N:     def [T] __init__(self, use_str: Literal[True]) -> SubP[T] \\\n            # N:     def [T] __init__(self, use_str: Literal[False]) -> SubP[T]\n\n# This is a bit unfortunate: we don't have a way to map the overloaded __init__ to subtype.\nx = SubP(use_str=True)  # E: Need type annotation for \"x\"\nreveal_type(x)  # N: Revealed type is \"__main__.SubP[Any]\"\ny: SubP[str] = SubP(use_str=True)\n\n[file lib.pyi]\nfrom typing import TypeVar, Generic, overload, Tuple\nfrom typing_extensions import Literal\n\nT = TypeVar('T')\nclass P(Generic[T]):\n    @overload\n    def __init__(self: P[str], use_str: Literal[True]) -> None: ...\n    @overload\n    def __init__(self: P[int], use_str: Literal[False]) -> None: ...\n\nclass C(Generic[T]):\n    @overload\n    def __init__(self: C[T], item: T, use_tuple: Literal[False]) -> None: ...\n    @overload\n    def __init__(self: C[Tuple[T, ...]], item: T, use_tuple: Literal[True]) -> None: ...\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeRestrictedMethodOverloadInitFallBacks]\nfrom lib import PFallBack, PFallBackAny\n\nt: bool\nxx = PFallBack(t)  # E: Need type annotation for \"xx\"\nyy = PFallBackAny(t)  # OK\n\n[file lib.pyi]\nfrom typing import TypeVar, Generic, overload, Tuple, Any\nfrom typing_extensions import Literal\n\nclass PFallBack(Generic[T]):\n    @overload\n    def __init__(self: PFallBack[str], use_str: Literal[True]) -> None: ...\n    @overload\n    def __init__(self: PFallBack[int], use_str: Literal[False]) -> None: ...\n    @overload\n    def __init__(self, use_str: bool) -> None: ...\n\nclass PFallBackAny(Generic[T]):\n    @overload\n    def __init__(self: PFallBackAny[str], use_str: Literal[True]) -> None: ...\n    @overload\n    def __init__(self: PFallBackAny[int], use_str: Literal[False]) -> None: ...\n    @overload\n    def __init__(self: PFallBackAny[Any], use_str: bool) -> None: ...\n[builtins fixtures/bool.pyi]\n\n[case testSelfTypeRestrictedMethodOverloadInitBadTypeNoCrash]\nfrom lib import P\nP(0)\n[file lib.pyi]\nfrom typing import overload\n\nclass P:\n    @overload\n    def __init__(self: Bad, x: int) -> None: ...  # E: Name \"Bad\" is not defined\n    @overload\n    def __init__(self) -> None: ...\n\n[case testSelfTypeNarrowBinding]\nfrom typing import TypeVar, List, Generic\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass Base(Generic[T]):\n    def get_item(self: Base[List[S]]) -> S: ...\n\nclass Sub(Base[List[int]]): ...\nclass BadSub(Base[int]): ...\n\nreveal_type(Sub().get_item())  # N: Revealed type is \"builtins.int\"\nBadSub().get_item()  # E: Invalid self argument \"BadSub\" to attribute function \"get_item\" with type \"Callable[[Base[List[S]]], S]\"\n[builtins fixtures/list.pyi]\n\n[case testMixinAllowedWithProtocol]\nfrom typing import TypeVar\nfrom typing_extensions import Protocol\n\nclass Resource(Protocol):\n    def close(self) -> int: ...\n\nclass AtomicClose:\n    def atomic_close(self: Resource) -> int:\n        return self.close()\n\nT = TypeVar('T', bound=Resource)\nclass Copyable:\n    def copy(self: T) -> T: ...\n\nclass File(AtomicClose, Copyable):\n    def close(self) -> int:\n       ...\n\nclass Bad(AtomicClose, Copyable):\n    ...\n\nf: File\nb: Bad\nf.atomic_close()  # OK\nb.atomic_close()  # E: Invalid self argument \"Bad\" to attribute function \"atomic_close\" with type \"Callable[[Resource], int]\"\n\nreveal_type(f.copy())  # N: Revealed type is \"__main__.File\"\nb.copy()  # E: Invalid self argument \"Bad\" to attribute function \"copy\" with type \"Callable[[T], T]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMixinProtocolSuper]\nfrom typing import Protocol\n\nclass Base(Protocol):\n    def func(self) -> int:\n        ...\n\nclass TweakFunc:\n    def func(self: Base) -> int:\n        return reveal_type(super().func())  # E: Call to abstract method \"func\" of \"Base\" with trivial body via super() is unsafe \\\n                                            # N: Revealed type is \"builtins.int\"\n\nclass Good:\n    def func(self) -> int: ...\nclass C(TweakFunc, Good): pass\nC().func()  # OK\n\nclass Bad:\n    def func(self) -> str: ...\nclass CC(TweakFunc, Bad): pass  # E: Definition of \"func\" in base class \"TweakFunc\" is incompatible with definition in base class \"Bad\"\n\n[case testBadClassLevelDecoratorHack]\nfrom typing_extensions import Protocol\nfrom typing import TypeVar, Any\n\nclass FuncLike(Protocol):\n    __call__: Any\nF = TypeVar('F', bound=FuncLike)\n\nclass Test:\n    def _deco(func: F) -> F: ...\n\n    @_deco\n    def meth(self, x: str) -> int: ...\n\nreveal_type(Test().meth)  # N: Revealed type is \"def (x: builtins.str) -> builtins.int\"\nTest()._deco  # E: Invalid self argument \"Test\" to attribute function \"_deco\" with type \"Callable[[F], F]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeTrickyExample]\nfrom typing import *\n\nIn = TypeVar('In')\nOut = TypeVar('Out')\nMid = TypeVar('Mid')\nNewOut = TypeVar('NewOut')\n\nclass Lnk(Generic[In, Out]):\n    def test(self: Lnk[In, Mid], other: Lnk[Mid, NewOut]) -> Lnk[In, NewOut]: ...\n\nclass X: pass\nclass Y: pass\nclass Z: pass\n\na: Lnk[X, Y] = Lnk()\nb: Lnk[Y, Z] = Lnk()\n\na.test(b)\nb.test(a)  # E: Argument 1 to \"test\" of \"Lnk\" has incompatible type \"Lnk[X, Y]\"; expected \"Lnk[Z, Y]\"\n\n[case testSelfTypeReallyTrickyExample]\nfrom typing import *\n\nIn = TypeVar('In')\nOut = TypeVar('Out')\nOther = TypeVar('Other')\n\n_1 = TypeVar('_1')\n_2 = TypeVar('_2')\n__1 = TypeVar('__1')\n__2 = TypeVar('__2')\n\nclass Lnk(Generic[In, Out]):\n    @overload\n    def __rshift__(self, other: Lnk[Out, Other]) -> Lnk[In,Other]: ...\n    @overload\n    def __rshift__(self: Lnk[In, Tuple[_1, _2]],\n                   other: Tuple[Lnk[_1, __1], Lnk[_2, __2]]) -> Lnk[In, Tuple[__1, __2]]: ...\n    def __rshift__(self: Any, other: Any) -> Any:\n        ...\n\na: Lnk[str, Tuple[str, int]] = Lnk()\nb: Lnk[str, int] = Lnk()\nc: Lnk[int, float] = Lnk()\n\nd: Lnk[str, float] = b >> c  # OK\ne: Lnk[str, Tuple[int, float]] = a >> (b, c)  # OK\nf: Lnk[str, Tuple[float, int]] = a >> (c, b) # E: Unsupported operand types for >> (\"Lnk[str, Tuple[str, int]]\" and \"Tuple[Lnk[int, float], Lnk[str, int]]\")\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeMutuallyExclusiveRestrictions]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass Foo(Generic[T]):\n    def f1(self: Foo[str]) -> None:\n        self.f2()  # E: Invalid self argument \"Foo[str]\" to attribute function \"f2\" with type \"Callable[[Foo[int]], None]\"\n    def f2(self: Foo[int]) -> None:\n        self.f1()  # E: Invalid self argument \"Foo[int]\" to attribute function \"f1\" with type \"Callable[[Foo[str]], None]\"\n\n[case testSelfTypeStructureMetaclassMatch]\nfrom typing import TypeVar, Type, Generic, cast\n\nCls = TypeVar('Cls')\nT = TypeVar('T')\n\nclass Manager(Generic[Cls]):\n    def create(self: Manager[Type[T]]) -> T: ...\n\nclass ModelMeta(type):\n    @property\n    def objects(cls: T) -> Manager[T]: ...\n\nclass Model(metaclass=ModelMeta):\n    pass\n\nclass Dog(Model): ...\nclass Cat(Model): ...\n\nc: Cat = Dog.objects.create()  # E: Incompatible types in assignment (expression has type \"Dog\", variable has type \"Cat\")\nd: Dog = Dog.objects.create()\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeProtocolMetaclassMatch]\nfrom typing import Type, TypeVar, Protocol\n\nclass HasX(Protocol):\n    x: int\n\nT = TypeVar('T', bound=HasX)\n\nclass Meta(type):\n    def do_x(cls: Type[T]) -> T:\n        cls.x\n        return cls()\n\nclass Good(metaclass=Meta):\n    x: int\nclass Bad(metaclass=Meta):\n    pass\n\nGood.do_x()\nBad.do_x()  # E: Invalid self argument \"Type[Bad]\" to attribute function \"do_x\" with type \"Callable[[Type[T]], T]\"\n\n[case testSelfTypeProtocolClassmethodMatch]\nfrom typing import Type, TypeVar, Protocol\n\nT = TypeVar('T')\n\nclass HasDoX(Protocol):\n    @classmethod\n    def do_x(cls: Type[T]) -> T:\n        ...\n\nclass Good:\n    @classmethod\n    def do_x(cls) -> 'Good':\n        ...\n\nclass Bad:\n    @classmethod\n    def do_x(cls) -> Good:\n        ...\n\ngood: HasDoX = Good()\nbad: HasDoX = Bad()\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:21: error: Incompatible types in assignment (expression has type \"Bad\", variable has type \"HasDoX\")\nmain:21: note: Following member(s) of \"Bad\" have conflicts:\nmain:21: note:     Expected:\nmain:21: note:         def do_x(cls) -> Bad\nmain:21: note:     Got:\nmain:21: note:         def do_x(cls) -> Good\n\n[case testSelfTypeNotSelfType]\n# Friendlier error messages for common mistakes. See #2950\nclass A:\n    def f(x: int) -> None: ...\n    def g(self: None) -> None: ...\n[out]\nmain:3: error: Self argument missing for a non-static method (or an invalid type for self)\nmain:4: error: The erased type of self \"None\" is not a supertype of its class \"__main__.A\"\n\n[case testUnionPropertyField]\nfrom typing import Union\n\nclass A:\n    x: int\n\nclass B:\n    @property\n    def x(self) -> int: return 1\n\nclass C:\n    @property\n    def x(self) -> int: return 1\n\nab: Union[A, B, C]\nreveal_type(ab.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n\n[case testSelfTypeNoTypeVars]\nfrom typing import Generic, List, Optional, TypeVar, Any\n\nQ = TypeVar(\"Q\")\nT = TypeVar(\"T\", bound='Super[Any]')\n\nclass Super(Generic[Q]):\n    @classmethod\n    def meth(cls, arg: List[T]) -> List[T]:\n        pass\n\nclass Sub(Super[int]): ...\n\ndef test(x: List[Sub]) -> None:\n    reveal_type(Sub.meth(x))  # N: Revealed type is \"builtins.list[__main__.Sub]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testSelfTypeNoTypeVarsRestrict]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass C(Generic[T]):\n    def limited(self: C[str], arg: S) -> S: ...\n\nreveal_type(C[str]().limited(0))  # N: Revealed type is \"builtins.int\"\n\n[case testSelfTypeMultipleTypeVars]\nfrom typing import Generic, TypeVar, Tuple\n\nT = TypeVar('T')\nS = TypeVar('S')\nU = TypeVar('U')\nV = TypeVar('V')\n\nclass C(Generic[T]):\n    def magic(self: C[Tuple[S, U]]) -> Tuple[T, S, U]: ...\n\nclass D(Generic[V]):\n    def f(self) -> None:\n        reveal_type(C[Tuple[V, str]]().magic())  # N: Revealed type is \"Tuple[Tuple[V`1, builtins.str], V`1, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeOnUnion]\nfrom typing import TypeVar, Union\n\nT = TypeVar('T')\n\nclass A:\n    same: int\n\nclass C:\n    def same(self: T) -> T: ...\n\nx: Union[A, C]\nreveal_type(x.same)  # N: Revealed type is \"Union[builtins.int, def () -> __main__.C]\"\n\n[case testSelfTypeOnUnionClassMethod]\nfrom typing import TypeVar, Union, Type\n\nT = TypeVar('T')\n\nclass A:\n    same: int\n\nclass C:\n    @classmethod\n    def same(cls: Type[T]) -> T: ...\n\nx: Union[A, C]\nreveal_type(x.same)  # N: Revealed type is \"Union[builtins.int, def () -> __main__.C]\"\n[builtins fixtures/classmethod.pyi]\n\n[case SelfTypeOverloadedClassMethod]\nfrom lib import Base\nfrom typing import overload, Tuple\n\nclass Sub(Base):\n    @overload\n    @classmethod\n    def make(cls) -> Sub: ...\n    @overload\n    @classmethod\n    def make(cls, num: int) -> Tuple[Sub, ...]: ...\n    @classmethod\n    def make(cls, num=1):\n        ...\n\nclass Other(Base): ...\nclass Double(Sub): ...\n\nreveal_type(Other.make())  # N: Revealed type is \"__main__.Other\"\nreveal_type(Other.make(3))  # N: Revealed type is \"builtins.tuple[__main__.Other, ...]\"\nreveal_type(Double.make())  # N: Revealed type is \"__main__.Sub\"\nreveal_type(Double.make(3))  # N: Revealed type is \"builtins.tuple[__main__.Sub, ...]\"\n[file lib.pyi]\nfrom typing import overload, TypeVar, Type, Tuple\n\nT = TypeVar('T', bound=Base)\n\nclass Base:\n    @overload\n    @classmethod\n    def make(cls: Type[T]) -> T: ...\n    @overload\n    @classmethod\n    def make(cls: Type[T], num: int) -> Tuple[T, ...]: ...\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeClassMethodOnUnion]\nfrom typing import Type, Union, TypeVar\n\nT = TypeVar('T')\n\nclass A:\n    @classmethod\n    def meth(cls: Type[T]) -> T: ...\nclass B(A): ...\nclass C(A): ...\n\nt: Type[Union[B, C]]\nreveal_type(t.meth)  # N: Revealed type is \"Union[def () -> __main__.B, def () -> __main__.C]\"\nx = t.meth()\nreveal_type(x)  # N: Revealed type is \"Union[__main__.B, __main__.C]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeClassMethodOnUnionGeneric]\nfrom typing import Type, Union, TypeVar, Generic\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Generic[T]):\n    @classmethod\n    def meth(cls: Type[S]) -> S: ...\n\nt: Type[Union[A[int], A[str]]]\nx = t.meth()\nreveal_type(x)  # N: Revealed type is \"Union[__main__.A[builtins.int], __main__.A[builtins.str]]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeClassMethodOnUnionList]\nfrom typing import Type, Union, TypeVar, List\n\nT = TypeVar('T')\n\nclass A:\n    @classmethod\n    def meth(cls: Type[T]) -> List[T]: ...\nclass B(A): ...\nclass C(A): ...\n\nt: Type[Union[B, C]]\nx = t.meth()[0]\nreveal_type(x)  # N: Revealed type is \"Union[__main__.B, __main__.C]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testSelfTypeClassMethodOverloadedOnInstance]\nfrom typing import Optional, Type, TypeVar, overload, Union\n\nId = int\n\nA = TypeVar(\"A\", bound='AClass')\n\nclass AClass:\n    @overload\n    @classmethod\n    def delete(cls: Type[A], id: Id, id2: Id) -> Optional[int]: ...\n\n    @overload\n    @classmethod\n    def delete(cls: Type[A], id: A, id2: None = None) -> Optional[int]: ...\n\n    @classmethod\n    def delete(cls: Type[A], id: Union[A, Id], id2: Optional[Id] = None) -> Optional[int]:\n        ...\n\ndef foo(x: Type[AClass]) -> None:\n    reveal_type(x.delete)  # N: Revealed type is \"Overload(def (id: builtins.int, id2: builtins.int) -> Union[builtins.int, None], def (id: __main__.AClass, id2: None =) -> Union[builtins.int, None])\"\n    y = x()\n    reveal_type(y.delete)  # N: Revealed type is \"Overload(def (id: builtins.int, id2: builtins.int) -> Union[builtins.int, None], def (id: __main__.AClass, id2: None =) -> Union[builtins.int, None])\"\n    y.delete(10, 20)\n    y.delete(y)\n\ndef bar(x: AClass) -> None:\n    reveal_type(x.delete)  # N: Revealed type is \"Overload(def (id: builtins.int, id2: builtins.int) -> Union[builtins.int, None], def (id: __main__.AClass, id2: None =) -> Union[builtins.int, None])\"\n    x.delete(10, 20)\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeBadTypeIgnoredInConstructor]\nclass Base: ...\nclass Sub(Base):\n    def __init__(self: Base) -> None: ...\n\nreveal_type(Sub())  # N: Revealed type is \"__main__.Sub\"\n\n[case testSelfTypeBadTypeIgnoredInConstructorGeneric]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass Base(Generic[T]): ...\nclass Sub(Base[T]):\n    def __init__(self: Base[T], item: T) -> None: ...\n\nreveal_type(Sub(42))  # N: Revealed type is \"__main__.Sub[builtins.int]\"\n\n[case testSelfTypeBadTypeIgnoredInConstructorOverload]\nfrom typing import overload\n\nclass Base: ...\nclass Sub(Base):\n    @overload\n    def __init__(self: Sub, item: int) -> None: ...\n    @overload\n    def __init__(self: Base) -> None: ...\n    def __init__(self, item=None):\n        ...\n\nreveal_type(Sub)  # N: Revealed type is \"Overload(def (item: builtins.int) -> __main__.Sub, def () -> __main__.Sub)\"\n\n[case testSelfTypeBadTypeIgnoredInConstructorAbstract]\nfrom abc import abstractmethod\nfrom typing import Protocol\n\nclass Blah(Protocol):\n    @abstractmethod\n    def something(self) -> None: ...\n\nclass Concrete(Blah):\n    def __init__(self: Blah) -> None: ...\n    def something(self) -> None: ...\n\nConcrete()  # OK\n\n[case testSelfTypeGenericClassNoClashInstanceMethod]\nfrom typing import TypeVar, Generic\n\nM = TypeVar(\"M\")\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass Descriptor(Generic[M]): ...\n\nclass BaseWrapper(Generic[M]):\n    def create_wrapper(self: T, metric_descriptor: Descriptor[M]) -> T: ...\nclass SubWrapper(BaseWrapper[M]): ...\n\ndef build_wrapper(descriptor: Descriptor[M]) -> BaseWrapper[M]:\n    wrapper: BaseWrapper[M]\n    return wrapper.create_wrapper(descriptor)\n\ndef build_sub_wrapper(descriptor: Descriptor[S]) -> SubWrapper[S]:\n    wrapper: SubWrapper[S]\n    x = wrapper.create_wrapper(descriptor)\n    reveal_type(x)  # N: Revealed type is \"__main__.SubWrapper[S`-1]\"\n    return x\n\n[case testSelfTypeGenericClassNoClashClassMethod]\nfrom typing import TypeVar, Generic, Type\n\nM = TypeVar(\"M\")\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass Descriptor(Generic[M]): ...\n\nclass BaseWrapper(Generic[M]):\n    @classmethod\n    def create_wrapper(cls: Type[T], metric_descriptor: Descriptor[M]) -> T: ...\nclass SubWrapper(BaseWrapper[M]): ...\n\ndef build_wrapper(descriptor: Descriptor[M]) -> BaseWrapper[M]:\n    wrapper_cls: Type[BaseWrapper[M]]\n    return wrapper_cls.create_wrapper(descriptor)\n\ndef build_sub_wrapper(descriptor: Descriptor[S]) -> SubWrapper[S]:\n    wrapper_cls: Type[SubWrapper[S]]\n    x = wrapper_cls.create_wrapper(descriptor)\n    reveal_type(x)  # N: Revealed type is \"__main__.SubWrapper[S`-1]\"\n    return x\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeGenericClassNoClashClassMethodClassObject]\nfrom typing import TypeVar, Generic, Type\n\nM = TypeVar(\"M\")\nT = TypeVar(\"T\")\n\nclass Descriptor(Generic[M]): ...\n\nclass BaseWrapper(Generic[M]):\n    @classmethod\n    def create_wrapper(cls: Type[T], metric_descriptor: Descriptor[M]) -> T: ...\nclass SubWrapper(BaseWrapper[M]): ...\n\ndef build_wrapper(descriptor: Descriptor[M]) -> BaseWrapper[M]:\n    return BaseWrapper.create_wrapper(descriptor)\n\ndef build_sub_wrapper(descriptor: Descriptor[M]) -> SubWrapper[M]:\n    x = SubWrapper.create_wrapper(descriptor)\n    reveal_type(x)  # N: Revealed type is \"__main__.SubWrapper[M`-1]\"\n    return x\n\ndef build_wrapper_non_gen(descriptor: Descriptor[int]) -> BaseWrapper[str]:\n    return BaseWrapper.create_wrapper(descriptor)  # E: Argument 1 to \"create_wrapper\" of \"BaseWrapper\" has incompatible type \"Descriptor[int]\"; expected \"Descriptor[str]\"\n\ndef build_sub_wrapper_non_gen(descriptor: Descriptor[int]) -> SubWrapper[str]:\n    return SubWrapper.create_wrapper(descriptor)  # E: Argument 1 to \"create_wrapper\" of \"BaseWrapper\" has incompatible type \"Descriptor[int]\"; expected \"Descriptor[str]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeInGenericClassUsedFromAnotherGenericClass1]\nfrom typing import TypeVar, Generic, Iterator, List, Tuple\n\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\nS = TypeVar(\"S\")\n\nclass Z(Iterator[_T_co]):\n    def __new__(cls,\n                __iter1: List[_T1],\n                __iter2: List[_T2]) -> Z[Tuple[_T1, _T2]]: ...\n    def __iter__(self: S) -> S: ...\n    def __next__(self) -> _T_co: ...\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    a: List[T]\n    b: List[str]\n\n    def f(self) -> None:\n        for x, y in Z(self.a, self.b):\n            reveal_type((x, y))  # N: Revealed type is \"Tuple[T`1, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testEnumerateReturningSelfFromIter]\nfrom typing import Generic, Iterable, Iterator, TypeVar, Tuple\n\nT = TypeVar(\"T\")\nKT = TypeVar(\"KT\")\nVT = TypeVar(\"VT\")\nSelf = TypeVar(\"Self\")\n\nclass enumerate(Iterator[Tuple[int, T]], Generic[T]):\n    def __init__(self, iterable: Iterable[T]) -> None: ...\n    def __iter__(self: Self) -> Self: ...\n    def __next__(self) -> Tuple[int, T]: ...\n\nclass Dict(Generic[KT, VT]):\n    def update(self, __m: Iterable[Tuple[KT, VT]]) -> None: ...\n\nclass ThingCollection(Generic[T]):\n    collection: Iterable[Tuple[float, T]]\n    index: Dict[int, T]\n\n    def do_thing(self) -> None:\n        self.index.update((idx, c) for idx, (k, c) in enumerate(self.collection))\n[builtins fixtures/tuple.pyi]\n\n[case testDequeReturningSelfFromCopy]\n# Tests a bug with generic self types identified in issue #12641\nfrom typing import Generic, Sequence, TypeVar\n\nT = TypeVar(\"T\")\nSelf = TypeVar(\"Self\")\n\nclass deque(Sequence[T]):\n    def copy(self: Self) -> Self: ...\n\nclass List(Sequence[T]): ...\n\nclass Test(Generic[T]):\n    def test(self) -> None:\n        a: deque[List[T]]\n        # previously this failed with 'Incompatible types in assignment (expression has type \"deque[List[List[T]]]\", variable has type \"deque[List[T]]\")'\n        b: deque[List[T]] = a.copy()\n\n[case testTypingSelfBasic]\nfrom typing import Self, List\n\nclass C:\n    attr: List[Self]\n    def meth(self) -> List[Self]: ...\n    def test(self) -> Self:\n        if bool():\n            return C()  # E: Incompatible return value type (got \"C\", expected \"Self\")\n        else:\n            return self\nclass D(C): ...\n\nreveal_type(C.meth)  # N: Revealed type is \"def [Self <: __main__.C] (self: Self`1) -> builtins.list[Self`1]\"\nC.attr  # E: Access to generic instance variables via class is ambiguous\nreveal_type(D().meth())  # N: Revealed type is \"builtins.list[__main__.D]\"\nreveal_type(D().attr)  # N: Revealed type is \"builtins.list[__main__.D]\"\n\n[case testTypingSelfInvalidLocations]\nfrom typing import Self, Callable\n\nvar: Self  # E: Self type is only allowed in annotations within class definition\nreveal_type(var)  # N: Revealed type is \"Any\"\n\ndef foo() -> Self: ...  # E: Self type is only allowed in annotations within class definition\nreveal_type(foo)  # N: Revealed type is \"def () -> Any\"\n\nbad: Callable[[Self], Self]  # E: Self type is only allowed in annotations within class definition \\\n                             # E: Self type is only allowed in annotations within class definition\nreveal_type(bad)  # N: Revealed type is \"def (Any) -> Any\"\n\ndef func() -> None:\n    var: Self  # E: Self type is only allowed in annotations within class definition\n\nclass C(Self): ...  # E: Self type is only allowed in annotations within class definition\n\n[case testTypingSelfInvalidArgs]\nfrom typing import Self, List\n\nclass C:\n    x: Self[int]  # E: Self type cannot have type arguments\n    def meth(self) -> List[Self[int]]:  # E: Self type cannot have type arguments\n        ...\n\n[case testTypingSelfConflict]\nfrom typing import Self, TypeVar, Tuple\n\nT = TypeVar(\"T\")\nclass C:\n    def meth(self: T) -> Tuple[Self, T]: ...  # E: Method cannot have explicit self annotation and Self type\nreveal_type(C().meth())  # N: Revealed type is \"Tuple[Never, __main__.C]\"\n[builtins fixtures/property.pyi]\n\n[case testTypingSelfProperty]\nfrom typing import Self, Tuple\nclass C:\n    @property\n    def attr(self) -> Tuple[Self, ...]: ...\nclass D(C): ...\n\nreveal_type(D().attr)  # N: Revealed type is \"builtins.tuple[__main__.D, ...]\"\n[builtins fixtures/property.pyi]\n\n[case testTypingSelfCallableVar]\nfrom typing import Self, Callable\n\nclass C:\n    x: Callable[[Self], Self]\n    def meth(self) -> Callable[[Self], Self]: ...\nclass D(C): ...\n\nreveal_type(C().x)  # N: Revealed type is \"def (__main__.C) -> __main__.C\"\nreveal_type(D().x)  # N: Revealed type is \"def (__main__.D) -> __main__.D\"\nreveal_type(D().meth())  # N: Revealed type is \"def (__main__.D) -> __main__.D\"\n\n[case testTypingSelfClassMethod]\nfrom typing import Self\n\nclass C:\n    @classmethod\n    def meth(cls) -> Self: ...\n    @staticmethod\n    def bad() -> Self: ...  # E: Static methods cannot use Self type \\\n        # E: A function returning TypeVar should receive at least one argument containing the same TypeVar \\\n        # N: Consider using the upper bound \"C\" instead\n\nclass D(C): ...\nreveal_type(D.meth())  # N: Revealed type is \"__main__.D\"\nreveal_type(D.bad())  # N: Revealed type is \"Never\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfOverload]\nfrom typing import Self, overload, Union\n\nclass C:\n    @overload\n    def foo(self, other: Self) -> Self: ...\n    @overload\n    def foo(self, other: int) -> int: ...\n    def foo(self, other: Union[Self, int]) -> Union[Self, int]:\n        return other\nclass D(C): ...\nreveal_type(D().foo)  # N: Revealed type is \"Overload(def (other: __main__.D) -> __main__.D, def (other: builtins.int) -> builtins.int)\"\n\n[case testTypingSelfNestedInAlias]\nfrom typing import Generic, Self, TypeVar, List, Tuple\n\nT = TypeVar(\"T\")\nPairs = List[Tuple[T, T]]\n\nclass C(Generic[T]):\n    def pairs(self) -> Pairs[Self]: ...\nclass D(C[T]): ...\nreveal_type(D[int]().pairs())  # N: Revealed type is \"builtins.list[Tuple[__main__.D[builtins.int], __main__.D[builtins.int]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingSelfOverrideVar]\nfrom typing import Self, TypeVar, Generic\n\nT = TypeVar(\"T\")\nclass C(Generic[T]):\n    x: Self\n\nclass D(C[int]):\n    x: D\nclass Bad(C[int]):\n    x: C[int]  # E: Incompatible types in assignment (expression has type \"C[int]\", base class \"C\" defined the type as \"Bad\")\n\n[case testTypingSelfOverrideVarMulti]\nfrom typing import Self\n\nclass C:\n    x: Self\nclass D:\n    x: C\nclass E:\n    x: Good\n\nclass Bad(D, C):  # E: Definition of \"x\" in base class \"D\" is incompatible with definition in base class \"C\"\n    ...\nclass Good(E, C):\n    ...\n\n[case testTypingSelfAlternativeGenericConstructor]\nfrom typing import Self, Generic, TypeVar, Tuple\n\nT = TypeVar(\"T\")\nclass C(Generic[T]):\n    def __init__(self, val: T) -> None: ...\n    @classmethod\n    def pair(cls, val: T) -> Tuple[Self, Self]:\n        return (cls(val), C(val))  # E: Incompatible return value type (got \"Tuple[Self, C[T]]\", expected \"Tuple[Self, Self]\")\n\nclass D(C[int]): pass\nreveal_type(C.pair(42))  # N: Revealed type is \"Tuple[__main__.C[builtins.int], __main__.C[builtins.int]]\"\nreveal_type(D.pair(\"no\"))  # N: Revealed type is \"Tuple[__main__.D, __main__.D]\" \\\n    # E: Argument 1 to \"pair\" of \"C\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfMixedTypeVars]\nfrom typing import Self, TypeVar, Generic, Tuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass C(Generic[T]):\n    def meth(self, arg: S) -> Tuple[Self, S, T]: ...\n\nclass D(C[int]): ...\n\nc: C[int]\nd: D\nreveal_type(c.meth(\"test\"))  # N: Revealed type is \"Tuple[__main__.C[builtins.int], builtins.str, builtins.int]\"\nreveal_type(d.meth(\"test\"))  # N: Revealed type is \"Tuple[__main__.D, builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingSelfRecursiveInit]\nfrom typing import Self\n\nclass C:\n    def __init__(self, other: Self) -> None: ...\nclass D(C): ...\n\nreveal_type(C)  # N: Revealed type is \"def (other: __main__.C) -> __main__.C\"\nreveal_type(D)  # N: Revealed type is \"def (other: __main__.D) -> __main__.D\"\n\n[case testTypingSelfCorrectName]\nfrom typing import Self, List\n\nclass C:\n    Self = List[C]\n    def meth(self) -> Self: ...\nreveal_type(C.meth)  # N: Revealed type is \"def (self: __main__.C) -> builtins.list[__main__.C]\"\n\n[case testTypingSelfClassVar]\nfrom typing import Self, ClassVar, Generic, TypeVar\n\nclass C:\n    DEFAULT: ClassVar[Self]\nreveal_type(C.DEFAULT)  # N: Revealed type is \"__main__.C\"\n\nT = TypeVar(\"T\")\nclass G(Generic[T]):\n    BAD: ClassVar[Self]  # E: ClassVar cannot contain Self type in generic classes\nreveal_type(G.BAD)  # N: Revealed type is \"__main__.G[Any]\"\n\n[case testTypingSelfMetaClassDisabled]\nfrom typing import Self\n\nclass Meta(type):\n    def meth(cls) -> Self: ...  # E: Self type cannot be used in a metaclass\n\n[case testTypingSelfNonAnnotationUses]\nfrom typing import Self, List, cast\n\nclass C:\n    A = List[Self]  # E: Self type cannot be used in type alias target\n    B = cast(Self, ...)\n    def meth(self) -> A: ...\n\nclass D(C): ...\nreveal_type(D().meth())  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(D().B)  # N: Revealed type is \"__main__.D\"\n\n[case testTypingSelfInternalSafe]\nfrom typing import Self\n\nclass C:\n    x: Self\n    def __init__(self, x: C) -> None:\n        self.x = x  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"Self\")\n\n[case testTypingSelfRedundantAllowed]\nfrom typing import Self, Type\n\nclass C:\n    def f(self: Self) -> Self:\n        d: Defer\n        class Defer: ...\n        return self\n\n    @classmethod\n    def g(cls: Type[Self]) -> Self:\n        d: DeferAgain\n        class DeferAgain: ...\n        return cls()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfRedundantAllowed_pep585]\n# flags: --python-version 3.9\nfrom typing import Self\n\nclass C:\n    def f(self: Self) -> Self:\n        d: Defer\n        class Defer: ...\n        return self\n\n    @classmethod\n    def g(cls: type[Self]) -> Self:\n        d: DeferAgain\n        class DeferAgain: ...\n        return cls()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfRedundantWarning]\n# mypy: enable-error-code=\"redundant-self\"\n\nfrom typing import Self, Type\n\nclass C:\n    def copy(self: Self) -> Self:  # E: Redundant \"Self\" annotation for the first method argument\n        d: Defer\n        class Defer: ...\n        return self\n\n    @classmethod\n    def g(cls: Type[Self]) -> Self:  # E: Redundant \"Self\" annotation for the first method argument\n        d: DeferAgain\n        class DeferAgain: ...\n        return cls()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfRedundantWarning_pep585]\n# flags: --python-version 3.9\n# mypy: enable-error-code=\"redundant-self\"\n\nfrom typing import Self\n\nclass C:\n    def copy(self: Self) -> Self:  # E: Redundant \"Self\" annotation for the first method argument\n        d: Defer\n        class Defer: ...\n        return self\n\n    @classmethod\n    def g(cls: type[Self]) -> Self:  # E: Redundant \"Self\" annotation for the first method argument\n        d: DeferAgain\n        class DeferAgain: ...\n        return cls()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfAssertType]\nfrom typing import Self, assert_type\n\nclass C:\n    def foo(self) -> None:\n        assert_type(self, Self)  # E: Expression is of type \"C\", not \"Self\"\n        assert_type(C(), Self)  # E: Expression is of type \"C\", not \"Self\"\n\n    def bar(self) -> Self:\n        assert_type(self, Self)  # OK\n        assert_type(C(), Self)  # E: Expression is of type \"C\", not \"Self\"\n        return self\n\n[case testTypingSelfTypeVarClash]\nfrom typing import Self, TypeVar, Tuple\n\nS = TypeVar(\"S\")\nclass C:\n    def bar(self) -> Self: ...\n    def foo(self, x: S) -> Tuple[Self, S]: ...\n\nreveal_type(C.foo)  # N: Revealed type is \"def [Self <: __main__.C, S] (self: Self`1, x: S`2) -> Tuple[Self`1, S`2]\"\nreveal_type(C().foo(42))  # N: Revealed type is \"Tuple[__main__.C, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingSelfTypeVarClashAttr]\nfrom typing import Self, TypeVar, Tuple, Callable\n\nclass Defer(This): ...\n\nS = TypeVar(\"S\")\nclass C:\n    def bar(self) -> Self: ...\n    foo: Callable[[S, Self], Tuple[Self, S]]\n\nreveal_type(C().foo)  # N: Revealed type is \"def [S] (S`1, __main__.C) -> Tuple[__main__.C, S`1]\"\nreveal_type(C().foo(42, C()))  # N: Revealed type is \"Tuple[__main__.C, builtins.int]\"\nclass This: ...\n[builtins fixtures/tuple.pyi]\n\n[case testTypingSelfAttrOldVsNewStyle]\nfrom typing import Self, TypeVar\n\nT = TypeVar(\"T\", bound='C')\nclass C:\n    x: Self\n    def foo(self: T) -> T:\n        return self.x\n    def bar(self: T) -> T:\n        self.x = self\n        return self\n    def baz(self: Self) -> None:\n        self.x = self\n    def bad(self) -> None:\n        # This is unfortunate, but required by PEP 484\n        self.x = self  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"Self\")\n\n[case testTypingSelfClashInBodies]\nfrom typing import Self, TypeVar\n\nT = TypeVar(\"T\")\nclass C:\n    def very_bad(self, x: T) -> None:\n        self.x = x  # E: Incompatible types in assignment (expression has type \"T\", variable has type \"Self\")\n    x: Self\n    def baz(self: Self, x: T) -> None:\n        y: T = x\n\n[case testTypingSelfClashUnrelated]\nfrom typing import Self, Generic, TypeVar\n\nclass B: ...\n\nT = TypeVar(\"T\", bound=B)\nclass C(Generic[T]):\n    def __init__(self, val: T) -> None:\n        self.val = val\n    def foo(self) -> Self: ...\n\ndef test(x: C[T]) -> T:\n    reveal_type(x.val)  # N: Revealed type is \"T`-1\"\n    return x.val\n\n[case testTypingSelfGenericBound]\nfrom typing import Self, Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass C(Generic[T]):\n    val: T\n    def foo(self) -> Self:\n        reveal_type(self.val)  # N: Revealed type is \"T`1\"\n        return self\n\n[case testTypingSelfDifferentImport]\nimport typing as t\n\nclass Foo:\n    def foo(self) -> t.Self:\n        return self\n    @classmethod\n    def bar(cls) -> t.Self:\n        return cls()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypingSelfAllowAliasUseInFinalClasses]\nfrom typing import Self, final\n\n@final\nclass C:\n    def meth(self) -> Self:\n        return C()  # OK for final classes\n\n[case testTypingSelfCallableClassVar]\nfrom typing import Self, ClassVar, Callable, TypeVar\nfrom types import FunctionType\n\nclass C:\n    f1: ClassVar[Callable[[Self], Self]]\n    f2: ClassVar[\"FunctionType[[Self], Self]\"]\nclass D(C): ...\n\nreveal_type(D.f1)  # N: Revealed type is \"def (__main__.D) -> __main__.D\"\nreveal_type(D().f1)  # N: Revealed type is \"def (__main__.D) -> __main__.D\"\n\nreveal_type(D.f2)  # N: Revealed type is \"def (__main__.D) -> __main__.D\"\nreveal_type(D().f2)  # N: Revealed type is \"def () -> __main__.D\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfTypeCallableClassVarOldStyle]\nfrom typing import ClassVar, Callable, TypeVar\nfrom types import FunctionType\nT = TypeVar(\"T\")\nclass C:\n    f: ClassVar[\"FunctionType[[T], T]\"]\n\nclass D(C): ...\n\nreveal_type(D.f)  # N: Revealed type is \"def [T] (T`1) -> T`1\"\nreveal_type(D().f)  # N: Revealed type is \"def () -> __main__.D\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingSelfOnSuperTypeVarValues]\nfrom typing import Self, Generic, TypeVar\n\nT = TypeVar(\"T\", int, str)\n\nclass B:\n    def copy(self) -> Self: ...\nclass C(B, Generic[T]):\n    def copy(self) -> Self:\n        inst = super().copy()\n        reveal_type(inst)  # N: Revealed type is \"Self`0\"\n        return inst\n\n[case testTypingSelfWithValuesExpansion]\nfrom typing import Self, Generic, TypeVar\n\nclass A: pass\nclass B: pass\nT = TypeVar(\"T\", A, B)\n\nclass C(Generic[T]):\n    val: T\n    def foo(self, x: T) -> None: ...\n    def bar(self, x: T) -> Self:\n        reveal_type(self.foo)  # N: Revealed type is \"def (x: __main__.A)\" \\\n                               # N: Revealed type is \"def (x: __main__.B)\"\n        self.foo(x)\n        return self\n    def baz(self: Self, x: T) -> None:\n        reveal_type(self.val)  # N: Revealed type is \"__main__.A\" \\\n                               # N: Revealed type is \"__main__.B\"\n        self.val = x\n\n[case testNarrowSelfType]\nfrom typing import Self, Union\n\nclass A: ...\nclass B:\n    def f1(self, v: Union[Self, A]) -> A:\n        if isinstance(v, B):\n            return A()\n        else:\n            return v\n    def f2(self, v: Union[Self, A]) -> A:\n        if isinstance(v, B):\n            return A()\n        else:\n            return B()  # E: Incompatible return value type (got \"B\", expected \"A\")\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testAttributeOnSelfAttributeInSubclass]\nfrom typing import List, Self\n\nclass A:\n    x: Self\n    xs: List[Self]\n\nclass B(A):\n    extra: int\n\n    def meth(self) -> None:\n        reveal_type(self.x)  # N: Revealed type is \"Self`0\"\n        reveal_type(self.xs[0])  # N: Revealed type is \"Self`0\"\n        reveal_type(self.x.extra)  # N: Revealed type is \"builtins.int\"\n        reveal_type(self.xs[0].extra)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testSelfTypesWithParamSpecExtract]\nfrom typing import Any, Callable, Generic, TypeVar\nfrom typing_extensions import ParamSpec\nfrom types import FunctionType\n\nP = ParamSpec(\"P\")\nF = TypeVar(\"F\", bound=Callable[..., Any])\nclass Example(Generic[F]):\n    def __init__(self, fn: F) -> None:\n        ...\n    def __call__(self: Example[\"FunctionType[P, Any]\"], *args: P.args, **kwargs: P.kwargs) -> None:\n        ...\n\ndef test_fn(a: int, b: str) -> None:\n    ...\n\nexample = Example(test_fn)\nexample()  # E: Missing positional arguments \"a\", \"b\" in call to \"__call__\" of \"Example\"\nexample(1, \"b\")  # OK\n[builtins fixtures/list.pyi]\n\n[case testSelfTypesWithParamSpecInfer]\nfrom typing import TypeVar, Protocol, Type, Callable\nfrom typing_extensions import ParamSpec\n\nR = TypeVar(\"R\", covariant=True)\nP = ParamSpec(\"P\")\nclass AsyncP(Protocol[P]):\n    def meth(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        ...\n\nclass Async:\n    @classmethod\n    def async_func(cls: Type[AsyncP[P]]) -> Callable[P, int]:\n        ...\n\nclass Add(Async):\n    def meth(self, x: int, y: int) -> None: ...\n\nreveal_type(Add.async_func())  # N: Revealed type is \"def (x: builtins.int, y: builtins.int) -> builtins.int\"\nreveal_type(Add().async_func())  # N: Revealed type is \"def (x: builtins.int, y: builtins.int) -> builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSelfTypeMethodOnClassObject]\nfrom typing import Self\n\nclass Object:  # Needed to mimic object in typeshed\n    ref: Self\n\nclass Foo:\n    def foo(self) -> Self:\n        return self\n\nclass Ben(Object):\n    MY_MAP = {\n        \"foo\": Foo.foo,\n    }\n    @classmethod\n    def doit(cls) -> Foo:\n        reveal_type(cls.MY_MAP)  # N: Revealed type is \"builtins.dict[builtins.str, def [Self <: __main__.Foo] (self: Self`4) -> Self`4]\"\n        foo_method = cls.MY_MAP[\"foo\"]\n        return foo_method(Foo())\n[builtins fixtures/isinstancelist.pyi]\n\n[case testSelfTypeOnGenericClassObjectNewStyleBound]\nfrom typing import Generic, TypeVar, Self\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass B(Generic[T, S]):\n    def copy(self) -> Self: ...\n\nb: B[int, str]\nreveal_type(B.copy(b))  # N: Revealed type is \"__main__.B[builtins.int, builtins.str]\"\n\nclass C(B[T, S]): ...\n\nc: C[int, str]\nreveal_type(C.copy(c))  # N: Revealed type is \"__main__.C[builtins.int, builtins.str]\"\n\nB.copy(42)  # E: Value of type variable \"Self\" of \"copy\" of \"B\" cannot be \"int\"\nC.copy(42)  # E: Value of type variable \"Self\" of \"copy\" of \"B\" cannot be \"int\"\n[builtins fixtures/tuple.pyi]\n\n[case testRecursiveSelfTypeCallMethodNoCrash]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\nclass Partial:\n    def __call__(self: Callable[..., T]) -> T: ...\n\nclass Partial2:\n    def __call__(self: Callable[..., T], x: T) -> T: ...\n\np: Partial\nreveal_type(p())  # N: Revealed type is \"Never\"\np2: Partial2\nreveal_type(p2(42))  # N: Revealed type is \"builtins.int\"\n\n[case testAccessingSelfClassVarInClassMethod]\nfrom typing import Self, ClassVar, Type, TypeVar\n\nT = TypeVar(\"T\", bound=\"Foo\")\n\nclass Foo:\n    instance: ClassVar[Self]\n    @classmethod\n    def get_instance(cls) -> Self:\n        return reveal_type(cls.instance)  # N: Revealed type is \"Self`0\"\n    @classmethod\n    def get_instance_old(cls: Type[T]) -> T:\n        return reveal_type(cls.instance)  # N: Revealed type is \"T`-1\"\n\nclass Bar(Foo):\n    extra: int\n\n    @classmethod\n    def get_instance(cls) -> Self:\n        reveal_type(cls.instance.extra)  # N: Revealed type is \"builtins.int\"\n        return cls.instance\n\n    @classmethod\n    def other(cls) -> None:\n        reveal_type(cls.instance)  # N: Revealed type is \"Self`0\"\n        reveal_type(cls.instance.extra)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(Bar.instance)  # N: Revealed type is \"__main__.Bar\"\n[builtins fixtures/classmethod.pyi]\n\n[case testAccessingSelfClassVarInClassMethodTuple]\nfrom typing import Self, ClassVar, Tuple\n\nclass C(Tuple[int, str]):\n    x: Self\n    y: ClassVar[Self]\n\n    @classmethod\n    def bar(cls) -> None:\n        reveal_type(cls.y)  # N: Revealed type is \"Self`0\"\n    @classmethod\n    def bar_self(self) -> Self:\n        return reveal_type(self.y)  # N: Revealed type is \"Self`0\"\n\nc: C\nreveal_type(c.x)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.C]\"\nreveal_type(c.y)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.C]\"\nreveal_type(C.y)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.C]\"\nC.x  # E: Access to generic instance variables via class is ambiguous\n[builtins fixtures/classmethod.pyi]\n\n[case testAccessingTypingSelfUnion]\nfrom typing import Self, Union\n\nclass C:\n    x: Self\nclass D:\n    x: int\nx: Union[C, D]\nreveal_type(x.x)  # N: Revealed type is \"Union[__main__.C, builtins.int]\"\n\n[case testCallableProtocolTypingSelf]\nfrom typing import Protocol, Self\n\nclass MyProtocol(Protocol):\n    __name__: str\n\n    def __call__(\n        self: Self,\n    ) -> None: ...\n\ndef test() -> None: ...\nvalue: MyProtocol = test\n\n[case testCallableProtocolOldSelf]\nfrom typing import Protocol, TypeVar\n\nSelf = TypeVar(\"Self\", bound=\"MyProtocol\")\n\nclass MyProtocol(Protocol):\n    __name__: str\n\n    def __call__(\n        self: Self,\n    ) -> None: ...\n\ndef test() -> None: ...\nvalue: MyProtocol = test\n\n[case testSelfTypeUnionIter]\nfrom typing import Self, Iterator, Generic, TypeVar, Union\n\nT = TypeVar(\"T\")\n\nclass range(Generic[T]):\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> T: ...\n\nclass count:\n    def __iter__(self) -> Iterator[int]: ...\n\ndef foo(x: Union[range[int], count]) -> None:\n    for item in x:\n        reveal_type(item)  # N: Revealed type is \"builtins.int\"\n\n[case testGenericDescriptorWithSelfTypeAnnotationsAndOverloads]\nfrom __future__ import annotations\nfrom typing import Any, overload, Callable, TypeVar, Generic, ParamSpec\nfrom typing_extensions import Concatenate\n\nC = TypeVar(\"C\", bound=Callable[..., Any])\nS = TypeVar(\"S\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nclass Descriptor(Generic[C]):\n    def __init__(self, impl: C) -> None: ...\n\n    @overload\n    def __get__(\n        self: Descriptor[C], instance: None, owner: type | None\n    ) -> Descriptor[C]: ...\n\n    @overload\n    def __get__(\n        self: Descriptor[Callable[Concatenate[S, P], R]], instance: S, owner: type | None,\n    ) -> Callable[P, R]: ...\n\n    def __get__(self, *args, **kwargs): ...\n\nclass Test:\n    @Descriptor\n    def method(self, foo: int, bar: str) -> bytes: ...\n\nreveal_type(Test().method) # N: Revealed type is \"def (foo: builtins.int, bar: builtins.str) -> builtins.bytes\"\n\nclass Test2:\n    @Descriptor\n    def method(self, foo: int, *, bar: str) -> bytes: ...\n\nreveal_type(Test2().method) # N: Revealed type is \"def (foo: builtins.int, *, bar: builtins.str) -> builtins.bytes\"\n[builtins fixtures/tuple.pyi]\n\n[case testSelfInMultipleInheritance]\nfrom typing_extensions import Self\n\nclass A:\n    foo: int\n    def method(self: Self, other: Self) -> None:\n        self.foo\n        other.foo\n\nclass B:\n    bar: str\n    def method(self: Self, other: Self) -> None:\n        self.bar\n        other.bar\n\nclass C(A, B):  # OK: both methods take Self\n    pass\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-semanal-error.test",
    "content": "-- Type checking after an error during semantic analysis\n-- -----------------------------------------------------\n--\n-- This tests both the semantic analyzer (that it does not generate\n-- corrupt state on error) and the type checker (that it can deal with\n-- whatever state the semantic analyzer sets up).\n\n-- TODO:\n--  - invalid type in annotation\n--  - invalid function comment type annotation\n--  - invalid multiple assignment type annotation\n--  - using a type variable as a value\n--  - using special names defined in typing as values\n\n[case testMissingModuleImport1]\nimport m # E\nm.foo()\nm.x = m.y\n1() # E\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"m\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:4: error: \"int\" not callable\n\n[case testMissingModuleImport2]\nfrom m import x # E\nx.foo()\nx.a = x.b\n1() # E\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"m\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:4: error: \"int\" not callable\n\n[case testMissingModuleImport3]\nfrom m import * # E\nx # E\n1() # E\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"m\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Name \"x\" is not defined\nmain:3: error: \"int\" not callable\n\n[case testInvalidBaseClass1]\nclass A(X): # E: Name \"X\" is not defined\n    x = 1\nA().foo(1)\nA().x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testInvalidBaseClass2]\n\nX = 1\nclass A(X): # E\n    x = 1\nA().foo(1)\nA().x = '' # E\n[out]\nmain:3: error: Variable \"__main__.X\" is not valid as a type\nmain:3: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\nmain:3: error: Invalid base class \"X\"\nmain:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n\n[case testInvalidNumberOfTypeArgs]\nfrom typing import TypeVar\nT = TypeVar('T')\nclass C:  # Forgot to add type params here\n    def __init__(self, t: T) -> None: pass\nc = C(t=3)  # type: C[int]  # E: \"C\" expects no type arguments, but 1 given\n\n[case testBreakOutsideLoop]\nbreak # E: \"break\" outside loop\n\n[case testContinueOutsideLoop]\ncontinue # E: \"continue\" outside loop\n\n[case testYieldOutsideFunction]\nyield # E: \"yield\" outside function\nx = 1\nyield from x # E: \"yield from\" outside function\n[(yield 1) for _ in x] # E: \"yield\" inside comprehension or generator expression\n{(yield 1) for _ in x} # E: \"yield\" inside comprehension or generator expression\n{i: (yield 1) for i in x} # E: \"yield\" inside comprehension or generator expression\n((yield 1) for _ in x) # E: \"yield\" inside comprehension or generator expression\ny = 1\n[(yield from x) for _ in y] # E: \"yield from\" inside comprehension or generator expression\n{(yield from x) for _ in y} # E: \"yield from\" inside comprehension or generator expression\n{i: (yield from x) for i in y} # E: \"yield from\" inside comprehension or generator expression\n((yield from x) for _ in y) # E: \"yield from\" inside comprehension or generator expression\ndef f(y):\n    [x for x in (yield y)]\n    {x for x in (yield y)}\n    {x: x for x in (yield y)}\n    (x for x in (yield y))\n    [x for x in (yield from y)]\n    {x for x in (yield from y)}\n    {x: x for x in (yield from y)}\n    (x for x in (yield from y))\ndef g(y):\n    [(yield 1) for _ in y] # E: \"yield\" inside comprehension or generator expression\n    {(yield 1) for _ in y} # E: \"yield\" inside comprehension or generator expression\n    {i: (yield 1) for i in y} # E: \"yield\" inside comprehension or generator expression\n    ((yield 1) for _ in y) # E: \"yield\" inside comprehension or generator expression\n    lst = 1\n    [(yield from lst) for _ in y] # E: \"yield from\" inside comprehension or generator expression\n    {(yield from lst) for _ in y} # E: \"yield from\" inside comprehension or generator expression\n    {i: (yield from lst) for i in y} # E: \"yield from\" inside comprehension or generator expression\n    ((yield from lst) for _ in y) # E: \"yield from\" inside comprehension or generator expression\ndef h(y):\n    lst = 1\n    [x for x in lst if (yield y)] # E: \"yield\" inside comprehension or generator expression\n    {x for x in lst if (yield y)} # E: \"yield\" inside comprehension or generator expression\n    {x: x for x in lst if (yield y)} # E: \"yield\" inside comprehension or generator expression\n    (x for x in lst if (yield y)) # E: \"yield\" inside comprehension or generator expression\n    lst = 1\n    [x for x in lst if (yield from y)] # E: \"yield from\" inside comprehension or generator expression\n    {x for x in lst if (yield from y)} # E: \"yield from\" inside comprehension or generator expression\n    {x: x for x in lst if (yield from y)} # E: \"yield from\" inside comprehension or generator expression\n    (x for x in lst if (yield from y)) # E: \"yield from\" inside comprehension or generator expression\n\n[case testImportFuncDup]\n\nimport m\ndef m() -> None: ...  # E: Name \"m\" already defined (by an import)\n\n[file m.py]\n[out]\n\n[case testIgnoredImportDup]\n\nimport m # type: ignore\nfrom m import f # type: ignore\ndef m() -> None: ...  # E: Name \"m\" already defined (possibly by an import)\ndef f() -> None: ...  # E: Name \"f\" already defined (possibly by an import)\n\n[out]\n\n[case testRuntimeProtoTwoBases]\nfrom typing_extensions import Protocol, runtime_checkable\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\n@runtime_checkable\nclass P(Protocol, Generic[T]):\n    attr: T\n\nclass C:\n    attr: int\n\nx: P[int] = C()\n[builtins fixtures/tuple.pyi]\n\n[case testSemanalDoesNotLeakSyntheticTypes]\n# flags: --cache-fine-grained\nfrom typing import Generic, NamedTuple, TypedDict, TypeVar\nfrom dataclasses import dataclass\n\nT = TypeVar('T')\nclass Wrap(Generic[T]): pass\n\ninvalid_1: 1 + 2        # E: Invalid type comment or annotation\ninvalid_2: Wrap[1 + 2]  # E: Invalid type comment or annotation\n\nclass A:\n    invalid_1: 1 + 2        # E: Invalid type comment or annotation\n    invalid_2: Wrap[1 + 2]  # E: Invalid type comment or annotation\n\nclass B(NamedTuple):\n    invalid_1: 1 + 2        # E: Invalid type comment or annotation\n    invalid_2: Wrap[1 + 2]  # E: Invalid type comment or annotation\n\nclass C(TypedDict):\n    invalid_1: 1 + 2        # E: Invalid type comment or annotation\n    invalid_2: Wrap[1 + 2]  # E: Invalid type comment or annotation\n\n@dataclass\nclass D:\n    invalid_1: 1 + 2        # E: Invalid type comment or annotation\n    invalid_2: Wrap[1 + 2]  # E: Invalid type comment or annotation\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n"
  },
  {
    "path": "test-data/unit/check-serialize.test",
    "content": "-- Serialization test cases (incremental type checking)\n--\n-- These test that modules deserialized from cache files behave\n-- identically to modules that have undergone full type checking.\n--\n-- These tests are written using the same syntax as test cases in\n-- check-incremental.test.  Look at the comment at that the top of\n-- that file for the details of how these tests work.\n--\n-- There is probably some overlap with check-incremental.test, but it\n-- is perhaps not worth trying to simplify these, since a few redundant\n-- test cases are cheap but accidentally losing test coverage is bad.\n--\n-- These are intended to be straightforward, and do not test import\n-- cycles and other tricky business.  Add test cases for complex things\n-- to check-incremental.test.\n\n--\n-- Basic things\n--\n\n[case testSerializeModuleAttribute]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\ny = b.x  # type: int\n[file b.py]\nx = ''\n-- We only do the following two sections once here to avoid repetition.\n-- Most other test cases are similar.\n[rechecked a]\n[stale]\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n--\n-- Functions\n--\n\n[case testSerializeAnnotatedFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.f(1)\nx = b.f('')  # type: str\n[file b.py]\ndef f(x: str) -> int: pass\n[out2]\ntmp/a.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\ntmp/a.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testSerializeUnannotatedFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.f(x=1)\nb.f()\n[file b.py]\ndef f(x): pass\n[out2]\ntmp/a.py:3: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testSerializeGenericFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import f\nreveal_type(f(1))\nreveal_type(f(x=''))\n[file b.py]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef f(x: T) -> T: return x\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.int\"\ntmp/a.py:3: note: Revealed type is \"builtins.str\"\n\n[case testSerializeFunctionReturningGenericFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.f)\nreveal_type(b.f()(''))\n[file b.py]\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\n\ndef f() -> Callable[[T], T]: pass\n[out2]\ntmp/a.py:2: note: Revealed type is \"def () -> def [T] (T`-1) -> T`-1\"\ntmp/a.py:3: note: Revealed type is \"builtins.str\"\n\n[case testSerializeArgumentKinds]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import f\nf(1, z=1)\nf(1, '', z=1)\nf(1, y='', z=1)\nf(1, '', 2, 3, z=1)\nf(1, '', zz=1, z=1)\nf(1, '', foo='', z=1)\n[file b.py]\ndef f(x: int,\n      y: str = '',\n      *args: int,\n      z: int,\n      zz: int = 1,\n      **kw: str) -> None: pass\n[builtins fixtures/dict.pyi]\n[out2]\n\n[case testSerializeCallableWithBoundTypeArguments]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nx = b.f\n[file b.py]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def f(self, x: T) -> None: pass\n\nc: C[int]\nf = c.f\n[out]\n[out2]\n\n[case testSerializePositionalOnlyArgument]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.f(1)\nb.f('')\nb.f(__x=1)\n[file b.py]\ndef f(__x: int) -> None: pass\n[out2]\ntmp/a.py:3: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:4: error: Unexpected keyword argument \"__x\" for \"f\"\n\n[case testSerializeArgumentKindsErrors]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import f\nf('', z=1)           # Line 2\nf(1, 2, z=1)         # 3\nf(1, y=1, z=1)       # 4\nf(1, '', 2, '', z=1) # 5\nf(1, '', z='')       # 6\nf(1, '', zz='', z=1) # 7\nf(1, '', z=1, foo=1) # 8\n[file b.py]\ndef f(x: int,\n      y: str = '',\n      *args: int,\n      z: int,\n      zz: int = 1,\n      **kw: str) -> None: pass\n[builtins fixtures/dict.pyi]\n[out2]\ntmp/a.py:2: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:3: error: Argument 2 to \"f\" has incompatible type \"int\"; expected \"str\"\ntmp/a.py:4: error: Argument \"y\" to \"f\" has incompatible type \"int\"; expected \"str\"\ntmp/a.py:5: error: Argument 4 to \"f\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:6: error: Argument \"z\" to \"f\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:7: error: Argument \"zz\" to \"f\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:8: error: Argument \"foo\" to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testSerializeOverloadedFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.f(1))\nreveal_type(b.f(''))\n[file b.pyi]\nfrom typing import overload\n@overload\ndef f(x: int) -> int: pass\n@overload\ndef f(x: str) -> str: pass\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.int\"\ntmp/a.py:3: note: Revealed type is \"builtins.str\"\n\n[case testSerializeDecoratedFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.f(''))\nb.f(x=1)\n[file b.py]\nfrom typing import Callable\ndef dec(f: Callable[[int], int]) -> Callable[[str], str]: pass\n@dec\ndef f(x: int) -> int: pass\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.str\"\ntmp/a.py:3: error: Unexpected keyword argument \"x\" for \"f\"\n\n[case testSerializeTypeGuardFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.guard(''))\nreveal_type(b.guard)\n[file b.py]\nfrom typing_extensions import TypeGuard\ndef guard(a: object) -> TypeGuard[str]: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.bool\"\ntmp/a.py:3: note: Revealed type is \"def (a: builtins.object) -> TypeGuard[builtins.str]\"\n--\n-- Classes\n--\n\n[case testSerializeClassAttribute]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.A().x = ''\n[file b.py]\nclass A:\n    x = 1\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testSerializeMethod]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.A().f('')\n[file b.py]\nclass A:\n    def f(self, x: int) -> None: pass\n[out2]\ntmp/a.py:2: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testSerialize__init__]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA('')\nclass B(A):\n    def f(self) -> None:\n        super().__init__('')\n[file b.py]\nclass A:\n    def __init__(self, x: int) -> None: pass\n[out2]\ntmp/a.py:2: error: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:5: error: Argument 1 to \"__init__\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testSerializeOverloaded__init__]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA(object()) # E\nA(x='')\nA(0)\nclass B(A):\n    def f(self) -> None:\n        super().__init__(object()) # E\n        super().__init__('')\n        super().__init__(0)\n[file b.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __init__(self, x: int) -> None: pass\n    @overload\n    def __init__(self, x: str) -> None: pass\n[out2]\ntmp/a.py:2: error: No overload variant of \"A\" matches argument type \"object\"\ntmp/a.py:2: note: Possible overload variants:\ntmp/a.py:2: note:     def A(self, x: int) -> A\ntmp/a.py:2: note:     def A(self, x: str) -> A\ntmp/a.py:7: error: No overload variant of \"__init__\" of \"A\" matches argument type \"object\"\ntmp/a.py:7: note: Possible overload variants:\ntmp/a.py:7: note:     def __init__(self, x: int) -> None\ntmp/a.py:7: note:     def __init__(self, x: str) -> None\n\n[case testSerialize__new__]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA('')\n[file b.py]\nclass A:\n    def __new__(cls, x: int) -> 'A': pass\n[out2]\ntmp/a.py:2: error: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testSerializeClassVar]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA.x = ''\nA().x = 1\n[file b.py]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/a.py:3: error: Cannot assign to class variable \"x\" via instance\n\n[case testSerializeGenericClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\na1: A[int, str] = A(1)\na2: A[int, str] = A('')\nreveal_type(a1.y)\nreveal_type(a1.f())\n[file b.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T, S]):\n    x: T\n    y: S\n    def __init__(self, x: T) -> None:\n        self.x = x\n    def f(self) -> T:\n        return self.x\n[out2]\ntmp/a.py:3: error: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:4: note: Revealed type is \"builtins.str\"\ntmp/a.py:5: note: Revealed type is \"builtins.int\"\n\n[case testSerializeAbstractClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA()\nclass B(A):\n    def f(self) -> None: pass\n    x: int\nB()\na: A\na.f()\na.x = 1\n[file b.py]\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n    @abstractproperty\n    def x(self) -> int: return 0\n[typing fixtures/typing-medium.pyi]\n[out2]\ntmp/a.py:2: error: Cannot instantiate abstract class \"A\" with abstract attributes \"f\" and \"x\"\ntmp/a.py:9: error: Property \"x\" defined in \"A\" is read-only\n\n[case testSerializeStaticMethod]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA.f(1)\nA.f()\nA().f()\n[file b.py]\nclass A:\n    @staticmethod\n    def f() -> None: pass\n[builtins fixtures/staticmethod.pyi]\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\" of \"A\"\n\n[case testSerializeClassMethod]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nA.f(1)\nA.f()\nA().f()\n[file b.py]\nclass A:\n    @classmethod\n    def f(cls) -> None: pass\n[builtins fixtures/classmethod.pyi]\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\" of \"A\"\n\n[case testSerializeReadOnlyProperty]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nreveal_type(A().x)\nA().x = 0\n[file b.py]\nclass A:\n    @property\n    def x(self) -> int: return 0\n[builtins fixtures/property.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.int\"\ntmp/a.py:3: error: Property \"x\" defined in \"A\" is read-only\n\n[case testSerializeReadWriteProperty]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nreveal_type(A().x)\nA().x = ''\nA().x = 0\n[file b.py]\nclass A:\n    @property\n    def x(self) -> int: return 0\n    @x.setter\n    def x(self, v: int) -> None: pass\n[builtins fixtures/property.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.int\"\ntmp/a.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testSerializeSelfType]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\nreveal_type(A().f())\nclass B(A): pass\nreveal_type(B().f())\n[file b.py]\nfrom typing import TypeVar\nT = TypeVar('T', bound='A')\nclass A:\n    def f(self: T) -> T: return self\n[out2]\ntmp/a.py:2: note: Revealed type is \"b.A\"\ntmp/a.py:4: note: Revealed type is \"a.B\"\n\n[case testSerializeInheritance]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A, B, C\nC().f(1) # E\nC().g(1) # E\nreveal_type(C().h())\na: A = C()\nb: B = C()\ni: int = C() # E\n[file b.py]\nclass A:\n    def f(self) -> int: pass\nclass B:\n    def g(self) -> str: pass\n    def h(self) -> object: pass\nclass C(A, B):\n    def h(self) -> int: pass\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\" of \"A\"\ntmp/a.py:3: error: Too many arguments for \"g\" of \"B\"\ntmp/a.py:4: note: Revealed type is \"builtins.int\"\ntmp/a.py:7: error: Incompatible types in assignment (expression has type \"C\", variable has type \"int\")\n\n[case testSerializeGenericInheritance]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import B\nb: B[int]\nreveal_type(b.f())\n[file b.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def f(self) -> T: pass\nclass B(A[A[T]]):\n    pass\n[out2]\ntmp/a.py:3: note: Revealed type is \"b.A[builtins.int]\"\n\n[case testSerializeFixedLengthTupleBaseClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\na: A\na.f(1)\nreveal_type((a[0], a[1]))\n[file b.py]\nfrom typing import Tuple\nclass A(Tuple[int, str]):\n    def f(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:3: error: Too many arguments for \"f\" of \"A\"\ntmp/a.py:4: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\n[case testSerializeVariableLengthTupleBaseClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\na: A\na.f(1)\nreveal_type((a[0], a[1]))\n[file b.py]\nfrom typing import Tuple\nclass A(Tuple[int, ...]):\n    def f(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:3: error: Too many arguments for \"f\" of \"A\"\ntmp/a.py:4: note: Revealed type is \"Tuple[builtins.int, builtins.int]\"\n\n[case testSerializePlainTupleBaseClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\na: A\na.f(1)\nreveal_type((a[0], a[1]))\n[file b.py]\nfrom typing import Tuple\nclass A(tuple):\n    def f(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:3: error: Too many arguments for \"f\" of \"A\"\ntmp/a.py:4: note: Revealed type is \"Tuple[Any, Any]\"\n\n[case testSerializeNamedTupleBaseClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\na: A\na.f(1)\nreveal_type((a[0], a[1]))\nreveal_type((a.x, a.y))\n[file b.py]\nfrom typing import NamedTuple\nclass A(NamedTuple('N', [('x', int), ('y', str)])):\n    def f(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:3: error: Too many arguments for \"f\" of \"A\"\ntmp/a.py:4: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\ntmp/a.py:5: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\n[case testSerializeAnyBaseClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import B\nB().f(1)\nreveal_type(B().xyz)\n[file b.py]\nfrom typing import Any\nA: Any\nclass B(A):\n    def f(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\" of \"B\"\ntmp/a.py:3: note: Revealed type is \"Any\"\n\n[case testSerializeIndirectAnyBaseClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import C\nC().f(1)\nC().g(1)\nreveal_type(C().xyz)\n[file b.py]\nfrom typing import Any\nA: Any\nclass B(A):\n    def f(self) -> None: pass\nclass C(B):\n    def g(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\" of \"B\"\ntmp/a.py:3: error: Too many arguments for \"g\" of \"C\"\ntmp/a.py:4: note: Revealed type is \"Any\"\n\n[case testSerializeNestedClass]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.A.B().f(1)\nb.A.B.C().g(1)\nb.b.f(1)\nb.c.g(1)\n[file b.py]\nclass A:\n    class B:\n        def f(self) -> None: pass\n        class C:\n            def g(self) -> None: pass\nb: A.B\nc: A.B.C\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\" of \"B\"\ntmp/a.py:3: error: Too many arguments for \"g\" of \"C\"\ntmp/a.py:4: error: Too many arguments for \"f\" of \"B\"\ntmp/a.py:5: error: Too many arguments for \"g\" of \"C\"\n\n[case testSerializeCallableVsTypeObjectDistinction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nt: type\nt = b.A\nif int():\n    t = b.f # E\n[file b.py]\nclass A: pass\ndef f() -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:5: error: Incompatible types in assignment (expression has type \"Callable[[], None]\", variable has type \"type\")\n\n[case testSerializeOverloadedVsTypeObjectDistinction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nt: type\nt = b.A\nif int():\n    t = b.f # E\n[file b.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: int) -> None: pass\n@overload\ndef f() -> None: pass\n@overload\ndef f(x: int) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:5: error: Incompatible types in assignment (expression has type overloaded function, variable has type \"type\")\n\n[case testSerializeNamedTupleInMethod4]\nfrom ntcrash import C\nreveal_type(C().a)\nreveal_type(C().b)\nreveal_type(C().c)\n[file ntcrash.py]\nfrom typing import NamedTuple\nclass C:\n    def __init__(self) -> None:\n        A = NamedTuple('A', [('x', int)])\n        self.a = A(0)\n        self.b = A(0)  # type: A\n        self.c = A\n[builtins fixtures/tuple.pyi]\n[out1]\nmain:2: note: Revealed type is \"Tuple[builtins.int, fallback=ntcrash.C.A@4]\"\nmain:3: note: Revealed type is \"Tuple[builtins.int, fallback=ntcrash.C.A@4]\"\nmain:4: note: Revealed type is \"def (x: builtins.int) -> Tuple[builtins.int, fallback=ntcrash.C.A@4]\"\n[out2]\nmain:2: note: Revealed type is \"Tuple[builtins.int, fallback=ntcrash.C.A@4]\"\nmain:3: note: Revealed type is \"Tuple[builtins.int, fallback=ntcrash.C.A@4]\"\nmain:4: note: Revealed type is \"def (x: builtins.int) -> Tuple[builtins.int, fallback=ntcrash.C.A@4]\"\n\n--\n-- Strict optional\n--\n\n[case testSerializeOptionalType]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.x)\nb.f(b.x)\n[file b.py]\nfrom typing import Optional\nx: Optional[int]\ndef f(x: int) -> None: pass\n[out2]\ntmp/a.py:2: note: Revealed type is \"Union[builtins.int, None]\"\ntmp/a.py:3: error: Argument 1 to \"f\" has incompatible type \"Optional[int]\"; expected \"int\"\n\n--\n-- # type: ignore\n--\n\n[case testSerializeIgnoredUndefinedType]\nimport b\nreveal_type(b.x)\n[file b.py]\nx: NonExistent  # type: ignore\n[out1]\nmain:2: note: Revealed type is \"Any\"\n[out2]\nmain:2: note: Revealed type is \"Any\"\n\n[case testSerializeIgnoredInvalidType]\nimport b\nreveal_type(b.x)\n[file b.py]\nA = 0\nx: A  # type: ignore\n[out1]\nmain:2: note: Revealed type is \"A?\"\n[out2]\nmain:2: note: Revealed type is \"A?\"\n\n[case testSerializeIgnoredMissingBaseClass]\nimport b\nreveal_type(b.B())\nreveal_type(b.B().x)\n[file b.py]\nclass B(A): pass  # type: ignore\n[out1]\nmain:2: note: Revealed type is \"b.B\"\nmain:3: note: Revealed type is \"Any\"\n[out2]\nmain:2: note: Revealed type is \"b.B\"\nmain:3: note: Revealed type is \"Any\"\n\n[case testSerializeIgnoredInvalidBaseClass]\nimport b\nreveal_type(b.B())\nreveal_type(b.B().x)\n[file b.py]\nA = 0\nclass B(A): pass  # type: ignore\n[out1]\nmain:2: note: Revealed type is \"b.B\"\nmain:3: note: Revealed type is \"Any\"\n[out2]\nmain:2: note: Revealed type is \"b.B\"\nmain:3: note: Revealed type is \"Any\"\n\n[case testSerializeIgnoredImport]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.m)\nreveal_type(b.x)\n[file b.py]\nimport m  # type: ignore\nfrom m import x  # type: ignore\n[out2]\ntmp/a.py:2: note: Revealed type is \"Any\"\ntmp/a.py:3: note: Revealed type is \"Any\"\n\n--\n-- TypeVar\n--\n\n[case testSerializeSimpleTypeVar]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\ndef f(x: b.T) -> b.T: return x\nreveal_type(f)\n[file b.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[out2]\ntmp/a.py:3: note: Revealed type is \"def [b.T] (x: b.T`-1) -> b.T`-1\"\n\n[case testSerializeBoundedTypeVar]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\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', bound=int)\ndef g(x: T) -> T: return x\n[out2]\ntmp/a.py:3: note: Revealed type is \"def [b.T <: builtins.int] (x: b.T`-1) -> b.T`-1\"\ntmp/a.py:4: note: Revealed type is \"def [T <: builtins.int] (x: T`-1) -> T`-1\"\n\n[case testSerializeTypeVarWithValues]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\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', int, str)\ndef g(x: T) -> T: return x\n[out2]\ntmp/a.py:3: note: Revealed type is \"def [b.T in (builtins.int, builtins.str)] (x: b.T`-1) -> b.T`-1\"\ntmp/a.py:4: note: Revealed type is \"def [T in (builtins.int, builtins.str)] (x: T`-1) -> T`-1\"\n\n[case testSerializeTypeVarInClassBody]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import A\ndef f(x: A.T) -> A.T: return x\nreveal_type(f)\n[file b.py]\nfrom typing import TypeVar\nclass A:\n    T = TypeVar('T', int, str)\n[out2]\ntmp/a.py:3: note: Revealed type is \"def [A.T in (builtins.int, builtins.str)] (x: A.T`-1) -> A.T`-1\"\n\n--\n-- NewType\n--\n\n[case testSerializeNewType]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\ny: b.N\ny = 1\ni = y\nb.x = 1\nb.x = y\ny = b.N(1)\ny = b.N('')\n[file b.py]\nfrom typing import NewType\nN = NewType('N', int)\nx: N\n[out2]\ntmp/a.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"N\")\ntmp/a.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"N\")\ntmp/a.py:8: error: Argument 1 to \"N\" has incompatible type \"str\"; expected \"int\"\n\n--\n-- Named tuples\n--\n\n[case testSerializeNamedTuple]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nfrom typing import Tuple\ny: b.N\nt: Tuple[int]\ny = t\nb.x = t\nt = y\nb.x = t\nreveal_type(b.N(x=1))\nreveal_type(y[0])\nb.N(x='')\n[file b.py]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int)])\nx: N\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:5: error: Incompatible types in assignment (expression has type \"Tuple[int]\", variable has type \"N\")\ntmp/a.py:6: error: Incompatible types in assignment (expression has type \"Tuple[int]\", variable has type \"N\")\ntmp/a.py:9: note: Revealed type is \"Tuple[builtins.int, fallback=b.N]\"\ntmp/a.py:10: note: Revealed type is \"builtins.int\"\ntmp/a.py:11: error: Argument \"x\" to \"N\" has incompatible type \"str\"; expected \"int\"\n\n--\n-- Types and type aliases\n--\n\n[case testSerializeTypeAliases]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nd: b.D\na: b.A\nu: b.U\nl: b.L\nt: b.T\nc: b.C\nty: b.Ty\nreveal_type(d)\nreveal_type(a)\nreveal_type(u)\nreveal_type(l)\nreveal_type(t)\nreveal_type(c)\nreveal_type(ty)\nc2: b.C2\nreveal_type(c2)\nty2: b.Ty2\nreveal_type(ty2)\n[file b.py]\nfrom typing import Any, Union, List, Tuple, Callable, Type\nclass DD: pass\nD = DD\nA = Any\nU = Union[int, str]\nL = List[int]\nT = Tuple[int, str]\nC = Callable[[int], str]\nC2 = Callable[..., str]\nTy = Type[int]\nTy2 = type\n[builtins fixtures/list.pyi]\n[out2]\ntmp/a.py:9: note: Revealed type is \"b.DD\"\ntmp/a.py:10: note: Revealed type is \"Any\"\ntmp/a.py:11: note: Revealed type is \"Union[builtins.int, builtins.str]\"\ntmp/a.py:12: note: Revealed type is \"builtins.list[builtins.int]\"\ntmp/a.py:13: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\ntmp/a.py:14: note: Revealed type is \"def (builtins.int) -> builtins.str\"\ntmp/a.py:15: note: Revealed type is \"Type[builtins.int]\"\ntmp/a.py:17: note: Revealed type is \"def (*Any, **Any) -> builtins.str\"\ntmp/a.py:19: note: Revealed type is \"builtins.type\"\n\n[case testSerializeGenericTypeAlias]\nimport b\nfrom b import X  # Work around https://github.com/python/mypy/issues/2887\nt: b.Y[int]\nreveal_type(t)\n[file b.py]\nfrom typing import TypeVar, Tuple\nX = TypeVar('X')\nY = Tuple[X, str]\n[builtins fixtures/tuple.pyi]\n[out1]\nmain:4: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n[out2]\nmain:4: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\n[case testSerializeTuple]\n# Don't repreat types tested by testSerializeTypeAliases here.\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.x)\nreveal_type(b.y)\n[file b.py]\nfrom typing import Tuple\nx: Tuple[int, ...]\ny: tuple\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.tuple[builtins.int, ...]\"\ntmp/a.py:3: note: Revealed type is \"builtins.tuple[Any, ...]\"\n\n[case testSerializeNone]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.x)\n[file b.py]\nx: None\n[out2]\ntmp/a.py:2: note: Revealed type is \"None\"\n\n--\n-- TypedDict\n--\n\n[case testSerializeTypedDictInMethod]\nfrom ntcrash import C\nreveal_type(C().a)\nreveal_type(C().b)\nreveal_type(C().c)\n[file ntcrash.py]\nfrom mypy_extensions import TypedDict\nclass C:\n    def __init__(self) -> None:\n        A = TypedDict('A', {'x': int})\n        self.a = A(x=0)\n        self.b = A(x=0)  # type: A\n        self.c = A\n[builtins fixtures/dict.pyi]\n[out1]\nmain:2: note: Revealed type is \"TypedDict('ntcrash.C.A@4', {'x': builtins.int})\"\nmain:3: note: Revealed type is \"TypedDict('ntcrash.C.A@4', {'x': builtins.int})\"\nmain:4: note: Revealed type is \"def (*, x: builtins.int) -> TypedDict('ntcrash.C.A@4', {'x': builtins.int})\"\n[out2]\nmain:2: note: Revealed type is \"TypedDict('ntcrash.C.A@4', {'x': builtins.int})\"\nmain:3: note: Revealed type is \"TypedDict('ntcrash.C.A@4', {'x': builtins.int})\"\nmain:4: note: Revealed type is \"def (*, x: builtins.int) -> TypedDict('ntcrash.C.A@4', {'x': builtins.int})\"\n\n[case testSerializeNonTotalTypedDict]\nfrom m import d\nreveal_type(d)\n[file m.py]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str}, total=False)\nd: D\n[builtins fixtures/dict.pyi]\n[out1]\nmain:2: note: Revealed type is \"TypedDict('m.D', {'x'?: builtins.int, 'y'?: builtins.str})\"\n[out2]\nmain:2: note: Revealed type is \"TypedDict('m.D', {'x'?: builtins.int, 'y'?: builtins.str})\"\n\n--\n-- Modules\n--\n\n[case testSerializeImport]\nimport b\nb.c.f()\nb.c.g()\n[file b.py]\nimport c\n[file c.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testSerializeImportAs]\nimport b\nb.d.f()\nb.d.g()\n[file b.py]\nimport c as d\n[file c.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testSerializeFromImportedClass]\nimport b\nb.A(1)\nreveal_type(b.A())\n[file b.py]\nfrom c import A\n[file c.py]\nclass A: pass\n[out1]\nmain:2: error: Too many arguments for \"A\"\nmain:3: note: Revealed type is \"c.A\"\n[out2]\nmain:2: error: Too many arguments for \"A\"\nmain:3: note: Revealed type is \"c.A\"\n\n[case testSerializeFromImportedClassAs]\nimport b\nb.B(1)\nreveal_type(b.B())\n[file b.py]\nfrom c import A as B\n[file c.py]\nclass A: pass\n[out1]\nmain:2: error: Too many arguments for \"A\"\nmain:3: note: Revealed type is \"c.A\"\n[out2]\nmain:2: error: Too many arguments for \"A\"\nmain:3: note: Revealed type is \"c.A\"\n\n[case testSerializeFromImportedModule]\nimport b\nb.d.f()\nb.d.g()\n[file b.py]\nfrom c import d\n[file c/__init__.py]\n[file c/d.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testSerializeQualifiedImport]\nimport b\nb.c.d.f()\nb.c.d.g()\n[file b.py]\nimport c.d\n[file c/__init__.py]\n[file c/d.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testSerializeQualifiedImportAs]\nimport b\nb.e.f()\nb.e.g()\n[file b.py]\nimport c.d as e\n[file c/__init__.py]\n[file c/d.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testSerialize__init__ModuleImport]\nimport b\nb.c.f()\nb.c.g()\na: b.c.d.A\nreveal_type(a)\n[file b.py]\nimport c\n[file c/__init__.py]\nimport d\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[file d.py]\nclass A: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\nmain:5: note: Revealed type is \"d.A\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\nmain:5: note: Revealed type is \"d.A\"\n\n[case testSerializeImportInClassBody]\nimport b\nb.A.c.f()\nb.A.c.g()\n[file b.py]\nclass A:\n    import c\n[file c.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[out1]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n[out2]\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testSerializeImportedTypeAlias]\nimport b\nx: b.B\nreveal_type(x)\n[file b.py]\nfrom c import B\n[file c.py]\nfrom typing import Any\nclass A: pass\nB = A\n[out1]\nmain:3: note: Revealed type is \"c.A\"\n[out2]\nmain:3: note: Revealed type is \"c.A\"\n\n[case testSerializeStarImport]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nb.f(1)\nx: b.A\nreveal_type(x)\n[file b.py]\nfrom c import *\n[file c.py]\ndef f() -> None: pass\nclass A: pass\n[out2]\ntmp/a.py:2: error: Too many arguments for \"f\"\ntmp/a.py:4: note: Revealed type is \"c.A\"\n\n[case testSerializeRelativeImport]\nimport b.c\nb.c.f(1)\n[file b/__init__.py]\n[file b/c.py]\nfrom .d import f\n[file b/d.py]\ndef f() -> None: pass\n[out1]\nmain:2: error: Too many arguments for \"f\"\n[out2]\nmain:2: error: Too many arguments for \"f\"\n\n[case testSerializeDummyType]\n# flags: --no-strict-optional\nimport a\n[file a.py]\nimport b\nreveal_type(b.Test(None).foo)\n[file a.py.2]\nimport b\nreveal_type(b.Test(b.Foo()).foo)\n[file b.py]\nclass Foo(object): pass\nclass Test:\n    def __init__(self, o: Foo) -> None:\n        self.foo = None\n        if callable(o):\n            self.foo = o\n[builtins fixtures/callable.pyi]\n[out1]\ntmp/a.py:2: note: Revealed type is \"b.<callable subtype of Foo>\"\n[out2]\ntmp/a.py:2: note: Revealed type is \"b.<callable subtype of Foo>\"\n\n[case testSerializeForwardReferenceToAliasInProperty]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.A().p)\n[file b.py]\n\nclass A:\n    @property\n    def p(self) -> C: pass\n    @p.setter\n    def p(self, c: C) -> None: pass\n    @p.deleter\n    def p(self) -> None: pass\n\nC = str\n[builtins fixtures/property.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.str\"\n\n[case testSerializeForwardReferenceToImportedAliasInProperty]\n\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\nreveal_type(b.A().p)\n[file b.py]\nclass A:\n    @property\n    def p(self) -> C: pass\n    @p.setter\n    def p(self, c: C) -> None: pass\n    @p.deleter\n    def p(self) -> None: pass\n\nfrom m import C\n[file m.py]\nC = str\n[builtins fixtures/property.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.str\"\n\n[case testSerializeNestedClassStuff]\n# flags: --verbose\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport b\n#\n[file b.py]\ndef foo() -> None:\n    class Foo:\n        class Bar: pass\n\n[case testSerializeGenericClassMethod]\nimport a\n[file a.py]\nimport b\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\nclass C:\n    @classmethod\n    def f(cls, x: T) -> T: ...\n\nx = C.f\n[file b.py]\nx = 1\n[file b.py.2]\nx = 'yes'\n[builtins fixtures/classmethod.pyi]\n\n[case testSerializeGenericAbstractMethod]\nimport a\n[file a.py]\nimport b\nfrom typing import TypeVar\nfrom abc import abstractmethod\n\nT = TypeVar('T')\n\nclass C:\n    @abstractmethod\n    def f(self, x: T) -> T: ...\n\nc: C\nx = c.f\n[file b.py]\nx = 1\n[file b.py.2]\nx = 'yes'\n\n[case testSerializeGenericNormalMethod]\nimport a\n[file a.py]\nimport b\nfrom typing import TypeVar\nfrom abc import abstractmethod\n\nT = TypeVar('T')\n\nclass C:\n    def f(self, x: T) -> T: ...\n\nc: C\nx = c.f\n[file b.py]\nx = 1\n[file b.py.2]\nx = 'yes'\n"
  },
  {
    "path": "test-data/unit/check-singledispatch.test",
    "content": "[case testIncorrectDispatchArgumentWhenDoesntMatchFallback]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef fun(arg: A) -> None:\n    pass\n@fun.register\ndef fun_b(arg: B) -> None:\n    pass\n\nfun(1) # E: Argument 1 to \"fun\" has incompatible type \"int\"; expected \"A\"\n\n# probably won't be required after singledispatch is special cased\n[builtins fixtures/args.pyi]\n\n[case testMultipleUnderscoreFunctionsIsntError]\nfrom functools import singledispatch\n\n@singledispatch\ndef fun(arg) -> None:\n    pass\n@fun.register\ndef _(arg: str) -> None:\n    pass\n@fun.register\ndef _(arg: int) -> None:\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testCheckNonDispatchArgumentsWithTypeAlwaysTheSame]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef f(arg: A, arg2: str) -> None:\n    pass\n\n@f.register\ndef g(arg: B, arg2: str) -> None:\n    pass\n\nf(A(), 'a')\nf(A(), 5) # E: Argument 2 to \"f\" has incompatible type \"int\"; expected \"str\"\n\nf(B(), 'a')\nf(B(), 1) # E: Argument 2 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[builtins fixtures/args.pyi]\n\n[case testImplementationHasSameDispatchTypeAsFallback-xfail]\nfrom functools import singledispatch\n\n# TODO: differentiate between fallback and other implementations in error message\n@singledispatch\ndef f(arg: int) -> None: # E: singledispatch implementation 1 will never be used: implementation 2's dispatch type is the same\n    pass\n\n@f.register\ndef g(arg: int) -> None:\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testRegisterHasDifferentTypeThanTypeSignature-xfail]\nfrom functools import singledispatch\n\n@singledispatch\ndef f(arg) -> None:\n    pass\n\n@f.register(str)\ndef g(arg: int) -> None: # E: Argument to register \"str\" is incompatible with type \"int\" in function signature\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testTypePassedAsArgumentToRegister]\nfrom functools import singledispatch\n\n@singledispatch\ndef f(arg: int) -> None:\n    pass\n@f.register(str)\ndef g(arg) -> None: # E: Dispatch type \"str\" must be subtype of fallback function first argument \"int\"\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testCustomClassPassedAsTypeToRegister]\nfrom functools import singledispatch\nclass A: pass\n\n@singledispatch\ndef f(arg: int) -> None:\n    pass\n@f.register(A)\ndef g(arg) -> None: # E: Dispatch type \"A\" must be subtype of fallback function first argument \"int\"\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testMultiplePossibleImplementationsForKnownType]\nfrom functools import singledispatch\nfrom typing import Union\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\n@singledispatch\ndef f(arg: Union[A, C]) -> None:\n    pass\n\n@f.register\ndef g(arg: B) -> None:\n    pass\n\n@f.register\ndef h(arg: C) -> None:\n    pass\n\nx: Union[B, C]\nf(x)\n\n[builtins fixtures/args.pyi]\n\n[case testOnePartOfUnionDoesNotHaveCorrespondingImplementation]\nfrom functools import singledispatch\nfrom typing import Union\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\n@singledispatch\ndef f(arg: Union[A, C]) -> None:\n    pass\n\n@f.register\ndef g(arg: B) -> None:\n    pass\n\n@f.register\ndef h(arg: C) -> None:\n    pass\n\nx: Union[B, C, int]\nf(x)  # E: Argument 1 to \"f\" has incompatible type \"Union[B, C, int]\"; expected \"Union[A, C]\"\n\n[builtins fixtures/args.pyi]\n\n[case testABCAllowedAsDispatchType]\nfrom functools import singledispatch\nfrom collections.abc import Mapping\n\n@singledispatch\ndef f(arg) -> None:\n    pass\n\n@f.register\ndef g(arg: Mapping) -> None:\n    pass\n[builtins fixtures/dict.pyi]\n\n[case testIncorrectArgumentsInSingledispatchFunctionDefinition]\nfrom functools import singledispatch\n\n@singledispatch\ndef f() -> None: # E: Singledispatch function requires at least one argument\n    pass\n\n@singledispatch\ndef g(**kwargs) -> None: # E: First argument to singledispatch function must be a positional argument\n    pass\n\n@singledispatch\ndef h(*, x) -> None: # E: First argument to singledispatch function must be a positional argument\n    pass\n\n@singledispatch\ndef i(*, x=1) -> None: # E: First argument to singledispatch function must be a positional argument\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testDispatchTypeIsNotASubtypeOfFallbackFirstArgument]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\n@singledispatch\ndef f(arg: A) -> None:\n    pass\n\n@f.register\ndef g(arg: B) -> None:\n    pass\n\n@f.register\ndef h(arg: C) -> None: # E: Dispatch type \"C\" must be subtype of fallback function first argument \"A\"\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testMultipleSingledispatchFunctionsIntermixed]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\n@singledispatch\ndef f(arg: A) -> None:\n    pass\n\n@singledispatch\ndef h(arg: C) -> None:\n    pass\n\n@f.register\ndef g(arg: B) -> None:\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testAnyInConstructorArgsWithClassPassedToRegister]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass Base: pass\nclass ConstExpr:\n    def __init__(self, **kwargs: Any) -> None: pass\n\n@singledispatch\ndef f(arg: Base) -> ConstExpr:\n    pass\n\n@f.register(ConstExpr)\ndef g(arg: ConstExpr) -> ConstExpr: # E: Dispatch type \"ConstExpr\" must be subtype of fallback function first argument \"Base\"\n    pass\n\n\n[builtins fixtures/args.pyi]\n\n[case testRegisteredImplementationUsedBeforeDefinition]\nfrom functools import singledispatch\nfrom typing import Union\n\nclass Node: pass\nclass MypyFile(Node): pass\nclass Missing: pass\n\n@singledispatch\ndef f(a: Union[Node, Missing]) -> None:\n    pass\n\n@f.register\ndef g(a: MypyFile) -> None:\n    x: Missing\n    f(x)\n\n@f.register\ndef h(a: Missing) -> None:\n    pass\n\n[builtins fixtures/args.pyi]\n\n[case testIncorrectArgumentTypeWhenCallingRegisteredImplDirectly]\nfrom functools import singledispatch\n\n@singledispatch\ndef f(arg, arg2: str) -> bool:\n    return False\n\n@f.register\ndef g(arg: int, arg2: str) -> bool:\n    pass\n\n@f.register(str)\ndef h(arg, arg2: str) -> bool:\n    pass\n\ng('a', 'a') # E: Argument 1 to \"g\" has incompatible type \"str\"; expected \"int\"\ng(1, 1) # E: Argument 2 to \"g\" has incompatible type \"int\"; expected \"str\"\n\n# don't show errors for incorrect first argument here, because there's no type annotation for the\n# first argument\nh(1, 'a')\nh('a', 1) # E: Argument 2 to \"h\" has incompatible type \"int\"; expected \"str\"\n\n[builtins fixtures/args.pyi]\n\n[case testDontCrashWhenRegisteringAfterError]\nimport functools\na = functools.singledispatch('a') # E: Need type annotation for \"a\" # E: Argument 1 to \"singledispatch\" has incompatible type \"str\"; expected \"Callable[..., Never]\"\n\n@a.register(int)\ndef default(val) -> int:\n    return 3\n\n[builtins fixtures/args.pyi]\n"
  },
  {
    "path": "test-data/unit/check-slots.test",
    "content": "[case testSlotsDefinitionWithStrAndListAndTuple]\nclass A:\n    __slots__ = \"a\"\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2  # E: Trying to assign name \"b\" that is not in \"__slots__\" of type \"__main__.A\"\n\nclass B:\n    __slots__ = (\"a\", \"b\")\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.c = 3  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.B\"\n\nclass C:\n    __slots__ = ['c']\n    def __init__(self) -> None:\n        self.a = 1  # E: Trying to assign name \"a\" that is not in \"__slots__\" of type \"__main__.C\"\n        self.c = 3\n\nclass WithVariable:\n    __fields__ = ['a', 'b']\n    __slots__ = __fields__\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.c = 3\n[builtins fixtures/list.pyi]\n\n\n[case testSlotsDefinitionWithDict]\nclass D:\n    __slots__ = {'key': 'docs'}\n    def __init__(self) -> None:\n        self.key = 1\n        self.missing = 2  # E: Trying to assign name \"missing\" that is not in \"__slots__\" of type \"__main__.D\"\n[builtins fixtures/dict.pyi]\n\n\n[case testSlotsDefinitionWithDynamicDict]\nslot_kwargs = {'b': 'docs'}\nclass WithDictKwargs:\n    __slots__ = {'a': 'docs', **slot_kwargs}\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.c = 3\n[builtins fixtures/dict.pyi]\n\n\n[case testSlotsDefinitionWithSet]\nclass E:\n    __slots__ = {'e'}\n    def __init__(self) -> None:\n        self.e = 1\n        self.missing = 2  # E: Trying to assign name \"missing\" that is not in \"__slots__\" of type \"__main__.E\"\n[builtins fixtures/set.pyi]\n\n\n[case testSlotsDefinitionOutsideOfClass]\n__slots__ = (\"a\", \"b\")\nclass A:\n    def __init__(self) -> None:\n        self.x = 1\n        self.y = 2\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsDefinitionWithClassVar]\nclass A:\n    __slots__ = ('a',)\n    b = 4\n\n    def __init__(self) -> None:\n        self.a = 1\n\n        # You cannot override class-level variables, but you can use them:\n        b = self.b\n        self.b = 2  # E: Trying to assign name \"b\" that is not in \"__slots__\" of type \"__main__.A\"\n\n        self.c = 3  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.A\"\n\nA.b = 1\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsDefinitionMultipleVars1]\nclass A:\n    __slots__ = __fields__ = (\"a\", \"b\")\n    def __init__(self) -> None:\n        self.x = 1\n        self.y = 2\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsDefinitionMultipleVars2]\nclass A:\n    __fields__ = __slots__ = (\"a\", \"b\")\n    def __init__(self) -> None:\n        self.x = 1\n        self.y = 2\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentEmptySlots]\nclass A:\n    __slots__ = ()\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n\na = A()\na.a = 1\na.b = 2\na.missing = 2\n[out]\nmain:4: error: Trying to assign name \"a\" that is not in \"__slots__\" of type \"__main__.A\"\nmain:5: error: Trying to assign name \"b\" that is not in \"__slots__\" of type \"__main__.A\"\nmain:8: error: Trying to assign name \"a\" that is not in \"__slots__\" of type \"__main__.A\"\nmain:9: error: Trying to assign name \"b\" that is not in \"__slots__\" of type \"__main__.A\"\nmain:10: error: \"A\" has no attribute \"missing\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithSuper]\nclass A:\n    __slots__ = (\"a\",)\nclass B(A):\n    __slots__ = (\"b\", \"c\")\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self._one = 1\n\nb = B()\nb.a = 1\nb.b = 2\nb.c = 3\nb._one = 1\nb._two = 2\n[out]\nmain:9: error: Trying to assign name \"_one\" that is not in \"__slots__\" of type \"__main__.B\"\nmain:14: error: \"B\" has no attribute \"c\"\nmain:15: error: Trying to assign name \"_one\" that is not in \"__slots__\" of type \"__main__.B\"\nmain:16: error: \"B\" has no attribute \"_two\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithSuperDuplicateSlots]\nclass A:\n    __slots__ = (\"a\",)\nclass B(A):\n    __slots__ = (\"a\", \"b\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self._one = 1  # E: Trying to assign name \"_one\" that is not in \"__slots__\" of type \"__main__.B\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithMixin]\nclass A:\n    __slots__ = (\"a\",)\nclass Mixin:\n    __slots__ = (\"m\",)\nclass B(A, Mixin):\n    __slots__ = (\"b\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.m = 2\n        self._one = 1\n\nb = B()\nb.a = 1\nb.m = 2\nb.b = 2\nb._two = 2\n[out]\nmain:11: error: Trying to assign name \"_one\" that is not in \"__slots__\" of type \"__main__.B\"\nmain:16: error: \"B\" has no attribute \"b\"\nmain:17: error: \"B\" has no attribute \"_two\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithSlottedSuperButNoChildSlots]\nclass A:\n    __slots__ = (\"a\",)\nclass B(A):\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 1\n\nb = B()\nb.a = 1\nb.b = 2\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithoutSuperSlots]\nclass A:\n    pass  # no slots\nclass B(A):\n    __slots__ = (\"a\", \"b\")\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n\nb = B()\nb.a = 1\nb.b = 2\nb.missing = 3\nb.extra = 4  # E: \"B\" has no attribute \"extra\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithoutSuperMixingSlots]\nclass A:\n    __slots__ = ()\nclass Mixin:\n    pass  # no slots\nclass B(A, Mixin):\n    __slots__ = (\"a\", \"b\")\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n\nb = B()\nb.a = 1\nb.b = 2\nb.missing = 3\nb.extra = 4  # E: \"B\" has no attribute \"extra\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithExplicitSetattr]\nclass A:\n    __slots__ = (\"a\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n\n    def __setattr__(self, k, v) -> None:\n        ...\n\na = A()\na.a = 1\na.b = 2\na.c = 3\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithParentSetattr]\nclass Parent:\n    __slots__ = ()\n\n    def __setattr__(self, k, v) -> None:\n        ...\n\nclass A(Parent):\n    __slots__ = (\"a\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n\na = A()\na.a = 1\na.b = 2\na.c = 3\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithProps]\nfrom typing import Any\n\ncustom_prop: Any\n\nclass A:\n    __slots__ = (\"a\",)\n\n    @property\n    def first(self) -> int:\n        ...\n\n    @first.setter\n    def first(self, arg: int) -> None:\n        ...\n\nclass B(A):\n    __slots__ = (\"b\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.c = 3\n\n    @property\n    def second(self) -> int:\n        ...\n\n    @second.setter\n    def second(self, arg: int) -> None:\n        ...\n\n    def get_third(self) -> int:\n        ...\n\n    def set_third(self, arg: int) -> None:\n        ...\n\n    third = custom_prop(get_third, set_third)\n\nb = B()\nb.a = 1\nb.b = 2\nb.c = 3\nb.first = 1\nb.second = 2\nb.third = 3\nb.extra = 'extra'\n[out]\nmain:22: error: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.B\"\nmain:43: error: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.B\"\nmain:47: error: \"B\" has no attribute \"extra\"\n[builtins fixtures/property.pyi]\n\n\n[case testSlotsAssignmentWithUnionProps]\nfrom typing import Any, Callable, Union\n\ncustom_obj: Any\n\nclass custom_property(object):\n    def __set__(self, *args, **kwargs):\n        ...\n\nclass A:\n    __slots__ = (\"a\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n\n    b: custom_property\n    c: Union[Any, custom_property]\n    d: Union[Callable, custom_property]\n    e: Callable\n\na = A()\na.a = 1\na.b = custom_obj\na.c = custom_obj\na.d = custom_obj\na.e = custom_obj\n[out]\n[builtins fixtures/dict.pyi]\n\n\n[case testSlotsAssignmentWithMethodReassign]\nclass A:\n    __slots__ = ()\n\n    def __init__(self) -> None:\n        self.method = lambda: None  # E: Cannot assign to a method\n\n    def method(self) -> None:\n        ...\n\na = A()\na.method = lambda: None  # E: Cannot assign to a method\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithExplicitDict]\nclass A:\n    __slots__ = (\"a\",)\nclass B(A):\n    __slots__ = (\"__dict__\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n\nb = B()\nb.a = 1\nb.b = 2\nb.c = 3  # E: \"B\" has no attribute \"c\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithExplicitSuperDict]\nclass A:\n    __slots__ = (\"__dict__\",)\nclass B(A):\n    __slots__ = (\"a\",)\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n\nb = B()\nb.a = 1\nb.b = 2\nb.c = 3  # E: \"B\" has no attribute \"c\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentWithVariable]\nslot_name = \"b\"\nclass A:\n    __slots__ = (\"a\", slot_name)\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.c = 3\n\na = A()\na.a = 1\na.b = 2\na.c = 3\na.d = 4  # E: \"A\" has no attribute \"d\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentMultipleLeftValues]\nclass A:\n    __slots__ = (\"a\", \"b\")\n    def __init__(self) -> None:\n        self.a, self.b, self.c = (1, 2, 3)  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsAssignmentMultipleAssignments]\nclass A:\n    __slots__ = (\"a\",)\n    def __init__(self) -> None:\n        self.a = self.b = self.c = 1\n[out]\nmain:4: error: Trying to assign name \"b\" that is not in \"__slots__\" of type \"__main__.A\"\nmain:4: error: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsWithTupleCall]\nclass A:\n    # TODO: for now this way of writing tuples are not recognised\n    __slots__ = tuple((\"a\", \"b\"))\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n[builtins fixtures/tuple.pyi]\n\n\n[case testSlotsWithListCall]\nclass A:\n    # TODO: for now this way of writing lists are not recognised\n    __slots__ = list((\"a\", \"b\"))\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n[builtins fixtures/list.pyi]\n\n\n[case testSlotsWithSetCall]\nclass A:\n    # TODO: for now this way of writing sets are not recognised\n    __slots__ = set((\"a\", \"b\"))\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n[builtins fixtures/set.pyi]\n\n\n[case testSlotsWithDictCall]\nclass A:\n    # TODO: for now this way of writing dicts are not recognised\n    __slots__ = dict(((\"a\", \"docs\"), (\"b\", \"docs\")))\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n[builtins fixtures/dict.pyi]\n\n\n[case testSlotsWithAny]\nfrom typing import Any\n\nsome_obj: Any\n\nclass A:\n    # You can do anything with `Any`:\n    __slots__ = some_obj\n\n    def __init__(self) -> None:\n        self.a = 1\n        self.b = 2\n        self.missing = 3\n[builtins fixtures/tuple.pyi]\n\n[case testSlotsWithClassVar]\nfrom typing import ClassVar\nclass X:\n    __slots__ = ('a',)\n    a: int\nx = X()\nX.a  # E: \"a\" in __slots__ conflicts with class variable access\nx.a\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-statements.test",
    "content": "-- Return statement\n-- ----------------\n\n\n[case testReturnValue]\nimport typing\ndef f() -> 'A':\n    return A()\ndef g() -> 'B':\n    return A()\nclass A:\n    pass\nclass B:\n    pass\n[out]\nmain:5: error: Incompatible return value type (got \"A\", expected \"B\")\n\n[case testReturnSubtype]\nimport typing\ndef f() -> 'B':\n    return A()\ndef g() -> 'A':\n    return B()\nclass A:\n    pass\nclass B(A):\n    pass\n[out]\nmain:3: error: Incompatible return value type (got \"A\", expected \"B\")\n\n[case testReturnWithoutAValue]\nimport typing\ndef f() -> 'A':\n    return\ndef g() -> None:\n    return\nclass A:\n    pass\n[out]\nmain:3: error: Return value expected\n\n[case testReturnNoneInFunctionReturningNone]\nimport typing\ndef f() -> None:\n    return None\ndef g() -> None:\n    return f()\n[out]\n\n[case testReturnInGenerator]\nfrom typing import Generator\ndef f() -> Generator[int, None, str]:\n    yield 1\n    return \"foo\"\n[out]\n\n[case testEmptyReturnInGenerator]\nfrom typing import Generator\ndef f() -> Generator[int, None, str]:\n    yield 1\n    return  # E: Return value expected\n[out]\n\n[case testNoReturnInGenerator]\nfrom typing import Generator\ndef f() -> Generator[int, None, str]:  # E: Missing return statement\n    yield 1\n[out]\n\n[case testEmptyReturnInNoneTypedGenerator]\nfrom typing import Generator\ndef f() -> Generator[int, None, None]:\n    yield 1\n    return\n[out]\n\n[case testNonEmptyReturnInNoneTypedGenerator]\nfrom typing import Generator\ndef f() -> Generator[int, None, None]:\n    yield 1\n    return 42  # E: No return value expected\n[out]\n\n[case testReturnInIterator]\nfrom typing import Iterator\ndef f() -> Iterator[int]:\n    yield 1\n    return \"foo\" # E: No return value expected\n[out]\n\n\n-- If statement\n-- ------------\n\n\n[case testIfStatement]\n\na: A\na2: A\na3: A\nb: bool\nif a:\n    a = b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nelif a2:\n    a = b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nelif a3:\n    a = b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nelse:\n    a = b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif b:\n    pass\nelif b:\n    pass\nif b:\n    pass\n\nclass A: pass\n[builtins fixtures/bool.pyi]\n\n\n-- Loops\n-- -----\n\n\n[case testWhileStatement]\n\na: A\nb: bool\nwhile a:\n    a = b    # Fail\nelse:\n    a = b    # Fail\nwhile b:\n    b = b\n\nclass A: pass\n[builtins fixtures/bool.pyi]\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nmain:7: error: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\n\n[case testForStatement]\nclass A: pass\n\na: A\nb: object\nfor a in [A()]:\n    a = b  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nelse:\n    a = b  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n[builtins fixtures/list.pyi]\n\n[case testBreakStatement]\nimport typing\nwhile None:\n    break\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testContinueStatement]\nimport typing\nwhile None:\n    continue\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testForStatementTypeComments]\n\nfrom typing import List, Union\nx = []  # type: List[int]\n\nfor y in x:  # type: str  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    pass\n\nfor z in x:  # type: int\n    pass\n\nfor w in x:  # type: Union[int, str]\n    reveal_type(w)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\nfor v in x:  # type: int, int  # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n    pass\n[builtins fixtures/list.pyi]\n\n[case testForStatementMultipleTypeComments]\n\nfrom typing import List, Tuple\nx = []  # type: List[Tuple[int, int]]\n\nfor y in x:  # type: int, int  # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n    pass\n\nfor z in x:  # type: Tuple[int, int]\n    pass\n\nfor w,v in x:  # type: int, str  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    pass\n\nfor a, b in x:  # type: int, int, int  # E: Incompatible number of tuple items\n    pass\n[builtins fixtures/list.pyi]\n\n\n-- Operator assignment\n-- -------------------\n\n\n[case testPlusAssign]\na: A\nb: B\nc: C\na += b   # Fail\nb += a   # Fail\nc += a   # Fail\na += c\n\nclass A:\n    def __add__(self, x: 'C') -> 'A': pass\n\nclass B:\n    def __add__(self, x: A) -> 'C': pass\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:4: error: Unsupported operand types for + (\"A\" and \"B\")\nmain:5: error: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\nmain:6: error: Unsupported left operand type for + (\"C\")\n\n[case testMinusAssign]\na: A\nb: B\nc: C\na -= b   # Fail\nb -= a   # Fail\nc -= a   # Fail\na -= c\n\nclass A:\n    def __sub__(self, x: 'C') -> 'A': pass\n\nclass B:\n    def __sub__(self, x: A) -> 'C': pass\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:4: error: Unsupported operand types for - (\"A\" and \"B\")\nmain:5: error: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\nmain:6: error: Unsupported left operand type for - (\"C\")\n\n[case testMulAssign]\na: A\nc: C\na *= a   # Fail\nc *= a   # Fail\na *= c\n\nclass A:\n    def __mul__(self, x: 'C') -> 'A': pass\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:3: error: Unsupported operand types for * (\"A\" and \"A\")\nmain:4: error: Unsupported left operand type for * (\"C\")\n\n[case testMatMulAssign]\na: A\nc: C\na @= a   # E: Unsupported operand types for @ (\"A\" and \"A\")\nc @= a   # E: Unsupported left operand type for @ (\"C\")\na @= c\n\nclass A:\n    def __matmul__(self, x: 'C') -> 'A': pass\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n\n[case testDivAssign]\na: A\nc: C\na /= a   # Fail\nc /= a   # Fail\na /= c\n\nclass A:\n    def __truediv__(self, x: 'C') -> 'A': pass\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:3: error: Unsupported operand types for / (\"A\" and \"A\")\nmain:4: error: Unsupported left operand type for / (\"C\")\n\n[case testPowAssign]\na: A\nc: C\na **= a   # Fail\nc **= a   # Fail\na **= c\n\nclass A:\n    def __pow__(self, x: 'C') -> 'A': pass\n\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:3: error: Unsupported operand types for ** (\"A\" and \"A\")\nmain:4: error: Unsupported left operand type for ** (\"C\")\n\n[case testSubtypesInOperatorAssignment]\na: A\nb: B\nb += b\nb += a\na += b\n\nclass A:\n    def __add__(self, x: 'A') -> 'B': pass\n\nclass B(A): pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testAdditionalOperatorsInOpAssign]\na: A\nc: C\na &= a  # Fail\na >>= a # Fail\na //= a # Fail\na &= c\na >>= c\na //= c\nclass A:\n    def __and__(self, x: 'C') -> 'A': pass\n    def __rshift__(self, x: 'C') -> 'A': pass\n    def __floordiv__(self, x: 'C') -> 'A': pass\nclass C: 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 \"A\")\nmain:5: error: Unsupported operand types for // (\"A\" and \"A\")\n\n[case testInplaceOperatorMethods]\nimport typing\nclass A:\n    def __iadd__(self, x: int) -> 'A': pass\n    def __imul__(self, x: str) -> 'A': pass\n    def __imatmul__(self, x: str) -> 'A': pass\na = A()\na += 1\na *= ''\na @= ''\na += '' # E: Argument 1 to \"__iadd__\" of \"A\" has incompatible type \"str\"; expected \"int\"\na *= 1  # E: Argument 1 to \"__imul__\" of \"A\" has incompatible type \"int\"; expected \"str\"\na @= 1  # E: Argument 1 to \"__imatmul__\" of \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testInplaceSetitem]\nclass A(object):\n    def __init__(self) -> None:\n        self.a = [1]\n\n    def __iadd__(self, a):\n        # type: (int) -> A\n        self.a += [2]\n        return self\n\na = A()\nb = [a]\nb[0] += 1\n[builtins fixtures/list.pyi]\n[out]\n\n\n-- Assert statement\n-- ----------------\n\n\n[case testAssert]\nimport typing\nassert None + None # Fail\nassert None\n[out]\nmain:2: error: Unsupported left operand type for + (\"None\")\n\n\n-- Exception handling\n-- ------------------\n\n\n[case testRaiseStatement]\n\ne: BaseException\nf: MyError\na: A\nraise a # Fail\nraise e\nraise f\nclass A: pass\nclass MyError(BaseException): pass\n[builtins fixtures/exception.pyi]\n[out]\nmain:5: error: Exception must be derived from BaseException\n\n[case testRaiseClassObject]\nclass A: pass\nclass MyError(BaseException): pass\ndef f(): pass\nif object():\n    raise BaseException\nif object():\n    raise MyError\nif object():\n    raise A # E: Exception must be derived from BaseException\nif object():\n    raise object # E: Exception must be derived from BaseException\nif object():\n    raise f # E: Exception must be derived from BaseException\n[builtins fixtures/exception.pyi]\n\n[case testRaiseClassObjectCustomInit]\nclass MyBaseError(BaseException):\n    def __init__(self, required) -> None:\n        ...\nclass MyError(Exception):\n    def __init__(self, required1, required2) -> None:\n        ...\nclass MyKwError(Exception):\n    def __init__(self, *, kwonly) -> None:\n        ...\nclass MyErrorWithDefault(Exception):\n    def __init__(self, optional=1) -> None:\n        ...\nif object():\n    raise BaseException\nif object():\n    raise Exception\nif object():\n    raise BaseException(1)\nif object():\n    raise Exception(2)\nif object():\n    raise MyBaseError(4)\nif object():\n    raise MyError(5, 6)\nif object():\n    raise MyKwError(kwonly=7)\nif object():\n    raise MyErrorWithDefault(8)\nif object():\n    raise MyErrorWithDefault\nif object():\n    raise MyBaseError  # E: Too few arguments for \"MyBaseError\"\nif object():\n    raise MyError  # E: Too few arguments for \"MyError\"\nif object():\n    raise MyKwError  # E: Missing named argument \"kwonly\" for \"MyKwError\"\n[builtins fixtures/exception.pyi]\n\n[case testRaiseExceptionType]\nimport typing\nx: typing.Type[BaseException]\nraise x\n[builtins fixtures/exception.pyi]\n\n[case testRaiseNonExceptionTypeFails]\nimport typing\nx = int # type: typing.Type[int]\nraise x # E: Exception must be derived from BaseException\n[builtins fixtures/exception.pyi]\n\n[case testRaiseUnion]\nimport typing\nx: typing.Union[BaseException, typing.Type[BaseException]]\nraise x\n[builtins fixtures/exception.pyi]\n\n[case testRaiseNonExceptionUnionFails]\nimport typing\nx: typing.Union[BaseException, int]\nraise x # E: Exception must be derived from BaseException\n[builtins fixtures/exception.pyi]\n\n[case testRaiseFromStatement]\ne: BaseException\nf: MyError\na: A\nx: BaseException\ndel x\nif object():\n    raise e from a # E: Exception must be derived from BaseException\nif object():\n    raise e from e\nif object():\n    raise e from f\nif object():\n    raise e from x # E: Trying to read deleted variable \"x\"\nclass A: pass\nclass MyError(BaseException): pass\n[builtins fixtures/exception.pyi]\n\n[case testRaiseFromClassobject]\nimport typing\nclass A: pass\nclass MyError(BaseException): pass\ndef f(): pass\nif object():\n    raise BaseException from BaseException\nif object():\n    raise BaseException from MyError\nif object():\n    raise BaseException from A # E: Exception must be derived from BaseException\nif object():\n    raise BaseException from object # E: Exception must be derived from BaseException\nif object():\n    raise BaseException from f # E: Exception must be derived from BaseException\n[builtins fixtures/exception.pyi]\n\n[case testRaiseNotImplementedFails]\nif object():\n    raise NotImplemented    # E: Exception must be derived from BaseException; did you mean \"NotImplementedError\"?\nif object():\n    raise NotImplemented()  # E: NotImplemented? not callable\n[builtins fixtures/notimplemented.pyi]\n\n[case testTryFinallyStatement]\nimport typing\ntry:\n    b = object() # type: A # Fail\nfinally:\n    c = object() # type: A # Fail\nclass A: pass\n[out]\nmain:3: error: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nmain:5: error: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n\n[case testSimpleTryExcept]\n\ntry:\n  pass\nexcept BaseException as e:\n  a: BaseException\n  o: object\n  e = a\n  e = o # Fail\nclass A: pass\nclass B: pass\n[builtins fixtures/exception.pyi]\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"object\", variable has type \"BaseException\")\n\n[case testTypeErrorInBlock]\nclass A: pass\nclass B: pass\nwhile int():\n    x: A\n    if int():\n        x = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n        x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testTypeErrorInvolvingBaseException]\nclass A: pass\n\nx: BaseException\na: A\nif int():\n    a = BaseException()  # E: Incompatible types in assignment (expression has type \"BaseException\", variable has type \"A\")\nif int():\n    a = object()         # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nif int():\n    x = object()         # E: Incompatible types in assignment (expression has type \"object\", variable has type \"BaseException\")\nif int():\n    x = A()              # E: Incompatible types in assignment (expression has type \"A\", variable has type \"BaseException\")\nif int():\n    x = BaseException()\n[builtins fixtures/exception.pyi]\n\n[case testSimpleTryExcept2]\nimport typing\ntry:\n  pass\nexcept BaseException as e:\n  e = object() # Fail\n  e = BaseException()\n[builtins fixtures/exception.pyi]\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"object\", variable has type \"BaseException\")\n\n[case testBaseClassAsExceptionTypeInExcept]\nimport typing\nclass Err(BaseException): pass\ntry:\n  pass\nexcept Err as e:\n  e = BaseException()  # E: Incompatible types in assignment (expression has type \"BaseException\", variable has type \"Err\")\n  e = Err()\n[builtins fixtures/exception.pyi]\n[case testMultipleExceptHandlers]\nimport typing\nclass Err(BaseException): pass\ntry:\n    pass\nexcept BaseException as e:\n    pass\nexcept Err as f:\n    f = BaseException()  # E: Incompatible types in assignment (expression has type \"BaseException\", variable has type \"Err\")\n    f = Err()\n[builtins fixtures/exception.pyi]\n[case testTryExceptStatement]\nimport typing\nclass A: pass\nclass B: pass\nclass Err(BaseException): pass\ntry:\n    a = B() # type: A  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nexcept BaseException as e:\n    e = A()  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"BaseException\")\n    e = Err()\nexcept Err as f:\n    f = BaseException()  # E: Incompatible types in assignment (expression has type \"BaseException\", variable has type \"Err\")\n    f = Err()\n[builtins fixtures/exception.pyi]\n[case testTryExceptWithinFunction]\nimport typing\ndef f() -> None:\n  try: pass\n  except BaseException as e:\n    e = object() # Fail\n    e = BaseException()\n  except Err as f:\n    f = BaseException() # Fail\n    f = Err()\nclass Err(BaseException): pass\n[builtins fixtures/exception.pyi]\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"object\", variable has type \"BaseException\")\nmain:8: error: Incompatible types in assignment (expression has type \"BaseException\", variable has type \"Err\")\n\n[case testTryExceptFlow]\ndef f() -> None:\n  x = 1\n  try:\n    pass\n  except:\n    raise\n  x + 'a' # E: Unsupported left operand type for + (\"int\")\n[builtins fixtures/exception.pyi]\n[out]\n\n[case testTryWithElse]\nimport typing\ntry: pass\nexcept BaseException: pass\nelse:\n  object(None) # E: Too many arguments for \"object\"\n[builtins fixtures/exception.pyi]\n\n[case testRedefinedFunctionInTryWithElse]\ndef f() -> None: pass\ntry:\n    pass\nexcept BaseException:\n    f2 = f\nelse:\n    def f2() -> str: pass\ntry:\n    pass\nexcept BaseException:\n    f3 = f\nelse:\n    def f3() -> None: pass\n[builtins fixtures/exception.pyi]\n[out]\nmain:7: error: Incompatible redefinition (redefinition with type \"Callable[[], str]\", original type \"Callable[[], None]\")\n\n[case testExceptWithoutType]\nimport typing\ntry:\n    -None # E: Unsupported operand type for unary - (\"None\")\nexcept:\n    ~None # E: Unsupported operand type for ~ (\"None\")\n[builtins fixtures/exception.pyi]\n\n[case testRaiseWithoutArgument]\nimport typing\ntry:\n    None\nexcept:\n    raise\n[builtins fixtures/exception.pyi]\n\n[case testExceptWithMultipleTypes]\nimport typing\nclass E1(BaseException): pass\nclass E2(E1): pass\ntry:\n    pass\nexcept (E1, E2): pass\nexcept (E1, object): pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\nexcept (object, E2): pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\nexcept (E1, (E2,)): pass  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n\nexcept (E1, E2): pass\nexcept ((E1, E2)): pass\nexcept (((E1, E2))): pass\n[builtins fixtures/exception.pyi]\n\n[case testExceptWithTypeType]\nimport typing\nE = BaseException  # type: typing.Type[BaseException]\n\ntry:\n    pass\nexcept E:\n    pass\n[builtins fixtures/exception.pyi]\n\n[case testExceptWithMultipleTypes2]\nimport typing\nclass E1(BaseException): pass\nclass E2(E1): pass\ntry:\n    pass\nexcept (E1, E2) as e1:\n    x = e1 # type: E1\n    y = e1 # type: E2 # E: Incompatible types in assignment (expression has type \"E1\", variable has type \"E2\")\nexcept (E2, E1) as e2:\n    a = e2 # type: E1\n    b = e2 # type: E2 # E: Incompatible types in assignment (expression has type \"E1\", variable has type \"E2\")\nexcept (E1, E2, int) as e3: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\n[builtins fixtures/exception.pyi]\n\n[case testExceptWithMultipleTypes3]\nimport typing\nclass E1(BaseException): pass\nclass E1_1(E1): pass\nclass E1_2(E1): pass\ntry: pass\nexcept (E1, E1_1, E1_2) as e1:\n    x = e1 # type: E1\n    y = e1 # type: E1_1 # E: Incompatible types in assignment (expression has type \"E1\", variable has type \"E1_1\")\n    z = e1 # type: E1_2 # E: Incompatible types in assignment (expression has type \"E1\", variable has type \"E1_2\")\nexcept (E1_1, E1_2) as e2:\n    a = e2 # type: E1\n    b = e2 # type: E1_1 # E: Incompatible types in assignment (expression has type \"Union[E1_1, E1_2]\", variable has type \"E1_1\")\n    c = e2 # type: E1_2 # E: Incompatible types in assignment (expression has type \"Union[E1_1, E1_2]\", variable has type \"E1_2\")\n[builtins fixtures/exception.pyi]\n\n[case testExceptWithMultipleTypes4]\nfrom typing import Tuple, Type, Union\n\nclass E1(BaseException): pass\nclass E2(BaseException): pass\nclass E3(BaseException): pass\n\ndef variadic(exc: Tuple[Type[E1], ...]) -> None:\n    try:\n        pass\n    except exc as e:\n        reveal_type(e)  # N: Revealed type is \"__main__.E1\"\n\ndef union(exc: Union[Type[E1], Type[E2]]) -> None:\n    try:\n        pass\n    except exc as e:\n        reveal_type(e)  # N: Revealed type is \"Union[__main__.E1, __main__.E2]\"\n\ndef tuple_in_union(exc: Union[Type[E1], Tuple[Type[E2], Type[E3]]]) -> None:\n    try:\n        pass\n    except exc as e:\n        reveal_type(e)  # N: Revealed type is \"Union[__main__.E1, __main__.E2, __main__.E3]\"\n\ndef variadic_in_union(exc: Union[Type[E1], Tuple[Type[E2], ...]]) -> None:\n    try:\n        pass\n    except exc as e:\n        reveal_type(e)  # N: Revealed type is \"Union[__main__.E1, __main__.E2]\"\n\ndef nested_union(exc: Union[Type[E1], Union[Type[E2], Type[E3]]]) -> None:\n    try:\n        pass\n    except exc as e:\n        reveal_type(e)  # N: Revealed type is \"Union[__main__.E1, __main__.E2, __main__.E3]\"\n\ndef error_in_union(exc: Union[Type[E1], int]) -> None:\n    try:\n        pass\n    except exc as e:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n        pass\n\ndef error_in_variadic(exc: Tuple[int, ...]) -> None:\n    try:\n        pass\n    except exc as e:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n        pass\n\n[builtins fixtures/tuple.pyi]\n\n[case testExceptWithAnyTypes]\nfrom typing import Any\n\nE1 = None  # type: Any\nclass E2(BaseException): pass\nclass NotBaseDerived: pass\n\ntry:\n    pass\nexcept BaseException as e1:\n    reveal_type(e1)  # N: Revealed type is \"builtins.BaseException\"\nexcept (E1, BaseException) as e2:\n    reveal_type(e2)  # N: Revealed type is \"Union[Any, builtins.BaseException]\"\nexcept (E1, E2) as e3:\n    reveal_type(e3)  # N: Revealed type is \"Union[Any, __main__.E2]\"\nexcept (E1, E2, BaseException) as e4:\n    reveal_type(e4)  # N: Revealed type is \"Union[Any, builtins.BaseException]\"\n\ntry: pass\nexcept E1 as e1:\n    reveal_type(e1)  # N: Revealed type is \"Any\"\nexcept E2 as e2:\n    reveal_type(e2)  # N: Revealed type is \"__main__.E2\"\nexcept NotBaseDerived as e3:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\nexcept (NotBaseDerived, E1) as e4:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\nexcept (NotBaseDerived, E2) as e5:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\nexcept (NotBaseDerived, E1, E2) as e6:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\nexcept (E1, E2, NotBaseDerived) as e6:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\n[builtins fixtures/exception.pyi]\n\n[case testReuseTryExceptionVariable]\nimport typing\nclass E1(BaseException): pass\nclass E2(BaseException): pass\ntry: pass\nexcept E1 as e: pass\ntry: pass\nexcept E1 as e: pass\ntry: pass\nexcept E2 as e: pass\ne + 1 # E: Trying to read deleted variable \"e\"  # E: Name \"e\" is used before definition\ne = E1() # E: Assignment to variable \"e\" outside except: block\n[builtins fixtures/exception.pyi]\n\n[case testReuseDefinedTryExceptionVariable]\nimport typing\nclass E1(BaseException): pass\nclass E2(BaseException): pass\ne = 1\ndef f(): e  # Prevent redefinition\ne = 1\ntry: pass\nexcept E1 as e: pass\ne = 1 # E: Assignment to variable \"e\" outside except: block\ne = E1() # E: Assignment to variable \"e\" outside except: block\n[builtins fixtures/exception.pyi]\n\n[case testExceptionVariableReuseInDeferredNode1]\ndef f(*a: BaseException) -> int:\n    x\n    try: pass\n    except BaseException as err: pass\n    try: pass\n    except BaseException as err: f(err)\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n\n[case testExceptionVariableReuseInDeferredNode2]\ndef f(*a: BaseException) -> int:\n    try: pass\n    except BaseException as err: pass\n    x\n    try: pass\n    except BaseException as err: f(err)\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n\n[case testExceptionVariableReuseInDeferredNode3]\ndef f(*a: BaseException) -> int:\n    try: pass\n    except BaseException as err: pass\n    try: pass\n    except BaseException as err: f(err)\n    x\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n\n[case testExceptionVariableReuseInDeferredNode4]\nclass EA(BaseException):\n    a = None  # type: int\nclass EB(BaseException):\n    b = None  # type: str\ndef f(*arg: BaseException) -> int:\n    x\n    try: pass\n    except EA as err:\n        f(err)\n        a = err.a\n        reveal_type(a)\n    try: pass\n    except EB as err:\n        f(err)\n        b = err.b\n        reveal_type(b)\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n[out]\nmain:11: note: Revealed type is \"builtins.int\"\nmain:16: note: Revealed type is \"builtins.str\"\n\n[case testExceptionVariableReuseInDeferredNode5]\nclass EA(BaseException):\n    a = None  # type: int\nclass EB(BaseException):\n    b = None  # type: str\ndef f(*arg: BaseException) -> int:\n    try: pass\n    except EA as err:\n        f(err)\n        a = err.a\n        reveal_type(a)\n    x\n    try: pass\n    except EB as err:\n        f(err)\n        b = err.b\n        reveal_type(b)\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n[out]\nmain:10: note: Revealed type is \"builtins.int\"\nmain:16: note: Revealed type is \"builtins.str\"\n\n[case testExceptionVariableReuseInDeferredNode6]\nclass EA(BaseException):\n    a = None  # type: int\nclass EB(BaseException):\n    b = None  # type: str\ndef f(*arg: BaseException) -> int:\n    try: pass\n    except EA as err:\n        f(err)\n        a = err.a\n        reveal_type(a)\n    try: pass\n    except EB as err:\n        f(err)\n        b = err.b\n        reveal_type(b)\n    x\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n[out]\nmain:10: note: Revealed type is \"builtins.int\"\nmain:15: note: Revealed type is \"builtins.str\"\n\n[case testExceptionVariableWithDisallowAnyExprInDeferredNode]\n# flags: --disallow-any-expr\ndef f() -> int:\n    x\n    try:\n        pass\n    except Exception as ex:\n        pass\n    return 0\nx = f()\n[builtins fixtures/exception.pyi]\n\n[case testArbitraryExpressionAsExceptionType]\nimport typing\na = BaseException\ntry: pass\nexcept a as b:\n    b = BaseException()\n    b = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"BaseException\")\n[builtins fixtures/exception.pyi]\n\n[case testInvalidExceptionCallable]\nimport typing\ndef exc() -> BaseException: pass\ntry: pass\nexcept exc as e: pass             # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\nexcept BaseException() as b: pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n[builtins fixtures/exception.pyi]\n\n[case testTupleValueAsExceptionType]\nimport typing\ndef exc() -> BaseException: pass\nclass E1(BaseException): pass\nclass E1_1(E1): pass\nclass E1_2(E1): pass\n\nexs1 = (E1, E1_1, E1_2)\ntry: pass\nexcept exs1 as e1:\n    x = e1 # type: E1\n    y = e1 # type: E1_1 # E: Incompatible types in assignment (expression has type \"E1\", variable has type \"E1_1\")\n    z = e1 # type: E1_2 # E: Incompatible types in assignment (expression has type \"E1\", variable has type \"E1_2\")\n\nexs2 = (E1_1, E1_2)\ntry: pass\nexcept exs2 as e2:\n    a = e2 # type: E1\n    b = e2 # type: E1_1 # E: Incompatible types in assignment (expression has type \"Union[E1_1, E1_2]\", variable has type \"E1_1\")\n    c = e2 # type: E1_2 # E: Incompatible types in assignment (expression has type \"Union[E1_1, E1_2]\", variable has type \"E1_2\")\n\nexs3 = (E1, (E1_1, (E1_2,)))\ntry: pass\nexcept exs3 as e3: pass  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n[builtins fixtures/exception.pyi]\n\n[case testInvalidTupleValueAsExceptionType]\nimport typing\ndef exc() -> BaseException: pass\nclass E1(BaseException): pass\nclass E2(E1): pass\n\nexs1 = (E1, E2, int)\ntry: pass\nexcept exs1 as e: pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n[builtins fixtures/exception.pyi]\n\n[case testOverloadedExceptionType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass E(BaseException):\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x) -> None: pass\ntry:\n    pass\nexcept E as e:\n    e = E()\n    e = BaseException() # E: Incompatible types in assignment (expression has type \"BaseException\", variable has type \"E\")\n[builtins fixtures/exception.pyi]\n\n[case testExceptionWithAnyBaseClass]\nfrom typing import Any\nE = None  # type: Any\nclass EE(E): pass\nraise EE()\nraise EE\n[builtins fixtures/exception.pyi]\n\n[case testExceptionIsType]\nfrom typing import Type\nclass B(BaseException): pass\ndef f(e: Type[B]):\n    try: pass\n    except e: pass\ndef g(e: Type[BaseException]):\n    try: pass\n    except e as err:\n        reveal_type(err)\ndef h(e: Type[int]):\n    try: pass\n    except e: pass\n[builtins fixtures/exception.pyi]\n[out]\nmain:9: note: Revealed type is \"builtins.BaseException\"\nmain:12: error: Exception type must be derived from BaseException (or be a tuple of exception classes)\n\n\n-- Del statement\n-- -------------\n\n\n[case testDelStmtWithIndex]\na: A\nb: B\ndel b[a]\ndel b[b] # E: Argument 1 to \"__delitem__\" of \"B\" has incompatible type \"B\"; expected \"A\"\ndel a[a] # E: \"A\" has no attribute \"__delitem__\"\ndel a[b] # E: \"A\" has no attribute \"__delitem__\"\nclass B:\n  def __delitem__(self, index: 'A'): pass\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n[case testDelStmtWithAttribute]\nclass A:\n    def f(self): pass\n    x = 0\na = A()\ndel a.f\ndel a.x\ndel a.z # E: \"A\" has no attribute \"z\"\n\n[case testDelStatementWithTuple]\nclass A:\n    x = 0\na = A()\ndel a.x, a.y # E: \"A\" has no attribute \"y\"\n[builtins fixtures/tuple.pyi]\n\n[case testDelStmtWithTypeInfo]\nclass Foo: ...\ndel Foo\nFoo + 1  # E: Trying to read deleted variable \"Foo\"\n\n[case testDelStatementWithAssignmentSimple]\na = 1\na + 1\ndel a\na + 1 # E: Trying to read deleted variable \"a\"\n[builtins fixtures/ops.pyi]\n\n[case testDelStatementWithAssignmentTuple]\na = 1\nb = 1\ndel (a, b)\nb + 1 # E: Trying to read deleted variable \"b\"\n[builtins fixtures/ops.pyi]\n\n[case testDelStatementWithAssignmentList]\na = 1\nb = 1\ndel [a, b]\nb + 1 # E: Trying to read deleted variable \"b\"\n[builtins fixtures/list.pyi]\n\n[case testDelStatementWithAssignmentClass]\nclass C:\n    a = 1\n\nc = C()\nc.a = 1\nc.a + 1\ndel c.a\nc.a + 1\n[builtins fixtures/ops.pyi]\n\n[case testDelStatementWithConditions]\nx = 5\ndel x\nif x: ...  # E: Trying to read deleted variable \"x\"\n\ndef f(x):\n    return x\n\nif 0: ...\nelif f(x): ...  # E: Trying to read deleted variable \"x\"\n\nwhile x == 5: ...  # E: Trying to read deleted variable \"x\"\n\n-- Yield statement\n-- ---------------\n\n\n[case testSimpleYield]\nfrom typing import Iterator\ndef f() -> Iterator[int]:\n    yield 1\n    yield '' # E: Incompatible types in \"yield\" (actual type \"str\", expected type \"int\")\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldInFunctionReturningGenerator]\nfrom typing import Generator\ndef f() -> Generator[int, None, None]:\n    yield 1\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldInFunctionReturningIterable]\nfrom typing import Iterable\ndef f() -> Iterable[int]:\n    yield 1\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldInFunctionReturningObject]\ndef f() -> object:\n    yield 1\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldInFunctionReturningAny]\nfrom typing import Any\ndef f() -> Any:\n    yield object()\n[out]\n\n[case testYieldInFunctionReturningFunction]\nfrom typing import Callable\ndef f() -> Callable[[], None]: # E: The return type of a generator function should be \"Generator\" or one of its supertypes\n    yield object()\n[out]\n\n[case testYieldInDynamicallyTypedFunction]\nimport typing\ndef f():\n    yield f\n\n[case testWithInvalidInstanceReturnType]\nimport typing\ndef f() -> int: # E: The return type of a generator function should be \"Generator\" or one of its supertypes\n    yield 1\n[builtins fixtures/for.pyi]\n[out]\n\n[case testTypeInferenceContextAndYield]\nfrom typing import List, Iterator\ndef f() -> 'Iterator[List[int]]':\n    yield []\n    yield [object()] # E: List item 0 has incompatible type \"object\"; expected \"int\"\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldAndReturnWithoutValue]\nfrom typing import Iterator\ndef f() -> Iterator[int]:\n    yield 1\n    return\n[builtins fixtures/for.pyi]\n\n[case testYieldWithNoValue]\nfrom typing import Iterator\ndef f() -> Iterator[None]:\n    yield\n[builtins fixtures/for.pyi]\n\n[case testYieldWithNoValueWhenValueRequired]\nfrom typing import Iterator\ndef f() -> Iterator[int]:\n    yield  # E: Yield value expected\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldWithExplicitNone]\nfrom typing import Iterator\ndef f() -> Iterator[None]:\n    yield None\n[builtins fixtures/for.pyi]\n[out]\n\n\n-- Yield from statement\n-- --------------------\n--\n-- (It's not really a statement, but don't want to move the tests.)\n\n[case testSimpleYieldFromWithIterator]\nfrom typing import Iterator\ndef g() -> Iterator[str]:\n    yield '42'\ndef h() -> Iterator[int]:\n    yield 42\ndef f() -> Iterator[str]:\n    yield from g()\n    yield from h()  # E: Incompatible types in \"yield from\" (actual type \"int\", expected type \"str\")\n[out]\n\n[case testYieldFromAppliedToAny]\nfrom typing import Any\ndef g() -> Any:\n    yield object()\ndef f() -> Any:\n    yield from g()\n[out]\n\n[case testYieldFromInFunctionReturningFunction]\nfrom typing import Iterator, Callable\ndef g() -> Iterator[int]:\n    yield 42\ndef f() -> Callable[[], None]:  # E: The return type of a generator function should be \"Generator\" or one of its supertypes\n    yield from g()\n[out]\n\n[case testYieldFromNotIterableReturnType]\nfrom typing import Iterator\ndef g() -> Iterator[int]:\n    yield 42\ndef f() -> int:  # E: The return type of a generator function should be \"Generator\" or one of its supertypes\n    yield from g()\n[out]\n\n[case testYieldFromNotAppliedIterator]\nfrom typing import Iterator\ndef g() -> int:\n    return 42\ndef f() -> Iterator[int]:\n    yield from g()  # E: \"yield from\" can't be applied to \"int\"\n[out]\n\n[case testYieldFromCheckIncompatibleTypesTwoIterables]\nfrom typing import List, Iterator\ndef g() -> Iterator[List[int]]:\n    yield [2, 3, 4]\ndef f() -> Iterator[List[int]]:\n    yield from g()\n    yield from [1, 2, 3]  # E: Incompatible types in \"yield from\" (actual type \"int\", expected type \"List[int]\")\n[builtins fixtures/for.pyi]\n[out]\n\n[case testYieldFromNotAppliedToNothing]\ndef h():\n    yield from  # E: invalid syntax\n[out]\n\n[case testYieldFromAndYieldTogether]\nfrom typing import Iterator\ndef f() -> Iterator[str]:\n    yield \"g1 ham\"\n    yield from g()\n    yield \"g1 eggs\"\ndef g() -> Iterator[str]:\n    yield \"g2 spam\"\n    yield \"g2 more spam\"\n[out]\n\n[case testYieldFromAny]\nfrom typing import Iterator\ndef f(a):\n    b = yield from a\n    return b\n[out]\n\n[case testYieldFromGenericCall]\nfrom typing import Generator, TypeVar\nT = TypeVar('T')\ndef f(a: T) -> Generator[int, str, T]: pass\ndef g() -> Generator[int, str, float]:\n    r = yield from f('')\n    reveal_type(r)  # N: Revealed type is \"builtins.str\"\n    return 3.14\n\n[case testYieldFromTupleStatement]\nfrom typing import Generator\ndef g() -> Generator[int, None, None]:\n    yield from ()\n    yield from (0, 1, 2)\n    yield from (0, \"ERROR\")  # E: Incompatible types in \"yield from\" (actual type \"Union[int, str]\", expected type \"int\")\n    yield from (\"ERROR\",)  # E: Incompatible types in \"yield from\" (actual type \"str\", expected type \"int\")\n[builtins fixtures/tuple.pyi]\n\n-- With statement\n-- --------------\n\n\n[case testSimpleWith]\nimport typing\nclass A:\n    def __enter__(self) -> None: pass\n    def __exit__(self, x, y, z) -> None: pass\nwith A():\n    object(A) # E: Too many arguments for \"object\"\n\n[case testWithStmtAndInvalidExit]\nimport typing\nclass A:\n    def __enter__(self) -> None: pass\n    def __exit__(self, x, y) -> None: pass\nwith A(): # E: Too many arguments for \"__exit__\" of \"A\"\n    pass\n\n[case testWithStmtAndMissingExit]\nimport typing\nclass A:\n    def __enter__(self) -> None: pass\nwith A(): # E: \"A\" has no attribute \"__exit__\"\n    pass\n\n[case testWithStmtAndInvalidEnter]\nimport typing\nclass A:\n    def __enter__(self, x) -> None: pass\n    def __exit__(self, x, y, z) -> None: pass\nwith A(): # E: Too few arguments for \"__enter__\" of \"A\"\n    pass\n\n[case testWithStmtAndMissingEnter]\nimport typing\nclass A:\n    def __exit__(self, x, y, z) -> None: pass\nwith A(): # E: \"A\" has no attribute \"__enter__\"\n    pass\n\n[case testWithStmtAndMultipleExprs]\nimport typing\nclass A:\n    def __enter__(self) -> None: pass\n    def __exit__(self, x, y, z) -> None: pass\nclass B:\n    def __enter__(self) -> None: pass\nwith A(), B(): # E: \"B\" has no attribute \"__exit__\"\n    pass\nwith B(), A(): # E: \"B\" has no attribute \"__exit__\"\n    pass\n\n[case testWithStmtAndResult]\nimport typing\nclass B: pass\nclass A:\n    def __enter__(self) -> B: pass\n    def __exit__(self, x, y, z): pass\nwith A() as b:\n    b = B()\n    b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testWithStmtAndMultipleResults]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass B: pass\nclass C: pass\nclass A(Generic[t]):\n    def __enter__(self) -> t: pass\n    def __exit__(self, x, y, z): pass\na_b = A() # type: A[B]\na_c = A() # type: A[C]\nwith a_b as b, a_c as c:\n    b = B()\n    c = C()\n    b = c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n    c = b # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\n\n[case testWithStmtAndComplexTarget]\nfrom typing import Tuple\nclass A:\n    def __enter__(self) -> Tuple[int, str]: pass\n    def __exit__(self, x, y, z): pass\nwith A() as (a, b):\n    a = 1\n    b = ''\n    a = b # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testWithStmtTypeComment]\n\nfrom typing import Union\nclass A:\n    def __enter__(self) -> int: pass\n    def __exit__(self, x, y, z): pass\n\nwith A():  # type: int  # E: Invalid type comment: \"with\" statement has no targets\n    pass\n\nwith A() as a:  # type: int\n    pass\n\nwith A() as b:  # type: str  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    pass\n\nwith A() as c:  # type: int, int  # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n    pass\n\nwith A() as d:  # type: Union[int, str]\n    reveal_type(d)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testWithStmtTupleTypeComment]\n\nfrom typing import Tuple\nclass A:\n    def __enter__(self) -> Tuple[int, int]: pass\n    def __exit__(self, x, y, z): pass\n\nwith A():\n    pass\n\nwith A() as a:  # type: Tuple[int, int]\n    pass\n\nwith A() as b:  # type: Tuple[int, str]  # E: Incompatible types in assignment (expression has type \"Tuple[int, int]\", variable has type \"Tuple[int, str]\")\n    pass\n\nwith A() as (c, d):  # type: int, int\n    pass\n\nwith A() as (e, f):  # type: Tuple[int, int]\n    pass\n\nwith A() as (g, h):  # type: int  # E: Tuple type expected for multiple variables\n    pass\n\nwith A() as (i, j):  # type: int, int, str  # E: Incompatible number of tuple items\n    pass\n\nwith A() as (k, l):  # type: int, str  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testWithStmtComplexTypeComment]\n\nfrom typing import Tuple\nclass A:\n    def __enter__(self) -> Tuple[int, int]: pass\n    def __exit__(self, x, y, z): pass\n\nclass B:\n    def __enter__(self) -> str: pass\n    def __exit__(self, x, y, z): pass\n\nwith A() as a, A() as (b, c), B() as d:  # type: Tuple[int, int], (int, int), str\n    pass\n\nwith A() as e, A() as (f, g), B() as h:  # type: Tuple[int, int], Tuple[int, int], str\n    pass\n\nwith A() as i, A() as (j, k), B() as l:  # type: (int, int), (int, int), str  # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n    pass\n\nwith A(), A(), B() as m, A() as n, B(), B() as o:  # type: int, Tuple[int, int]  # E: Incompatible number of types for \"with\" targets\n    pass\n\nwith A(), B(), B() as p, A(), A():  # type: str\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testWithStmtBoolExitReturnWithResultFalse]\nfrom typing import Optional\n\nclass InvalidReturn1:\n    def __exit__(self, x, y, z) -> bool:  # E: \"bool\" is invalid as return type for \"__exit__\" that always returns False \\\n# N: Use \"typing_extensions.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\nclass InvalidReturn2:\n    def __exit__(self, x, y, z) -> Optional[bool]:  # E: \"bool\" is invalid as return type for \"__exit__\" that always returns False \\\n# N: Use \"typing_extensions.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        if int():\n            return False\n        else:\n            return False\n\nclass InvalidReturn3:\n    def __exit__(self, x, y, z) -> bool:  # E: \"bool\" is invalid as return type for \"__exit__\" that always returns False \\\n# N: Use \"typing_extensions.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        def nested() -> bool:\n            return True\n        return False\n[builtins fixtures/bool.pyi]\n\n[case testWithStmtBoolExitReturnOkay]\nfrom typing_extensions import Literal\n\nclass GoodReturn1:\n    def __exit__(self, x, y, z) -> bool:\n        if int():\n            return True\n        else:\n            return False\n\nclass GoodReturn2:\n    def __exit__(self, x, y, z) -> bool:\n        if int():\n            return False\n        else:\n            return True\n\nclass GoodReturn3:\n    def __exit__(self, x, y, z) -> bool:\n        return bool()\n\nclass GoodReturn4:\n    def __exit__(self, x, y, z) -> None:\n        return\n\nclass GoodReturn5:\n    def __exit__(self, x, y, z) -> None:\n        return None\n\nclass GoodReturn6:\n    def exit(self, x, y, z) -> bool:\n        return False\n\nclass GoodReturn7:\n    def exit(self, x, y, z) -> bool:\n        pass\n\nclass MissingReturn:\n    def exit(self, x, y, z) -> bool: # E: Missing return statement\n        x = 0\n\nclass LiteralReturn:\n    def __exit__(self, x, y, z) -> Literal[False]:\n        return False\n[builtins fixtures/bool.pyi]\n\n[case testWithStmtBoolExitReturnInStub]\nimport stub\n\n[file stub.pyi]\nfrom typing import Optional\n\nclass C1:\n    def __exit__(self, x, y, z) -> bool: ...\n\nclass C2:\n    def __exit__(self, x, y, z) -> bool: pass\n\nclass C3:\n    def __exit__(self, x, y, z) -> Optional[bool]: pass\n[builtins fixtures/bool.pyi]\n\n[case testWithStmtScopeBasics]\nfrom m import A, B\n\ndef f1() -> None:\n    with A() as x:\n        reveal_type(x)  # N: Revealed type is \"m.A\"\n    with B() as x:\n        reveal_type(x)  # N: Revealed type is \"m.B\"\n\ndef f2() -> None:\n    with A() as x:\n        reveal_type(x)  # N: Revealed type is \"m.A\"\n    y = x  # Use outside with makes the scope function-level\n    with B() as x: \\\n        # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        reveal_type(x)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\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 testWithStmtScopeAndFuncDef]\nfrom m import A, B\n\nwith A() as x:\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\ndef f() -> None:\n    pass  # Don't support function definition in the middle\n\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\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 testWithStmtScopeAndFuncDef2]\nfrom m import A, B\n\ndef f() -> None:\n    pass  # function before with is unsupported\n\nwith A() as x:\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\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 testWithStmtScopeAndFuncDef3]\nfrom m import A, B\n\nwith A() as x:\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\ndef f() -> None:\n    pass  # function after with is unsupported\n\n[file m.pyi]\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 testWithStmtScopeAndFuncDef4]\nfrom m import A, B\n\nwith A() as x:\n    def f() -> None:\n        pass  # Function within with is unsupported\n\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\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 testWithStmtScopeAndImport1]\nfrom m import A, B, x\n\nwith A() as x: \\\n    # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    reveal_type(x)  # N: Revealed type is \"m.B\"\n\nwith B() as x:\n    reveal_type(x)  # N: Revealed type is \"m.B\"\n\n[file m.pyi]\nx: B\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 testWithStmtScopeAndImport2]\nfrom m import A, B\nimport m as x\n\nwith A() as x: \\\n     # E: Incompatible types in assignment (expression has type \"A\", variable has type Module)\n    pass\n\nwith B() as x: \\\n     # E: Incompatible types in assignment (expression has type \"B\", variable has type Module)\n    pass\n\n[file m.pyi]\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[builtins fixtures/module.pyi]\n\n[case testWithStmtScopeAndImportStar]\nfrom m import A, B\nfrom m import *\n\nwith A() as x:\n    pass\n\nwith B() as x: \\\n     # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n\n[file m.pyi]\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 testWithStmtScopeNestedWith1]\nfrom m import A, B\n\nwith A() as x:\n    with B() as x: \\\n        # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        reveal_type(x)  # N: Revealed type is \"m.A\"\n\nwith B() as x:\n    with A() as x: \\\n        # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        reveal_type(x)  # N: Revealed type is \"m.B\"\n\n[file m.pyi]\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 testWithStmtScopeNestedWith2]\nfrom m import A, B\n\nwith A() as x:\n    with A() as y:\n        reveal_type(y)  # N: Revealed type is \"m.A\"\n    with B() as y:\n        reveal_type(y)  # N: Revealed type is \"m.B\"\n\n[file m.pyi]\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 testWithStmtScopeInnerAndOuterScopes]\nfrom m import A, B\n\nx = A()  # Outer scope should have no impact\n\nwith A() as x:\n    pass\n\ndef f() -> None:\n    with A() as x:\n        reveal_type(x)  # N: Revealed type is \"m.A\"\n    with B() as x:\n        reveal_type(x)  # N: Revealed type is \"m.B\"\n\ny = x\n\nwith A() as x:\n    pass\n\n[file m.pyi]\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 testWithStmtScopeMultipleContextManagers]\nfrom m import A, B\n\nwith A() as x, B() as y:\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n    reveal_type(y)  # N: Revealed type is \"m.B\"\nwith B() as x, A() as y:\n    reveal_type(x)  # N: Revealed type is \"m.B\"\n    reveal_type(y)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\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 testWithStmtScopeMultipleAssignment]\nfrom m import A, B\n\nwith A() as (x, y):\n    reveal_type(x)  # N: Revealed type is \"m.A\"\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\nwith B() as [x, y]:\n    reveal_type(x)  # N: Revealed type is \"m.B\"\n    reveal_type(y)  # N: Revealed type is \"builtins.str\"\n\n[file m.pyi]\nfrom typing import Tuple\n\nclass A:\n    def __enter__(self) -> Tuple[A, int]: ...\n    def __exit__(self, x, y, z) -> None: ...\nclass B:\n    def __enter__(self) -> Tuple[B, str]: ...\n    def __exit__(self, x, y, z) -> None: ...\n[builtins fixtures/tuple.pyi]\n\n[case testWithStmtScopeComplexAssignments]\nfrom m import A, B, f\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\nwith B() as f(x).x:\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\nwith B() as f(y)[0]:\n    pass\n\n[file m.pyi]\ndef f(x): ...\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 testWithStmtScopeAndClass]\nfrom m import A, B\n\nwith A() as x:\n    pass\n\nclass C:\n    with A() as y:\n        pass\n    with B() as y:\n        pass\n\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n\n[file m.pyi]\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 testWithStmtScopeInnerScopeReference]\nfrom m import A, B\n\nwith A() as x:\n    def f() -> A:\n        return x\n    f()\n\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n[file m.pyi]\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 testWithStmtScopeAndLambda]\nfrom m import A, B\n\n# This is technically not correct, since the lambda can outlive the with\n# statement, but this behavior seems more intuitive.\n\nwith A() as x:\n    lambda: reveal_type(x)  # N: Revealed type is \"m.A\"\n\nwith B() as x:\n    pass\n[file m.pyi]\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\n-- Chained assignment\n-- ------------------\n\n\n[case testChainedAssignment]\nimport typing\nclass A: pass\nclass B: pass\nx = y = A()\nif int():\n    x = A()\nif int():\n    y = A()\nif int():\n    x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    y = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testChainedAssignment2]\nimport typing\ndef f() -> None:\n    x = 1\n    y = 'x'\n    if int():\n        x = y = 'x' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        x = y = 1   # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testChainedAssignmentWithType]\n# flags: --no-strict-optional\nx = y = None # type: int\nif int():\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    y = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    x = 1\nif int():\n    y = 1\n\n\n-- Star assignment\n-- ---------------\n\n\n[case testAssignListToStarExpr]\nfrom typing import List\nbs: List[A]\ncs: List[B]\nif int():\n    *bs, b = bs\nif int():\n    *bs, c = cs  # E: Incompatible types in assignment (expression has type \"List[B]\", variable has type \"List[A]\")\n    if int():\n        *ns, c = cs\nif int():\n    nc = cs\n\nclass A: pass\nclass B: pass\n[builtins fixtures/list.pyi]\n\n\n-- Type aliases\n-- ------------\n\n\n[case testSimpleTypeAlias]\nimport typing\nfoo = int\ndef f(x: foo) -> None: pass\nf(1)\nf('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testTypeAliasDefinedInAModule]\nimport typing\nimport m\ndef f(x: m.foo) -> None: pass\nf(1)\nf('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[file m.py]\nimport typing\nfoo = int\n\n[case testTypeAliasDefinedInAModule2]\nimport typing\nfrom m import foo\ndef f(x: foo) -> None: pass\nf(1)\nf('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[file m.py]\nimport typing\nfoo = int\n\n\n-- nonlocal and global\n-- -------------------\n\n\n[case testTypeOfGlobalUsed]\nimport typing\nclass A(): pass\nclass B(): pass\ng = A()\ndef f() -> None:\n    global g\n    g = B()  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[case testTypeOfNonlocalUsed]\nimport typing\ndef f() -> None:\n    a = A()\n    def g() -> None:\n        nonlocal a\n        a = B()\n\nclass A(): pass\nclass B(): pass\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testTypeOfOuterMostNonlocalUsed]\nimport typing\ndef f() -> None:\n    a = A()\n    def g() -> None:\n        a = B()\n        def h() -> None:\n            nonlocal a\n            a = A()\n            a = B()\n\nclass A(): pass\nclass B(): pass\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testAugmentedAssignmentIntFloat]\nweight0 = 65.5\nreveal_type(weight0)  # N: Revealed type is \"builtins.float\"\nif int():\n    weight0 = 65\n    reveal_type(weight0)  # N: Revealed type is \"builtins.int\"\n    weight0 *= 'a'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"float\")\n    weight0 *= 0.5\n    reveal_type(weight0)  # N: Revealed type is \"builtins.float\"\n    weight0 *= object()  # E: Unsupported operand types for * (\"float\" and \"object\")\n    reveal_type(weight0) # N: Revealed type is \"builtins.float\"\n\n[builtins fixtures/float.pyi]\n\n[case testAugmentedAssignmentIntFloatMember]\nclass A:\n    def __init__(self) -> None:\n        self.weight0 = 65.5\n        reveal_type(self.weight0)  # N: Revealed type is \"builtins.float\"\n        self.weight0 = 65\n        reveal_type(self.weight0)  # N: Revealed type is \"builtins.int\"\n        self.weight0 *= 'a'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"float\")\n        self.weight0 *= 0.5\n        reveal_type(self.weight0)  # N: Revealed type is \"builtins.float\"\n        self.weight0 *= object()  # E: Unsupported operand types for * (\"float\" and \"object\")\n        reveal_type(self.weight0) # N: Revealed type is \"builtins.float\"\n\n[builtins fixtures/float.pyi]\n\n[case testAugmentedAssignmentIntFloatDict]\nfrom typing import Dict\nd = {'weight0': 65.5}\nreveal_type(d['weight0'])  # N: Revealed type is \"builtins.float\"\nd['weight0'] = 65\nreveal_type(d['weight0'])  # N: Revealed type is \"builtins.float\"\nd['weight0'] *= 'a'  # E: Unsupported operand types for * (\"float\" and \"str\")\nd['weight0'] *= 0.5\nreveal_type(d['weight0'])  # N: Revealed type is \"builtins.float\"\nd['weight0'] *= object()  # E: Unsupported operand types for * (\"float\" and \"object\")\nreveal_type(d['weight0']) # N: Revealed type is \"builtins.float\"\n\n[builtins fixtures/floatdict.pyi]\n\n[case testForwardRefsInForStatementImplicit]\nfrom typing import List, NamedTuple\nlst: List[N]\n\nfor i in lst:\n    reveal_type(i.x)  # N: Revealed type is \"builtins.int\"\n    a: str = i[0] # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nN = NamedTuple('N', [('x', int)])\n[builtins fixtures/list.pyi]\n[out]\n\n[case testForwardRefsInForStatement]\nfrom typing import List, NamedTuple\nlst: List[M]\n\nfor i in lst: # type: N\n    reveal_type(i.x)  # N: Revealed type is \"builtins.int\"\n    a: str = i[0] # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nN = NamedTuple('N', [('x', int)])\nclass M(N): pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testForwardRefsInWithStatementImplicit]\nfrom typing import ContextManager, Any\nfrom mypy_extensions import TypedDict\ncm: ContextManager[N]\n\nwith cm as g:\n    a: int = g['x']\n\nN = TypedDict('N', {'x': int})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n\n[case testForwardRefsInWithStatement]\nfrom typing import ContextManager, Any\nfrom mypy_extensions import TypedDict\ncm: ContextManager[Any]\n\nwith cm as g:  # type: N\n    a: str = g['x']  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nN = TypedDict('N', {'x': int})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n\n[case testGlobalWithoutInitialization]\n# flags: --disable-error-code=annotation-unchecked\nfrom typing import List\n\ndef foo() -> None:\n    global bar\n    # TODO: Confusing error message\n    bar = []  # type: List[str]  # E: Name \"bar\" already defined (possibly by an import)\n    bar  # E: Name \"bar\" is not defined\n\ndef foo2():\n    global bar2\n    bar2 = []  # type: List[str]\n    bar2\n[builtins fixtures/list.pyi]\n\n[case testNoteUncheckedAnnotation]\ndef foo():\n    x: int = \"no\"  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\n    y = \"no\"  # type: int  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\n    z: int  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\n\n[case testGeneratorUnion]\nfrom typing import Generator, Union\n\nclass A: pass\nclass B: pass\n\ndef foo(x: int) -> Union[Generator[A, None, None], Generator[B, None, None]]:\n    yield x  # E: Incompatible types in \"yield\" (actual type \"int\", expected type \"Union[A, B]\")\n\n[case testYieldFromUnionOfGenerators]\nfrom typing import Generator, Union\n\nclass T: pass\n\ndef foo(arg: Union[Generator[int, None, T], Generator[str, None, T]]) -> Generator[Union[int, str], None, T]:\n    return (yield from arg)\n\n[case testYieldFromInvalidUnionReturn]\nfrom typing import Generator, Union\n\nclass A: pass\nclass B: pass\n\ndef foo(arg: Union[A, B]) -> Generator[Union[int, str], None, A]:\n    return (yield from arg) # E: \"yield from\" can't be applied to \"Union[A, B]\"\n\n[case testYieldFromUnionOfGeneratorWithIterableStr]\nfrom typing import Generator, Union, Iterable, Optional\n\ndef foo(arg: Union[Generator[int, None, bytes], Iterable[str]]) -> Generator[Union[int, str], None, Optional[bytes]]:\n    return (yield from arg)\n\ndef bar(arg: Generator[str, None, str]) -> Generator[str, None, str]:\n    return foo(arg)  # E: Incompatible return value type (got \"Generator[Union[int, str], None, Optional[bytes]]\", expected \"Generator[str, None, str]\")\n\ndef launder(arg: Iterable[str]) -> Generator[Union[int, str], None, Optional[bytes]]:\n    return foo(arg)\n\ndef baz(arg: Generator[str, None, str]) -> Generator[Union[int, str], None, Optional[bytes]]:\n    # this is unsound, the Generator return type will actually be str\n    return launder(arg)\n[builtins fixtures/tuple.pyi]\n\n[case testYieldIteratorReturn]\nfrom typing import Iterator\n\ndef get_strings(foo: bool) -> Iterator[str]:\n    if foo:\n        return [\"foo1\", \"foo2\"]  # E: No return value expected\n    else:\n        yield \"bar1\"\n        yield \"bar2\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashOnStarRightHandSide]\nx = *(1, 2, 3)  # E: can't use starred expression here\n[builtins fixtures/tuple.pyi]\n\n\n[case testTypingExtensionsSuggestion]\nfrom typing import _FutureFeatureFixture\n\n# This import is only needed in tests. In real life, mypy will always have typing_extensions in its\n# build due to its pervasive use in typeshed. This assumption may one day prove False, but when\n# that day comes this suggestion will also be less helpful than it is today.\nimport typing_extensions\n[out]\nmain:1: error: Module \"typing\" has no attribute \"_FutureFeatureFixture\"\nmain:1: note: Use `from typing_extensions import _FutureFeatureFixture` instead\nmain:1: note: See https://kotlinisland.github.io/basedmypy/runtime_troubles.html#using-new-additions-to-the-typing-module\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashOnBreakOutsideLoopFunction]\ndef foo():\n    for x in [1, 2]:\n        def inner():\n            break  # E: \"break\" outside loop\n[builtins fixtures/list.pyi]\n\n[case testNoCrashOnBreakOutsideLoopClass]\nclass Outer:\n    for x in [1, 2]:\n        class Inner:\n            break  # E: \"break\" outside loop\n[builtins fixtures/list.pyi]\n\n[case testCallableInstanceOverlapAllowed]\n# flags: --warn-unreachable\nfrom typing import Any, Callable, List\n\nclass CAny:\n    def __call__(self) -> Any: ...\nclass CNone:\n    def __call__(self) -> None: ...\nclass CWrong:\n    def __call__(self, x: int) -> None: ...\n\ndef describe(func: Callable[[], None]) -> str:\n    if isinstance(func, CAny):\n        return \"CAny\"\n    elif isinstance(func, CNone):\n        return \"CNone\"\n    elif isinstance(func, CWrong):\n        return \"CWrong\"  # E: Statement is unreachable\n    else:\n        return \"other\"\n\nclass C(CAny):\n    def __call__(self) -> None: ...\n\ndef f():\n    pass\n\ndescribe(CAny())\ndescribe(C())\ndescribe(CNone())\ndescribe(CWrong())  # E: Argument 1 to \"describe\" has incompatible type \"CWrong\"; expected \"Callable[[], None]\" \\\n                    # N: \"CWrong.__call__\" has type \"Callable[[Arg(int, 'x')], None]\"\ndescribe(f)\n[builtins fixtures/isinstancelist.pyi]\n"
  },
  {
    "path": "test-data/unit/check-super.test",
    "content": "-- Test cases for type checker related to super().\n\n\n-- Supertype member reference\n-- --------------------------\n\n\n[case testAccessingSupertypeMethod]\n\nclass B:\n  def f(self) -> 'B': pass\nclass A(B):\n  def f(self) -> 'A':\n    a: A\n    b: B\n    if int():\n        a = super().f() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = super().g() # E: \"g\" undefined in superclass\n        b = super().f()\n    return a\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testAccessingSuperTypeMethodWithArgs]\nfrom typing import Any\nclass B:\n  def f(self, y: 'A') -> None: pass\nclass A(B):\n  def f(self, y: Any) -> None:\n    a: A\n    b: B\n    super().f(b) # E: Argument 1 to \"f\" of \"B\" has incompatible type \"B\"; expected \"A\"\n    super().f(a)\n    self.f(b)\n    self.f(a)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testAccessingSuperInit]\n# flags: --no-strict-optional\nimport typing\nclass B:\n    def __init__(self, x: A) -> None: pass\nclass A(B):\n  def __init__(self) -> None:\n    super().__init__(B(None)) # E: Argument 1 to \"__init__\" of \"B\" has incompatible type \"B\"; expected \"A\"\n    super().__init__()       # E: Missing positional argument \"x\" in call to \"__init__\" of \"B\"\n    super().__init__(A())\n[out]\n\n[case testAccessingSuperMemberWithDeepHierarchy]\nimport typing\nclass C:\n  def f(self) -> None: pass\nclass B(C): pass\nclass A(B):\n  def f(self) -> None:\n    super().g() # E: \"g\" undefined in superclass\n    super().f()\n[out]\n\n[case testAssignToBaseClassMethod]\nimport typing\nclass A:\n    def f(self) -> None: pass\nclass B(A):\n    def g(self) -> None:\n        super().f = None\n[out]\nmain:6: error: Invalid assignment target\n\n[case testSuperWithMultipleInheritance]\nimport typing\nclass A:\n  def f(self) -> None: pass\nclass B:\n  def g(self, x: int) -> None: pass\nclass C(A, B):\n    def f(self) -> None:\n        super().f()\n        super().g(1)\n        super().f(1) # E: Too many arguments for \"f\" of \"A\"\n        super().g() # E: Missing positional argument \"x\" in call to \"g\" of \"B\"\n        super().not_there() # E: \"not_there\" undefined in superclass\n[out]\n\n[case testSuperWithNew]\nclass A:\n    def __new__(cls, x: int) -> 'A':\n        return object.__new__(cls)\n\nclass B(A):\n    def __new__(cls, x: int, y: str = '') -> 'B':\n        super().__new__(cls, 1)\n        super().__new__(cls, 1, '')  # E: Too many arguments for \"__new__\" of \"A\"\n        return cls(1)\nB('')  # E: Argument 1 to \"B\" has incompatible type \"str\"; expected \"int\"\nB(1)\nB(1, 'x')\n[builtins fixtures/__new__.pyi]\n\nreveal_type(C.a)  # N: Revealed type is \"Any\"\n[out]\n\n[case testSuperWithUnknownBase]\nfrom typing import Any\nB = None  # type: Any\nclass C(B):\n    def __init__(self, arg=0):\n        super(C, self).__init__(arg, arg=arg)\n[out]\n\n[case testSuperSilentInDynamicFunction]\nclass A:\n    pass\n\nclass B(A):\n    def foo(self):\n        super(B, self).foo() # Not an error\n[out]\n\n[case testSuperWithAny]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self, x) -> None:\n        reveal_type(super(x, x).f) # N: Revealed type is \"def ()\"\n        reveal_type(super(C, x).f) # N: Revealed type is \"def ()\"\n        reveal_type(super(C, type(x)).f) # N: Revealed type is \"def (self: __main__.B)\"\n\n[case testSuperInUnannotatedMethod]\nclass C:\n    def h(self):\n        super(C, self).xyz\n\n[case testSuperWithTypeObjects]\nfrom typing import Type\n\nclass A:\n    def f(self) -> object: pass\n\nclass B(A):\n    def f(self) -> int: pass\n\n    @classmethod\n    def g(cls, x) -> None:\n        reveal_type(super(cls, x).f) # N: Revealed type is \"def () -> builtins.object\"\n\n    def h(self, t: Type[B]) -> None:\n        reveal_type(super(t, self).f) # N: Revealed type is \"def () -> builtins.object\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSuperWithTypeTypeAsSecondArgument]\nclass B:\n    def f(self) -> None: pass\n\nclass C(B):\n    def __new__(cls) -> 'C':\n        super(C, cls).f\n        return C()\n\n[case testSuperWithGenericSelf]\nfrom typing import TypeVar\n\nT = TypeVar('T', bound='C')\n\nclass B:\n    def f(self) -> float: pass\n\nclass C(B):\n    def f(self) -> int: pass\n\n    def g(self: T) -> T:\n        reveal_type(super(C, self).f) # N: Revealed type is \"def () -> builtins.float\"\n        return self\n\n[case testSuperWithTypeVarValues1]\nfrom typing import TypeVar\n\nT = TypeVar('T', 'C', 'D')\nS = TypeVar('S', 'B', 'C')\n\nclass B:\n    def f(self) -> None: pass\n\nclass C(B):\n    def f(self) -> None: pass\n\n    def g(self, x: T, y: S) -> None:\n        super(C, x).f\n        super(C, y).f # E: Argument 2 for \"super\" not an instance of argument 1\n\nclass D(C): pass\n\n[case testSuperWithTypeVarValues2]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T', 'C', 'D')\nS = TypeVar('S', 'B', 'C')\n\nclass B:\n    def f(self) -> None: pass\n\nclass C(B, Generic[T, S]):\n    def f(self) -> None: pass\n\n    def g(self, x: T, y: S) -> None:\n        super(C, x).f\n        super(C, y).f # E: Argument 2 for \"super\" not an instance of argument 1\n\nclass D(C): pass\n\n[case testSuperInClassMethod]\nfrom typing import Union\n\nclass A:\n    def f(self, i: int) -> None: pass\n\nclass B(A):\n    def f(self, i: Union[int, str]) -> None: pass\n\n    @classmethod\n    def g(cls, i: int) -> None:\n        super().f(B(), i)\n        super(B, cls).f(cls(), i)\n        super(B, B()).f(i)\n\n        super().f(B(), '') # E: Argument 2 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n        super(B, cls).f(cls(), '') # E: Argument 2 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n        super(B, B()).f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSuperWithUnrelatedTypes]\nfrom typing import Union\n\nclass A:\n    def f(self, s: str) -> None: pass\n\nclass B(A):\n    def f(self, s: Union[int, str]) -> None: pass\n\nclass C:\n    def g(self, b: B) -> None:\n        super(B, b).f('42')\n        super(B, b).f(42) # E: Argument 1 to \"f\" of \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testSuperOutsideClass]\nfrom typing import Union\n\nclass A:\n    def f(self, s: str) -> None: pass\n\nclass B(A):\n    def f(self, s: Union[int, str]) -> None: pass\n\ndef g(b: B) -> None:\n    super(B, b).f('42')\n    super(B, b).f(42) # E: Argument 1 to \"f\" of \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testSuperInInitSubclass]\nclass A:\n    def __init_subclass__(cls) -> None:\n        super().__init_subclass__()\n[builtins fixtures/__init_subclass__.pyi]\n\n[case testSuperClassGetItem]\nfrom typing import TypeVar, Type, Any\n\nT = TypeVar(\"T\", bound=\"B\")\n\nclass A:\n    def __class_getitem__(cls, item) -> None: pass\n\nclass B(A):\n    def __class_getitem__(cls: Type[T], item: Any) -> None:\n        super(B, cls).__class_getitem__(item)\n\n-- Invalid uses of super()\n-- -----------------------\n\n\n[case testSuperOutsideMethodNoCrash]\nclass A:\n    x = 1\nclass B(A): pass\nclass C(B):\n    b = super(B, B).x\n    a = super().whatever  # E: \"super()\" outside of a method is not supported\n\n[case testSuperWithObjectClassAsFirstArgument]\nclass A:\n    def f(self) -> None:\n        super(object, self).f()  # E: Target class has no base class\n\n[case testSuperWithTypeVarAsFirstArgument]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef f(obj: T) -> None:\n    super(obj.__class__, obj).f()  # E: Target class has no base class\n[builtins fixtures/__new__.pyi]\n\n[case testSuperWithSingleArgument]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def __init__(self) -> None:\n        super(C).f() # E: \"super\" with a single argument not supported\n\n[case testSuperWithThreeArguments]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(C, self, 1).f() # E: Too many arguments for \"super\"\n\n[case testSuperWithNonPositionalArguments]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(C, x=self).f() # E: \"super\" only accepts positional arguments\n        super(**{}).f() # E: \"super\" only accepts positional arguments\n\n[case testSuperWithVarArgs]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(*(C, self)).f() # E: Varargs not supported with \"super\"\n\n[case testInvalidSuperArg]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(x, y).f # E: Name \"x\" is not defined # E: Name \"y\" is not defined\n\n[case testTypeErrorInSuperArg]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(1(), self).f # E: \"int\" not callable\n        super(C, ''()).f  # E: \"str\" not callable\n\n[case testFlippedSuperArgs]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(self, C).f # E: Argument 1 for \"super\" must be a type object; got a non-type instance\n\n[case testInvalidFirstSuperArg]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(None, C).f # E: Argument 1 for \"super\" must be a type object; got \"None\"\n\n[case testInvalidSecondArgumentToSuper]\nclass B:\n    def f(self) -> None: pass\nclass C(B):\n    def h(self) -> None:\n        super(C, 1).f # E: Argument 2 for \"super\" not an instance of argument 1\n        super(C, None).f # E: Unsupported argument 2 for \"super\"\n\n[case testSuperInMethodWithNoArguments]\nclass A:\n    def f(self) -> None: pass\n    @staticmethod\n    def st() -> int:\n        return 1\n\nclass B(A):\n    def g() -> None: # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        super().f() # E: \"super()\" requires one or two positional arguments in enclosing function\n    def h(self) -> None:\n        def a() -> None:\n            super().f() # E: \"super()\" requires one or two positional arguments in enclosing function\n    @staticmethod\n    def st() -> int:\n        reveal_type(super(B, B).st())  # N: Revealed type is \"builtins.int\"\n        super().st() # E: \"super()\" requires one or two positional arguments in enclosing function\n        return 2\n[builtins fixtures/staticmethod.pyi]\n\n[case testSuperWithUnsupportedTypeObject]\nfrom typing import Type\n\nclass A:\n    def f(self) -> int: pass\n\nclass B(A):\n    def h(self, t: Type[None]) -> None:\n        super(t, self).f # E: Unsupported argument 1 for \"super\"\n\n[case testSuperSelfTypeInstanceMethod]\nfrom typing import TypeVar, Type\n\nT = TypeVar(\"T\", bound=\"A\")\n\nclass A:\n    def foo(self: T) -> T: ...\n\nclass B(A):\n    def foo(self: T) -> T:\n        reveal_type(super().foo())  # N: Revealed type is \"T`-1\"\n        return super().foo()\n\n[case testSuperSelfTypeClassMethod]\nfrom typing import TypeVar, Type\n\nT = TypeVar(\"T\", bound=\"A\")\n\nclass A:\n    @classmethod\n    def foo(cls: Type[T]) -> T: ...\n\nclass B(A):\n    @classmethod\n    def foo(cls: Type[T]) -> T:\n        reveal_type(super().foo())  # N: Revealed type is \"T`-1\"\n        return super().foo()\n[builtins fixtures/classmethod.pyi]\n\n[case testWrongSuperOutsideMethodNoCrash]\nclass B:\n    x: int\nclass C1(B): ...\nclass C2(B): ...\nsuper(C1, C2).x  # E: Argument 2 for \"super\" not an instance of argument 1\n"
  },
  {
    "path": "test-data/unit/check-tuples.test",
    "content": "-- Normal assignment and subtyping\n-- -------------------------------\n\n\n[case testTupleAssignmentWithTupleTypes]\nfrom typing import Tuple\nt1: Tuple[A]\nt2: Tuple[B]\nt3: Tuple[A, A]\nt4: Tuple[A, B]\nt5: Tuple[B, A]\n\nif int():\n    t1 = t2 # E: Incompatible types in assignment (expression has type \"Tuple[B]\", variable has type \"Tuple[A]\")\nif int():\n    t1 = t3 # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"Tuple[A]\")\nif int():\n    t3 = t1 # E: Incompatible types in assignment (expression has type \"Tuple[A]\", variable has type \"Tuple[A, A]\")\nif int():\n    t3 = t4 # E: Incompatible types in assignment (expression has type \"Tuple[A, B]\", variable has type \"Tuple[A, A]\")\nif int():\n    t3 = t5 # E: Incompatible types in assignment (expression has type \"Tuple[B, A]\", variable has type \"Tuple[A, A]\")\n\n# Ok\nif int():\n    t1 = t1\nif int():\n    t2 = t2\nif int():\n    t3 = t3\nif int():\n    t4 = t4\nif int():\n    t5 = t5\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testTupleSubtyping]\nfrom typing import Tuple\nt1: Tuple[A, A]\nt2: Tuple[A, B]\nt3: Tuple[B, A]\n\nif int():\n    t2 = t1  # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"Tuple[A, B]\")\n    t2 = t3  # E: Incompatible types in assignment (expression has type \"Tuple[B, A]\", variable has type \"Tuple[A, B]\")\n    t3 = t1  # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"Tuple[B, A]\")\n    t3 = t2  # E: Incompatible types in assignment (expression has type \"Tuple[A, B]\", variable has type \"Tuple[B, A]\")\n\n    t1 = t2\n    t1 = t3\n\nclass A: pass\nclass B(A): pass\n[builtins fixtures/tuple.pyi]\n\n[case testTupleCompatibilityWithOtherTypes]\n# flags: --no-strict-optional\nfrom typing import Tuple\nclass A: pass\na, o = A(), object() # type: (A, object)\nt: Tuple[A, A]\n\nif int():\n    a = t # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"A\")\nif int():\n    t = o # E: Incompatible types in assignment (expression has type \"object\", variable has type \"Tuple[A, A]\")\nif int():\n    t = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"Tuple[A, A]\")\n# TODO: callable types + tuples\n\n# Ok\nif int():\n    o = t\nif int():\n    t = None\n\n[builtins fixtures/tuple.pyi]\n\n[case testNestedTupleTypes]\nfrom typing import Tuple\nt1: Tuple[A, Tuple[A, A]]\nt2: Tuple[B, Tuple[B, B]]\n\nif int():\n    t2 = t1 # E: Incompatible types in assignment (expression has type \"Tuple[A, Tuple[A, A]]\", variable has type \"Tuple[B, Tuple[B, B]]\")\nif int():\n    t1 = t2\n\nclass A: pass\nclass B(A): pass\n[builtins fixtures/tuple.pyi]\n\n[case testNestedTupleTypes2]\nfrom typing import Tuple\nt1: Tuple[A, Tuple[A, A]]\nt2: Tuple[B, Tuple[B, B]]\n\nif int():\n    t2 = t1 # E: Incompatible types in assignment (expression has type \"Tuple[A, Tuple[A, A]]\", variable has type \"Tuple[B, Tuple[B, B]]\")\nif int():\n    t1 = t2\n\nclass A: pass\nclass B(A): pass\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingWithTupleType]\nfrom __future__ import annotations\nfrom typing import Any, Tuple\n\ntuple_aa: tuple[A, A]\nTuple_aa: Tuple[A, A]\n\ntuple_obj: tuple[object, ...]\nTuple_obj: Tuple[object, ...]\n\ntuple_obj_one: tuple[object]\nTuple_obj_one: Tuple[object]\n\ntuple_obj_two: tuple[object, object]\nTuple_obj_two: Tuple[object, object]\n\ntuple_any_implicit: tuple\nTuple_any_implicit: Tuple\n\ntuple_any: tuple[Any, ...]\nTuple_any: Tuple[Any, ...]\n\ntuple_any_one: tuple[Any]\nTuple_any_one: Tuple[Any]\n\ntuple_any_two: tuple[Any, Any]\nTuple_any_two: Tuple[Any, Any]\n\ndef takes_tuple_aa(t: tuple[A, A]): ...\n\ntakes_tuple_aa(tuple_aa)\ntakes_tuple_aa(Tuple_aa)\ntakes_tuple_aa(tuple_obj)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[object, ...]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(Tuple_obj)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[object, ...]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(tuple_obj_one)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[object]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(Tuple_obj_one)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[object]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(tuple_obj_two)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[object, object]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(Tuple_obj_two)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[object, object]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(tuple_any_implicit)\ntakes_tuple_aa(Tuple_any_implicit)\ntakes_tuple_aa(tuple_any)\ntakes_tuple_aa(Tuple_any)\ntakes_tuple_aa(tuple_any_one)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[Any]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(Tuple_any_one)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"Tuple[Any]\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(tuple_any_two)\ntakes_tuple_aa(Tuple_any_two)\n\ndef takes_tuple_any_implicit(t: tuple): ...\n\ntakes_tuple_any_implicit(tuple_aa)\ntakes_tuple_any_implicit(Tuple_aa)\ntakes_tuple_any_implicit(tuple_obj)\ntakes_tuple_any_implicit(Tuple_obj)\ntakes_tuple_any_implicit(tuple_obj_one)\ntakes_tuple_any_implicit(Tuple_obj_one)\ntakes_tuple_any_implicit(tuple_obj_two)\ntakes_tuple_any_implicit(Tuple_obj_two)\ntakes_tuple_any_implicit(tuple_any_implicit)\ntakes_tuple_any_implicit(Tuple_any_implicit)\ntakes_tuple_any_implicit(tuple_any)\ntakes_tuple_any_implicit(Tuple_any)\ntakes_tuple_any_implicit(tuple_any_one)\ntakes_tuple_any_implicit(Tuple_any_one)\ntakes_tuple_any_implicit(tuple_any_two)\ntakes_tuple_any_implicit(Tuple_any_two)\n\ndef takes_tuple_any_one(t: tuple[Any]): ...\n\ntakes_tuple_any_one(tuple_aa)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[A, A]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(Tuple_aa)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[A, A]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(tuple_obj)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[object, ...]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(Tuple_obj)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[object, ...]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(tuple_obj_one)\ntakes_tuple_any_one(Tuple_obj_one)\ntakes_tuple_any_one(tuple_obj_two)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[object, object]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(Tuple_obj_two)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[object, object]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(tuple_any_implicit)\ntakes_tuple_any_one(Tuple_any_implicit)\ntakes_tuple_any_one(tuple_any)\ntakes_tuple_any_one(Tuple_any)\ntakes_tuple_any_one(tuple_any_one)\ntakes_tuple_any_one(Tuple_any_one)\ntakes_tuple_any_one(tuple_any_two)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[Any, Any]\"; expected \"Tuple[Any]\"\ntakes_tuple_any_one(Tuple_any_two)  # E: Argument 1 to \"takes_tuple_any_one\" has incompatible type \"Tuple[Any, Any]\"; expected \"Tuple[Any]\"\n\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingWithTupleTypeSubclass]\nfrom __future__ import annotations\nfrom typing import Any, Tuple\n\nclass A: ...\n\ninst_tuple_aa: Tuple[A, A]\n\nclass tuple_aa_subclass(Tuple[A, A]): ...\ninst_tuple_aa_subclass: tuple_aa_subclass\n\nclass tuple_any_subclass(Tuple[Any, ...]): ...\ninst_tuple_any_subclass: tuple_any_subclass\n\nclass tuple_any_one_subclass(Tuple[Any]): ...\ninst_tuple_any_one_subclass: tuple_any_one_subclass\n\nclass tuple_any_two_subclass(Tuple[Any, Any]): ...\ninst_tuple_any_two_subclass: tuple_any_two_subclass\n\nclass tuple_obj_subclass(Tuple[object, ...]): ...\ninst_tuple_obj_subclass: tuple_obj_subclass\n\nclass tuple_obj_one_subclass(Tuple[object]): ...\ninst_tuple_obj_one_subclass: tuple_obj_one_subclass\n\nclass tuple_obj_two_subclass(Tuple[object, object]): ...\ninst_tuple_obj_two_subclass: tuple_obj_two_subclass\n\ndef takes_tuple_aa(t: Tuple[A, A]): ...\n\ntakes_tuple_aa(inst_tuple_aa)\ntakes_tuple_aa(inst_tuple_aa_subclass)\ntakes_tuple_aa(inst_tuple_any_subclass)\ntakes_tuple_aa(inst_tuple_any_one_subclass)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"tuple_any_one_subclass\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(inst_tuple_any_two_subclass)\ntakes_tuple_aa(inst_tuple_obj_subclass)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"tuple_obj_subclass\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(inst_tuple_obj_one_subclass)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"tuple_obj_one_subclass\"; expected \"Tuple[A, A]\"\ntakes_tuple_aa(inst_tuple_obj_two_subclass)  # E: Argument 1 to \"takes_tuple_aa\" has incompatible type \"tuple_obj_two_subclass\"; expected \"Tuple[A, A]\"\n\ndef takes_tuple_aa_subclass(t: tuple_aa_subclass): ...\n\ntakes_tuple_aa_subclass(inst_tuple_aa)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"Tuple[A, A]\"; expected \"tuple_aa_subclass\"\ntakes_tuple_aa_subclass(inst_tuple_aa_subclass)\ntakes_tuple_aa_subclass(inst_tuple_any_subclass)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"tuple_any_subclass\"; expected \"tuple_aa_subclass\"\ntakes_tuple_aa_subclass(inst_tuple_any_one_subclass)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"tuple_any_one_subclass\"; expected \"tuple_aa_subclass\"\ntakes_tuple_aa_subclass(inst_tuple_any_two_subclass)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"tuple_any_two_subclass\"; expected \"tuple_aa_subclass\"\ntakes_tuple_aa_subclass(inst_tuple_obj_subclass)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"tuple_obj_subclass\"; expected \"tuple_aa_subclass\"\ntakes_tuple_aa_subclass(inst_tuple_obj_one_subclass)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"tuple_obj_one_subclass\"; expected \"tuple_aa_subclass\"\ntakes_tuple_aa_subclass(inst_tuple_obj_two_subclass)  # E: Argument 1 to \"takes_tuple_aa_subclass\" has incompatible type \"tuple_obj_two_subclass\"; expected \"tuple_aa_subclass\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTupleInitializationWithNone]\n# flags: --no-strict-optional\nfrom typing import Tuple\nt = None # type: Tuple[A, A]\nt = None\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n\n-- Tuple expressions\n-- -----------------\n\n\n[case testTupleExpressions]\n# flags: --no-strict-optional\nfrom typing import Tuple\n\nclass A: pass\nclass B: pass\nclass C(B): pass\n\nt1: tuple\nt2: Tuple[A]\nt3: Tuple[A, B]\n\na, b, c = A(), B(), C() # type: (A, B, C)\n\nif int():\n    t2 = ()        # E: Incompatible types in assignment (expression has type \"Tuple[()]\", variable has type \"Tuple[A]\")\nif int():\n    t2 = (a, a)    # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"Tuple[A]\")\nif int():\n    t3 = (a, a)    # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"Tuple[A, B]\")\nif int():\n    t3 = (b, b)    # E: Incompatible types in assignment (expression has type \"Tuple[B, B]\", variable has type \"Tuple[A, B]\")\nif int():\n    t3 = (a, b, a) # E: Incompatible types in assignment (expression has type \"Tuple[A, B, A]\", variable has type \"Tuple[A, B]\")\n\nt1 = ()\nt1 = (a,)\nt2 = (a,)\nt3 = (a, b)\nt3 = (a, c)\nt3 = (None, None)\n\n[builtins fixtures/tuple.pyi]\n\n[case testVoidValueInTuple]\nimport typing\ndef f() -> None: pass\n\n(None, f()) # E: \"f\" does not return a value (it only ever returns None)\n(f(), None) # E: \"f\" does not return a value (it only ever returns None)\n[builtins fixtures/tuple.pyi]\n\n\n-- Indexing\n-- --------\n\n\n[case testIndexingTuples]\nfrom typing import Tuple\nt1: Tuple[A, B]\nt2: Tuple[A]\nt3: Tuple[A, B, C, D, E]\na: A\nb: B\nx: Tuple[A, B, C]\ny: Tuple[A, C, E]\nn = 0\n\nif int():\n    a = t1[1] # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = t1[0] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nt1[2]     # E: Tuple index out of range\nt1[3]     # E: Tuple index out of range\nt2[1]     # E: Tuple index out of range\nreveal_type(t1[n])     # N: Revealed type is \"Union[__main__.A, __main__.B]\"\nreveal_type(t3[n:])    # N: Revealed type is \"builtins.tuple[Union[__main__.A, __main__.B, __main__.C, __main__.D, __main__.E], ...]\"\nif int():\n    b = t1[(0)] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a = t1[0]\nif int():\n    b = t1[1]\nif int():\n    b = t1[-1]\nif int():\n    a = t1[(0)]\nif int():\n    b = t1[+1]\nif int():\n    x = t3[0:3] # type (A, B, C)\nif int():\n    y = t3[0:+5:2] # type (A, C, E)\nif int():\n    x = t3[:-2] # type (A, B, C)\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nclass E: pass\n[builtins fixtures/tuple.pyi]\n\n[case testIndexingTuplesWithNegativeIntegers]\nfrom typing import Tuple\nt1: Tuple[A, B]\nt2: Tuple[A]\na: A\nb: B\n\nif int():\n    a = t1[-1] # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = t1[-2] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nt1[-3]     # E: Tuple index out of range\nt1[-4]     # E: Tuple index out of range\nif int():\n    b = t2[(-1)] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a = t1[-2]\nif int():\n    b = t1[-1]\nif int():\n    a = t2[(-1)]\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testAssigningToTupleItems]\nfrom typing import Tuple\n\nclass A: pass\nclass B: pass\n\nt: Tuple[A, B]\nn = 0\n\nt[0] = A() # E: Unsupported target for indexed assignment (\"Tuple[A, B]\")\nt[2] = A() # E: Unsupported target for indexed assignment (\"Tuple[A, B]\")\nt[n] = A() # E: Unsupported target for indexed assignment (\"Tuple[A, B]\")\n[builtins fixtures/tuple.pyi]\n\n\n-- Multiple assignment\n-- -------------------\n\n\n[case testMultipleAssignmentWithTuples]\n# flags: --no-strict-optional\nfrom typing import Tuple\n\nclass A: pass\nclass B: pass\nt1: Tuple[A, B]\nt2: Tuple[A, B, A]\na, b = A(), B() # type: (A, B)\n(a1, b1) = A(), B() # type: Tuple[A, B]\n\nreveal_type(a1)  # N: Revealed type is \"__main__.A\"\nreveal_type(b1)  # N: Revealed type is \"__main__.B\"\n\nif int():\n    a, a = t1 # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b, b = t1 # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a, b, b = t2 # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a, b = t1\nif int():\n    a, b, a1 = t2\n\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithSquareBracketTuples]\n# flags: --no-strict-optional\nfrom typing import Tuple\n\ndef avoid_confusing_test_parser() -> None:\n    t1: Tuple[A, B]\n    t2: Tuple[A, B, A]\n    [a, b] = A(), B() # type: (A, B)\n    [a1, b1] = A(), B() # type: Tuple[A, B]\n\n    reveal_type(a)  # N: Revealed type is \"__main__.A\"\n    reveal_type(b)  # N: Revealed type is \"__main__.B\"\n    reveal_type(a1)  # N: Revealed type is \"__main__.A\"\n    reveal_type(b1)  # N: Revealed type is \"__main__.B\"\n\n    if int():\n        [a, a] = t1 # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        [b, b] = t1 # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        [a, b, b] = t2 # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n        [a, b] = t1\n        [a, b, a1] = t2\n\n        [a2, b2] = t1\n        reveal_type(a2)  # N: Revealed type is \"__main__.A\"\n        reveal_type(b2)  # N: Revealed type is \"__main__.B\"\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithInvalidNumberOfValues]\nfrom typing import Tuple\nt1: Tuple[A, A, A]\na: A\n\na, a = t1       # E: Too many values to unpack (2 expected, 3 provided)\na, a, a, a = t1 # E: Need more than 3 values to unpack (4 expected)\n\na, a, a = t1\n\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithTupleExpressionRvalue]\na: A\nb: B\n\nif int():\n    a, b = a, a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a, b = b, a \\\n      # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\") \\\n      # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a, b = a, b\nif int():\n    a, a = a, a\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingInMultipleAssignment]\na: A\nb: B\n\nif int():\n    b, b = a, b # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b, b = b, a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a, b = b, b\nif int():\n    b, a = b, b\n\nclass A: pass\nclass B(A): pass\n[builtins fixtures/tuple.pyi]\n\n[case testInitializationWithMultipleValues]\n# flags: --no-strict-optional\na: A\nb: B\n\na1, b1 = a, a # type: (A, B)  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\na2, b2 = b, b # type: (A, B)  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\na3, b3 = a # type: (A, B)     # E: \"A\" object is not iterable\na4, b4 = None # type: (A, B)  # E: \"None\" object is not iterable\na5, b5 = a, b, a # type: (A, B)  # E: Too many values to unpack (2 expected, 3 provided)\n\nax, bx = a, b # type: (A, B)\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithNonTupleRvalue]\na: A\nb: B\ndef f(): pass\n\na, b = None # E: \"None\" object is not iterable\na, b = a   # E: \"A\" object is not iterable\na, b = f   # E: \"Callable[[], Any]\" object is not iterable\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithIndexedLvalues]\na: A\nb: B\naa: AA\nbb: BB\n\na[a], b[b] = a, bb   # E: Incompatible types in assignment (expression has type \"A\", target has type \"AA\")\na[a], b[b] = aa, b   # E: Incompatible types in assignment (expression has type \"B\", target has type \"BB\")\na[aa], b[b] = aa, bb # E: Invalid index type \"AA\" for \"A\"; expected type \"A\"\na[a], b[bb] = aa, bb # E: Invalid index type \"BB\" for \"B\"; expected type \"B\"\na[a], b[b] = aa, bb\n\nclass A:\n    def __setitem__(self, x: 'A', y: 'AA') -> None: pass\nclass B:\n    def __setitem__(self, x: 'B', y: 'BB') -> None: pass\n\nclass AA: pass\nclass BB: pass\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleDeclarationWithParentheses]\n# flags: --no-strict-optional\n(a, b) = (None, None) # type: int, str\nif int():\n    a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    b = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    a = 1\n    b = ''\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithExtraParentheses]\na: A\nb: B\n\nif int():\n    (a, b) = (a, a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    (a, b) = (b, b) # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    ((a), (b)) = ((a), (a))  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    ((a), (b)) = ((b), (b))  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    [a, b] = a, a  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    [a, b] = b, b  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\nif int():\n    (a, b) = (a, b)\nif int():\n    ((a), (b)) = ((a), (b))\nif int():\n    [a, b] = a, b\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentUsingSingleTupleType]\n# flags: --no-strict-optional\nfrom typing import Tuple\na, b = None, None  # type: Tuple[int, str]\nif int():\n    a = 1\nif int():\n    b = ''\nif int():\n    a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    b = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleAssignmentWithMixedVariables]\na = b, c = 1, 1\nx, y = p, q = 1, 1\nu, v, w = r, s = 1, 1 # E: Need more than 2 values to unpack (3 expected)\nd, e = f, g, h = 1, 1 # E: Need more than 2 values to unpack (3 expected)\n[builtins fixtures/tuple.pyi]\n\n\n-- Assignment to starred expressions\n-- ---------------------------------\n\n\n[case testAssignmentToStarMissingAnnotation]\nfrom typing import List\nt = 1, 2\na, b, *c = 1, 2  # E: Need type annotation for \"c\" (hint: \"c: List[<type>] = ...\")\naa, bb, *cc = t  # E: Need type annotation for \"cc\" (hint: \"cc: List[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testAssignmentToStarAnnotation]\n# flags: --no-strict-optional\nfrom typing import List\nli, lo = [], [] # type: List[int], List[object]\na, b, *c = 1, 2  # type: int, int, List[int]\nif int():\n    c = lo  # E: Incompatible types in assignment (expression has type \"List[object]\", variable has type \"List[int]\")\nif int():\n    c = li\n[builtins fixtures/list.pyi]\n\n[case testAssignmentToStarCount1]\nfrom typing import List\nca: List[int]\nc = [1]\nif int():\n    a, b, *c = 1,  # E: Need more than 1 value to unpack (2 expected)\nif int():\n    a, b, *c = 1, 2\nif int():\n    a, b, *c = 1, 2, 3\nif int():\n    a, b, *c = 1, 2, 3, 4\n[builtins fixtures/list.pyi]\n\n[case testAssignmentToStarCount2]\nfrom typing import List\nca: List[int]\nt1 = 1,\nt2 = 1, 2\nt3 = 1, 2, 3\nt4 = 1, 2, 3, 4\nc = [1]\nif int():\n    a, b, *c = t1  # E: Need more than 1 value to unpack (2 expected)\nif int():\n    a, b, *c = t2\nif int():\n    a, b, *c = t3\nif int():\n    a, b, *c = t4\n[builtins fixtures/list.pyi]\n\n[case testAssignmentToStarFromAny]\nfrom typing import Any, cast\nclass C: pass\n\na, c = cast(Any, 1), C()\np, *q = a\nc = a\nc = q\n[case testAssignmentToComplexStar]\nfrom typing import List\nli: List[int]\nif int():\n    a, *(li) = 1,\na, *(b, c) = 1, 2  # E: Need more than 1 value to unpack (2 expected)\nif int():\n    a, *(b, c) = 1, 2, 3\nif int():\n    a, *(b, c) = 1, 2, 3, 4  # E: Too many values to unpack (2 expected, 3 provided)\n[builtins fixtures/list.pyi]\n\n[case testAssignmentToStarFromTupleType]\nfrom typing import List, Tuple\nli: List[int]\nla: List[A]\nta: Tuple[A, A, A]\nif int():\n    a, *la = ta\nif int():\n    a, *li = ta  # E: List item 0 has incompatible type \"A\"; expected \"int\" \\\n                 # E: List item 1 has incompatible type \"A\"; expected \"int\"\nif int():\n    a, *na = ta\n    if int():\n        na = la\n        na = a  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"List[A]\")\n\nclass A: pass\n[builtins fixtures/list.pyi]\n\n[case testAssignmentToStarFromTupleInference]\nfrom typing import List\nclass A: pass\nli: List[int]\nla: List[A]\na, *l = A(), A()\nif int():\n    l = li  # E: Incompatible types in assignment (expression has type \"List[int]\", variable has type \"List[A]\")\nif int():\n    l = la\n[builtins fixtures/list.pyi]\n[out]\n\n[case testAssignmentToStarFromListInference]\nfrom typing import List\n\nclass A: pass\n\nli: List[int]\nla: List[A]\na, *l = [A(), A()]\nif int():\n    l = li  # E: Incompatible types in assignment (expression has type \"List[int]\", variable has type \"List[A]\")\nif int():\n    l = la\n[builtins fixtures/list.pyi]\n[out]\n\n[case testAssignmentToStarFromTupleTypeInference]\nfrom typing import List, Tuple\nli: List[int]\nla: List[A]\nta: Tuple[A, A, A]\na, *l = ta\nif int():\n    l = li  # E: Incompatible types in assignment (expression has type \"List[int]\", variable has type \"List[A]\")\nif int():\n    l = la\n\nclass A: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testAssignmentToStarFromListTypeInference]\nfrom typing import List\nli: List[int]\nla: List[A]\na, *l = la\nif int():\n    l = li  # E: Incompatible types in assignment (expression has type \"List[int]\", variable has type \"List[A]\")\nif int():\n    l = la\n\nclass A: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testAssignmentToStarFromIterable]\nfrom typing import List, Tuple, Iterable\n\nclass CustomIterable(Iterable[int]): pass\n\na: List[int]\nb: Tuple[int, ...]\nc: Tuple[int, int, int]\nd: Iterable[int]\ne: CustomIterable\n\na1, *a2 = a\nb1, *b2 = b\nc1, *c2 = c\nd1, *d2 = d\ne1, *e2 = e\n\nreveal_type(a2)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(b2)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(c2)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(d2)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(e2)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n-- Nested tuple assignment\n-- ----------------------------\n\n\n[case testNestedTupleAssignment1]\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/tuple.pyi]\n\n[case testNestedTupleAssignment2]\na1: A\na2: A\nb1: B\nb2: B\nc1: C\nc2: C\nt = a1, b1\n\nif int():\n    a2, b2 = t\nif int():\n    (a2, b2), c2 = t, c1\nif int():\n    (a2, c2), c2 = t, c1  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\nif int():\n    t, c2 = (a2, b2), c2\nif int():\n    t, c2 = (a2, a2), c2  # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"Tuple[A, B]\")\nif int():\n    t = a1, a1, a1  # E: Incompatible types in assignment (expression has type \"Tuple[A, A, A]\", variable has type \"Tuple[A, B]\")\nif int():\n    t = a1  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"Tuple[A, B]\")\nif int():\n    a2, a2, a2 = t  # E: Need more than 2 values to unpack (3 expected)\nif int():\n    a2, = t  # E: Too many values to unpack (1 expected, 2 provided)\nif int():\n    a2 = t  # E: Incompatible types in assignment (expression has type \"Tuple[A, B]\", variable has type \"A\")\n\nclass A: pass\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n\n\n-- Error messages\n-- --------------\n\n\n[case testTupleErrorMessages]\nclass A:\n    def __add__(self, x: 'A') -> 'A': pass\ndef f(x: 'A') -> None: pass\n\na: A\n\n(a, a) + a  # E: Unsupported operand types for + (\"Tuple[A, A]\" and \"A\")\na + (a, a)  # E: Unsupported operand types for + (\"A\" and \"Tuple[A, A]\")\nf((a, a))   # E: Argument 1 to \"f\" has incompatible type \"Tuple[A, A]\"; expected \"A\"\n(a, a).foo  # E: \"Tuple[A, A]\" has no attribute \"foo\"\n[builtins fixtures/tuple.pyi]\n\n[case testLargeTuplesInErrorMessages]\n\na: LongTypeName\na + (a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a) # Fail\n\nclass LongTypeName:\n    def __add__(self, x: 'LongTypeName') -> 'LongTypeName': pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:3: error: Unsupported operand types for + (\"LongTypeName\" and \"Tuple[LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName, LongTypeName]\")\n\n\n-- Tuple methods\n-- -------------\n\n\n[case testTupleMethods]\nfrom typing import Tuple\nt: Tuple[int, str]\ni = 0\ns = ''\nb = bool()\n\nif int():\n    s = t.__len__()  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    i = t.__str__()  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    i = s in t       # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"int\")\nt.foo            # E: \"Tuple[int, str]\" has no attribute \"foo\"\n\nif int():\n    i = t.__len__()\nif int():\n    s = t.__str__()\nif int():\n    b = s in t\n\n[file builtins.py]\nfrom typing import TypeVar, Generic\n_T = TypeVar('_T')\nclass object:\n    def __init__(self) -> None: pass\nclass tuple(Generic[_T]):\n    def __len__(self) -> int: pass\n    def __str__(self) -> str: pass\n    def __contains__(self, o: object) -> bool: pass\nclass int: pass\nclass str: pass\nclass bool: pass\nclass type: pass\nclass function: pass\nclass dict: pass\n\n\n-- For loop over tuple\n-- -------------------\n\n\n[case testForLoopOverTuple]\nimport typing\nt = 1, 2\nfor x in t:\n    x = 1\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/for.pyi]\n\n[case testForLoopOverEmptyTuple]\nimport typing\nt = ()\nfor x in t: pass  # E: Need type annotation for \"x\"\n[builtins fixtures/for.pyi]\n\n[case testForLoopOverNoneValuedTuple]\nimport typing\nfor x in None, None: pass\n[builtins fixtures/for.pyi]\n\n[case testForLoopOverTupleAndSubtyping]\nimport typing\nclass A: pass\nclass B(A): pass\nfor x in B(), A():\n    x = A()\n    x = B()\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"A\")\n[builtins fixtures/for.pyi]\n\n[case testTupleIterable]\nfrom typing import Iterable, Optional, TypeVar\n\nT = TypeVar(\"T\")\n\ndef sum(iterable: Iterable[T], start: Optional[T] = None) -> T: pass\n\ny = 'a'\nx = sum((1,2))\nif int():\n    y = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/tuple.pyi]\n\n\n-- Tuple as a base type\n-- --------------------\n\n\n[case testTupleBaseClass]\nimport m\n[file m.pyi]\nfrom typing import Tuple\nclass A(Tuple[int, str]):\n    def f(self, x: int) -> None:\n        a, b = 1, ''\n        if int():\n            a, b = self\n            b, a = self  # Error\n        self.f('')   # Error\n[builtins fixtures/tuple.pyi]\n[out]\ntmp/m.pyi:7: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\ntmp/m.pyi:7: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/m.pyi:8: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testValidTupleBaseClass2]\nfrom typing import Tuple\nclass A(Tuple[int, str]): pass\n\nx, y = A()\nreveal_type(x) # N: Revealed type is \"builtins.int\"\nreveal_type(y) # N: Revealed type is \"builtins.str\"\n\nx1 = A()[0] # type: int\nx2 = A()[1] # type: int # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nA()[2] # E: Tuple index out of range\n\nclass B(Tuple[int, ...]): pass\n\nz1 = B()[0] # type: int\nz2 = B()[1] # type: str # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nB()[100]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testValidTupleBaseClass]\nfrom typing import Tuple\nclass A(tuple): pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleBaseClass2]\nimport m\n[file m.pyi]\nfrom typing import Tuple\na: A\nclass A(Tuple[int, str]): pass\nx, y = a\nx() # E: \"int\" not callable\ny() # E: \"str\" not callable\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testGenericClassWithTupleBaseClass]\nfrom typing import TypeVar, Generic, Tuple\nT = TypeVar('T')\nclass Test(Generic[T], Tuple[T]): pass\nx = Test() # type: Test[int]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.Test[builtins.int]]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n-- Variable-length tuples (Tuple[t, ...] with literal '...')\n-- ---------------------------------------------------------\n\n\n[case testIndexingVariableLengthTuple]\nfrom typing import Tuple\nx: Tuple[str, ...]\nn = 5\nx[n]() # E: \"str\" not callable\nx[3]() # E: \"str\" not callable\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingVariableLengthTuple]\nfrom typing import Tuple\nclass A: pass\nclass B(A): pass\ndef fa(t: Tuple[A, ...]) -> None: pass\ndef fb(t: Tuple[B, ...]) -> None: pass\nta: Tuple[A, ...]\ntb: Tuple[B, ...]\nfa(ta)\nfa(tb)\nfb(tb)\nfb(ta) # E: Argument 1 to \"fb\" has incompatible type \"Tuple[A, ...]\"; expected \"Tuple[B, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingFixedAndVariableLengthTuples]\nfrom typing import Tuple\nclass A: pass\nclass B(A): pass\ndef fa(t: Tuple[A, ...]) -> None: pass\ndef fb(t: Tuple[B, ...]) -> None: pass\naa = (A(), A())\nab = (A(), B())\nbb = (B(), B())\nfa(aa)\nfa(ab)\nfa(bb)\nfb(bb)\nfb(ab) # E: Argument 1 to \"fb\" has incompatible type \"Tuple[A, B]\"; expected \"Tuple[B, ...]\"\nfb(aa) # E: Argument 1 to \"fb\" has incompatible type \"Tuple[A, A]\"; expected \"Tuple[B, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingTupleIsContainer]\nfrom typing import Container\na: Container[str]\na = ()\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testSubtypingTupleIsSized]\nfrom typing import Sized\na: Sized\na = ()\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr1]\n\na = (1, 2)\nb = (*a, '')\nreveal_type(b)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr2]\na = [1]\nb = (0, *a)\nreveal_type(b)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr2Precise]\n# flags: --enable-incomplete-feature=PreciseTupleTypes\na = [1]\nb = (0, *a)\nreveal_type(b)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr3]\na = ['']\nb = (0, *a)\nreveal_type(b)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\nc = (*a, '')\nreveal_type(c)  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr3Precise]\n# flags: --enable-incomplete-feature=PreciseTupleTypes\na = ['']\nb = (0, *a)\nreveal_type(b)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]]]\"\nc = (*a, '')\nreveal_type(c)  # N: Revealed type is \"Tuple[Unpack[builtins.tuple[builtins.str, ...]], builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr4]\na = (1, 1, 'x', 'x')\nb = (1, 'x')\na = (0, *b, '')\n[builtins fixtures/tuple.pyi]\n\n[case testUnpackSyntaxError]\n*foo  # E: can't use starred expression here\n[builtins fixtures/tuple.pyi]\n\n[case testUnpackBases]\nclass A: ...\nclass B: ...\nbases = (A, B)\nclass C(*bases): ...  # E: Invalid base class\n[builtins fixtures/tuple.pyi]\n\n[case testTupleMeetTupleAny]\nfrom typing import Union, Tuple\nclass A: pass\nclass B: pass\n\ndef f(x: Union[B, Tuple[A, A]]) -> None:\n    if isinstance(x, tuple):\n        reveal_type(x) # N: Revealed type is \"Tuple[__main__.A, __main__.A]\"\n    else:\n        reveal_type(x) # N: Revealed type is \"__main__.B\"\n\ndef g(x: Union[str, Tuple[str, str]]) -> None:\n    if isinstance(x, tuple):\n        reveal_type(x) # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\n    else:\n        reveal_type(x) # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleMeetTupleAnyComplex]\nfrom typing import Tuple, Union\n\nPair = Tuple[int, int]\nVariant = Union[int, Pair]\ndef tuplify(v: Variant) -> None:\n    reveal_type(v) # N: Revealed type is \"Union[builtins.int, Tuple[builtins.int, builtins.int]]\"\n    if not isinstance(v, tuple):\n        reveal_type(v) # N: Revealed type is \"builtins.int\"\n        v = (v, v)\n        reveal_type(v) # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\n    reveal_type(v) # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\n    reveal_type(v[0]) # N: Revealed type is \"builtins.int\"\n\nPair2 = Tuple[int, str]\nVariant2 = Union[int, Pair2]\ndef tuplify2(v: Variant2) -> None:\n    if isinstance(v, tuple):\n        reveal_type(v) # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n    else:\n        reveal_type(v) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleMeetTupleAnyAfter]\nfrom typing import Tuple, Union\n\ndef good(blah: Union[Tuple[int, int], int]) -> None:\n    reveal_type(blah) # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], builtins.int]\"\n    if isinstance(blah, tuple):\n        reveal_type(blah) # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\n    reveal_type(blah) # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], builtins.int]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleMeetTupleVariable]\nfrom typing import Tuple, TypeVar, Generic, Union\nT = TypeVar('T')\n\nclass A: pass\nclass B1(A): pass\nclass B2(A): pass\nclass C: pass\n\nx: Tuple[A, ...]\ny: Tuple[Union[B1, C], Union[B2, C]]\n\ndef g(x: T) -> Tuple[T, T]:\n    return (x, x)\n\nz = 1\nx, y = g(z) # E: Argument 1 to \"g\" has incompatible type \"int\"; expected \"Tuple[B1, B2]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFixedTupleJoinVarTuple]\nfrom typing import Tuple, TypeVar\n\nclass A: pass\nclass B(A): pass\n\nfixtup: Tuple[B, B]\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nvartup_b: Tuple[B, ...]\nreveal_type(join(fixtup, vartup_b))  # N: Revealed type is \"builtins.tuple[__main__.B, ...]\"\nreveal_type(join(vartup_b, fixtup))  # N: Revealed type is \"builtins.tuple[__main__.B, ...]\"\n\nvartup_a: Tuple[A, ...]\nreveal_type(join(fixtup, vartup_a))  # N: Revealed type is \"builtins.tuple[__main__.A, ...]\"\nreveal_type(join(vartup_a, fixtup))  # N: Revealed type is \"builtins.tuple[__main__.A, ...]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFixedTupleJoinList]\nfrom typing import Tuple, List, TypeVar\n\nclass A: pass\nclass B(A): pass\n\nfixtup: Tuple[B, B]\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nlst_b: List[B]\nreveal_type(join(fixtup, lst_b))  # N: Revealed type is \"typing.Sequence[__main__.B]\"\nreveal_type(join(lst_b, fixtup))  # N: Revealed type is \"typing.Sequence[__main__.B]\"\n\nlst_a: List[A]\nreveal_type(join(fixtup, lst_a))  # N: Revealed type is \"typing.Sequence[__main__.A]\"\nreveal_type(join(lst_a, fixtup))  # N: Revealed type is \"typing.Sequence[__main__.A]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testEmptyTupleJoin]\nfrom typing import Tuple, List, TypeVar\n\nclass A: pass\n\nempty = ()\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nfixtup: Tuple[A]\nreveal_type(join(fixtup, empty))  # N: Revealed type is \"builtins.tuple[__main__.A, ...]\"\nreveal_type(join(empty, fixtup))  # N: Revealed type is \"builtins.tuple[__main__.A, ...]\"\n\nvartup: Tuple[A, ...]\nreveal_type(join(vartup, empty))  # N: Revealed type is \"builtins.tuple[__main__.A, ...]\"\nreveal_type(join(empty, vartup))  # N: Revealed type is \"builtins.tuple[__main__.A, ...]\"\n\nlst: List[A]\nreveal_type(join(empty, lst))  # N: Revealed type is \"typing.Sequence[__main__.A]\"\nreveal_type(join(lst, empty))  # N: Revealed type is \"typing.Sequence[__main__.A]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleSubclassJoin]\nfrom typing import Tuple, NamedTuple, TypeVar\n\nclass NTup(NamedTuple):\n    a: bool\n    b: bool\n\nclass SubTuple(Tuple[bool]): ...\nclass SubVarTuple(Tuple[int, ...]): ...\n\nntup: NTup\nsubtup: SubTuple\nvartup: SubVarTuple\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nreveal_type(join(ntup, vartup))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(join(subtup, vartup))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleJoinIrregular]\nfrom typing import Tuple, TypeVar\n\ntup1: Tuple[bool, int]\ntup2: Tuple[bool]\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nreveal_type(join(tup1, tup2))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(join(tup2, tup1))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nreveal_type(join(tup1, ()))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(join((), tup1))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nreveal_type(join(tup2, ()))  # N: Revealed type is \"builtins.tuple[builtins.bool, ...]\"\nreveal_type(join((), tup2))  # N: Revealed type is \"builtins.tuple[builtins.bool, ...]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleSubclassJoinIrregular]\nfrom typing import Tuple, NamedTuple, TypeVar\n\nclass NTup1(NamedTuple):\n    a: bool\n\nclass NTup2(NamedTuple):\n    a: bool\n    b: bool\n\nclass SubTuple(Tuple[bool, int, int]): ...\n\ntup1: NTup1\ntup2: NTup2\nsubtup: SubTuple\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nreveal_type(join(tup1, tup2))  # N: Revealed type is \"builtins.tuple[builtins.bool, ...]\"\nreveal_type(join(tup2, tup1))  # N: Revealed type is \"builtins.tuple[builtins.bool, ...]\"\n\nreveal_type(join(tup1, subtup))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(join(subtup, tup1))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nreveal_type(join(tup2, subtup))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(join(subtup, tup2))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTupleWithUndersizedContext]\na = ([1], 'x')\nif int():\n    a = ([], 'x', 1)  # E: Incompatible types in assignment (expression has type \"Tuple[List[Never], str, int]\", variable has type \"Tuple[List[int], str]\")\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithOversizedContext]\na = (1, [1], 'x')\nif int():\n    a = (1, [])  # E: Incompatible types in assignment (expression has type \"Tuple[int, List[int]]\", variable has type \"Tuple[int, List[int], str]\")\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithoutContext]\na = (1, [])  # E: Need type annotation for \"a\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithUnionContext]\nfrom typing import List, Union, Tuple\ndef f() -> Union[int, Tuple[List[str]]]:\n    return ([],)\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithVariableSizedTupleContext]\nfrom typing import List, Tuple\ndef f() -> Tuple[List[str], ...]:\n    return ([],)\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithoutArgs]\nfrom typing import Tuple\ndef f(a: Tuple) -> None: pass\nf(())\nf((1,))\nf(('', ''))\nf(0)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"Tuple[Any, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleSingleton]\n\nfrom typing import Tuple\ndef f(a: Tuple[()]) -> None: pass\nf(())\nf((1,))  # E: Argument 1 to \"f\" has incompatible type \"Tuple[int]\"; expected \"Tuple[()]\"\nf(('', ''))  # E: Argument 1 to \"f\" has incompatible type \"Tuple[str, str]\"; expected \"Tuple[()]\"\nf(0)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"Tuple[()]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNonliteralTupleIndex]\nt = (0, \"\")\nx = 0\ny = \"\"\nreveal_type(t[x])  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nt[y]  # E: No overload variant of \"__getitem__\" of \"tuple\" matches argument type \"str\" \\\n      # N: Possible overload variants: \\\n      # N:     def __getitem__(self, int, /) -> Union[int, str] \\\n      # N:     def __getitem__(self, slice, /) -> Tuple[Union[int, str], ...]\n\n[builtins fixtures/tuple.pyi]\n\n[case testNonliteralTupleSlice]\nt = (0, \"\")\nx = 0\ny = \"\"\nreveal_type(t[x:])  # N: Revealed type is \"builtins.tuple[Union[builtins.int, builtins.str], ...]\"\nt[y:]  # E: Slice index must be an integer, SupportsIndex or None\n[builtins fixtures/tuple.pyi]\n\n[case testTupleSliceStepZeroNoCrash]\n# This was crashing: https://github.com/python/mypy/issues/18062\n# TODO: emit better error when 0 is used for step\n()[::0]  # E: Ambiguous slice of a variadic tuple\n[builtins fixtures/tuple.pyi]\n\n[case testInferTupleTypeFallbackAgainstInstance]\nfrom typing import TypeVar, Generic, Tuple\nT = TypeVar('T')\n\nclass Base(Generic[T]): pass\ndef f(x: Base[T]) -> T: pass\n\nclass DT(Tuple[str, str], Base[int]):\n    pass\n\nreveal_type(f(DT())) # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTypeTupleClassmethod]\nfrom typing import Tuple, Type\n\nclass C(Tuple[int, str]):\n    @classmethod\n    def f(cls) -> None: pass\n\nt: Type[C]\nt.g()  # E: \"Type[C]\" has no attribute \"g\"\nt.f()\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeTupleCall]\nfrom typing import Tuple\n\ndef foo(o: CallableTuple) -> int:\n    reveal_type(o)  # N: Revealed type is \"Tuple[builtins.str, builtins.int, fallback=__main__.CallableTuple]\"\n    return o(1, 2)\n\nclass CallableTuple(Tuple[str, int]):\n    def __call__(self, n: int, m: int) -> int:\n        return n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeTupleGenericCall]\nfrom typing import Generic, Tuple, TypeVar\n\nT = TypeVar('T')\n\ndef foo(o: CallableTuple[int]) -> int:\n    reveal_type(o)  # N: Revealed type is \"Tuple[builtins.str, builtins.int, fallback=__main__.CallableTuple[builtins.int]]\"\n    reveal_type(o.count(3))  # N: Revealed type is \"builtins.int\"\n    return o(1, 2)\n\nclass CallableTuple(Tuple[str, T]):\n    def __call__(self, n: int, m: int) -> int:\n        return n\n[builtins fixtures/tuple.pyi]\n\n[case testTupleCompatibleWithSequence]\nfrom typing import Sequence\ns: Sequence[str]\ns = tuple()\nreveal_type(s) # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTupleInstanceCompatibleWithIterable]\nfrom typing import Iterable, Tuple\nx: Iterable[int] = ()\ny: Tuple[int, ...]\nx = y\nreveal_type(x) # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTupleTypeCompatibleWithIterable]\nfrom typing import Iterable, Tuple\nx: Iterable[int] = ()\ny: Tuple[int, int] = (1, 2)\nx = y\nreveal_type(x) # N: Revealed type is \"Tuple[builtins.int, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleOverlapDifferentTuples]\nfrom typing import Optional, Tuple\nclass A: pass\nclass B: pass\n\npossibles: Tuple[int, Tuple[A]]\nx: Optional[Tuple[B]]\n\nif x in possibles:\n    reveal_type(x) # N: Revealed type is \"Tuple[__main__.B]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"Union[Tuple[__main__.B], None]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOfTupleIndex]\nfrom typing import Union, Tuple\n\ntup: Union[Tuple[int, str], Tuple[int, int, str]]\nreveal_type(tup[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(tup[1])  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nreveal_type(tup[2])  # E: Tuple index out of range \\\n                     # N: Revealed type is \"Union[Any, builtins.str]\"\nreveal_type(tup[:])  # N: Revealed type is \"Union[Tuple[builtins.int, builtins.str], Tuple[builtins.int, builtins.int, builtins.str]]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOfTupleIndexMixed]\nfrom typing import Union, Tuple, List\n\ntup: Union[Tuple[int, str], List[int]]\nreveal_type(tup[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(tup[1])  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nreveal_type(tup[2])  # E: Tuple index out of range \\\n                     # N: Revealed type is \"Union[Any, builtins.int]\"\nreveal_type(tup[:])  # N: Revealed type is \"Union[Tuple[builtins.int, builtins.str], builtins.list[builtins.int]]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testFixedLengthTupleConcatenation]\na = (1, \"foo\", 3)\nb = (\"bar\", 7)\n\nreveal_type(a + b)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, builtins.int, builtins.str, builtins.int]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testAssigningWithLongTupleInitializer]\nfrom typing import Tuple\n\n# long initializer assignment with few mismatches\nt: Tuple[int, ...] = (1, 2, 3, 4, 5, 6, 7, 8, \"str\", \"str\", \"str\", 11) # E: Incompatible types in assignment (3 tuple items are incompatible) \\\n                                                                       # N: Expression tuple item 8 has type \"str\"; \"int\" expected;  \\\n                                                                       # N: Expression tuple item 9 has type \"str\"; \"int\" expected;  \\\n                                                                       # N: Expression tuple item 10 has type \"str\"; \"int\" expected;\n\n# long initializer assignment with more mismatches\nt1: Tuple[int, ...] = (1, 2, 3, 4, 5, 6, 7, 8, \"str\", \"str\", \"str\", \"str\") # E: Incompatible types in assignment (4 tuple items are incompatible; 1 items are omitted) \\\n                                                                           # N: Expression tuple item 8 has type \"str\"; \"int\" expected;  \\\n                                                                           # N: Expression tuple item 9 has type \"str\"; \"int\" expected;  \\\n                                                                           # N: Expression tuple item 10 has type \"str\"; \"int\" expected;\n\n# short tuple initializer assignment\nt2: Tuple[int, ...] = (1, 2, \"s\", 4) # E: Incompatible types in assignment (expression has type \"Tuple[int, int, str, int]\", variable has type \"Tuple[int, ...]\")\n\n# long initializer assignment with few mismatches, no ellipsis\nt3: Tuple[int, int, int, int, int, int, int, int, int, int, int, int] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \"str\", \"str\") # E: Incompatible types in assignment (2 tuple items are incompatible) \\\n                                                                                                                      # N: Expression tuple item 10 has type \"str\"; \"int\" expected;  \\\n                                                                                                                      # N: Expression tuple item 11 has type \"str\"; \"int\" expected;\n\n# long initializer assignment with more mismatches, no ellipsis\nt4: Tuple[int, int, int, int, int, int, int, int, int, int, int, int] = (1, 2, 3, 4, 5, 6, 7, 8, \"str\", \"str\", \"str\", \"str\") # E: Incompatible types in assignment (4 tuple items are incompatible; 1 items are omitted) \\\n                                                                                                                             # N: Expression tuple item 8 has type \"str\"; \"int\" expected;  \\\n                                                                                                                             # N: Expression tuple item 9 has type \"str\"; \"int\" expected;  \\\n                                                                                                                             # N: Expression tuple item 10 has type \"str\"; \"int\" expected;\n\n# short tuple initializer assignment, no ellipsis\nt5: Tuple[int, int] = (1, 2, \"s\", 4)  # E: Incompatible types in assignment (expression has type \"Tuple[int, int, str, int]\", variable has type \"Tuple[int, int]\")\n\n# long initializer assignment with mismatched pairs\nt6: Tuple[int, int, int, int, int, int, int, int, int, int, int, int] = (1, 2, 3, 4, 5, 6, 7, 8, \"str\", \"str\", \"str\", \"str\", 1, 1, 1, 1, 1) # E: Incompatible types in assignment (expression has type Tuple[int, int, ... <15 more items>], variable has type Tuple[int, int, ... <10 more items>])\n\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithStarExpr]\nfrom typing import Tuple, List\npoints = (1, \"test\")  # type: Tuple[int, str]\nx, y, z = *points, 0\nreveal_type(x) # N: Revealed type is \"builtins.int\"\nreveal_type(y) # N: Revealed type is \"builtins.str\"\nreveal_type(z) # N: Revealed type is \"builtins.int\"\n\npoints2 = [1,2]\nx2, y2, z2= *points2, \"test\"\n\nreveal_type(x2) # N: Revealed type is \"builtins.int\"\nreveal_type(y2) # N: Revealed type is \"builtins.int\"\nreveal_type(z2) # N: Revealed type is \"builtins.str\"\n\nx3, x4, y3, y4, z3 = *points, *points2, \"test\"\n\nreveal_type(x3) # N: Revealed type is \"builtins.int\"\nreveal_type(x4) # N: Revealed type is \"builtins.str\"\nreveal_type(y3) # N: Revealed type is \"builtins.int\"\nreveal_type(y4) # N: Revealed type is \"builtins.int\"\nreveal_type(z3) # N: Revealed type is \"builtins.str\"\n\nx5, x6, y5, y6, z4 = *points2, *points2, \"test\"\n\nreveal_type(x5) # N: Revealed type is \"builtins.int\"\nreveal_type(x6) # N: Revealed type is \"builtins.int\"\nreveal_type(y5) # N: Revealed type is \"builtins.int\"\nreveal_type(y6) # N: Revealed type is \"builtins.int\"\nreveal_type(z4) # N: Revealed type is \"builtins.str\"\n\npoints3 = [\"test1\", \"test2\"]\nx7, x8, y7, y8 = *points2, *points3 # E: Contiguous iterable with same type expected\n\nx9, y9, x10, y10, z5 = *points2, 1, *points2 # E: Contiguous iterable with same type expected\n[builtins fixtures/tuple.pyi]\n\n[case testAssignEmpty]\n() = []\n\n[case testAssignEmptyBogus]\n() = 1  # E: \"int\" object is not iterable\n[builtins fixtures/tuple.pyi]\n\n[case testMultiplyTupleByIntegerLiteral]\nfrom typing import Tuple\nt = ('',) * 2\nreveal_type(t)  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\nt2 = ('',) * -1\nreveal_type(t2)  # N: Revealed type is \"Tuple[()]\"\nt3 = ('', 1) * 2\nreveal_type(t3)  # N: Revealed type is \"Tuple[builtins.str, builtins.int, builtins.str, builtins.int]\"\ndef f() -> Tuple[str, ...]:\n    return ('', )\nreveal_type(f() * 2)  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testEmptyTupleTypeRepr]\nfrom typing import Tuple\n\ndef f() -> Tuple[()]: ...\n\nreveal_type(f)    # N: Revealed type is \"def () -> Tuple[()]\"\nreveal_type(f())  # N: Revealed type is \"Tuple[()]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMultiplyTupleByIntegerLiteralReverse]\nfrom typing import Tuple\nt = 2 * ('',)\nreveal_type(t)  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\nt2 = -1 * ('',)\nreveal_type(t2)  # N: Revealed type is \"Tuple[()]\"\nt3 = 2 * ('', 1)\nreveal_type(t3)  # N: Revealed type is \"Tuple[builtins.str, builtins.int, builtins.str, builtins.int]\"\ndef f() -> Tuple[str, ...]:\n    return ('', )\nreveal_type(2 * f())  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testSingleUndefinedTypeAndTuple]\nfrom typing import Tuple\n\nclass Foo:\n    ...\n\nclass Bar(aaaaaaaaaa):  # E: Name \"aaaaaaaaaa\" is not defined\n    ...\n\nclass FooBarTuple(Tuple[Foo, Bar]):\n    ...\n[builtins fixtures/tuple.pyi]\n\n[case testMultipleUndefinedTypeAndTuple]\nfrom typing import Tuple\n\nclass Foo(aaaaaaaaaa):  # E: Name \"aaaaaaaaaa\" is not defined\n    ...\n\nclass Bar(aaaaaaaaaa):  # E: Name \"aaaaaaaaaa\" is not defined\n    ...\n\nclass FooBarTuple(Tuple[Foo, Bar]):\n    ...\n[builtins fixtures/tuple.pyi]\n\n\n[case testTupleOverloadZipAny]\nfrom typing import Any, Iterable, Iterator, Tuple, TypeVar, overload\n\nT = TypeVar(\"T\")\n\n@overload\ndef zip(__i: Iterable[T]) -> Iterator[Tuple[T]]: ...\n@overload\ndef zip(*i: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ...\ndef zip(i): ...\n\ndef g(t: Tuple):\n    reveal_type(zip(*t))  # N: Revealed type is \"typing.Iterator[builtins.tuple[Any, ...]]\"\n    reveal_type(zip(t))  # N: Revealed type is \"typing.Iterator[Tuple[Any]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleSubclassSlice]\nfrom typing import Tuple\n\nclass A: ...\n\nclass tuple_aa_subclass(Tuple[A, A]): ...\n\ninst_tuple_aa_subclass: tuple_aa_subclass = tuple_aa_subclass((A(), A()))[:]  # E: Incompatible types in assignment (expression has type \"Tuple[A, A]\", variable has type \"tuple_aa_subclass\")\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-type-aliases.test",
    "content": "[case testSimpleTypeAlias]\nimport typing\ni = int\ndef f(x: i) -> None: pass\nf(1)\nf('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[targets __main__, __main__.f]\n\n[case testUnionTypeAlias]\nfrom typing import Union\nU = Union[int, str]\ndef f(x: U) -> None: pass\nf(1)\nf('')\nf(()) # E: Argument 1 to \"f\" has incompatible type \"Tuple[()]\"; expected \"Union[int, str]\"\n[targets __main__, __main__.f]\n[builtins fixtures/tuple.pyi]\n\n[case testTupleTypeAlias]\nfrom typing import Tuple\nT = Tuple[int, str]\ndef f(x: T) -> None: pass\nf((1, 'x'))\nf(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"Tuple[int, str]\"\n[targets __main__, __main__.f]\n[builtins fixtures/tuple.pyi]\n\n[case testCallableTypeAlias]\nfrom typing import Callable\nA = Callable[[int], None]\nf: A\nf(1)\nf('') # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n[targets __main__]\n\n[case testListTypeAlias]\nfrom typing import List\nA = List[int]\ndef f(x: A) -> None: pass\nf([1])\nf(['x']) # E: List item 0 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n[targets __main__, __main__.f]\n\n[case testAnyTypeAlias]\nfrom typing import Any\nA = Any\ndef f(x: A) -> None:\n    x.foo()\nf(1)\nf('x')\n\n[case testNoReturnTypeAlias]\n# https://github.com/python/mypy/issues/11903\nfrom typing import NoReturn\nNever = NoReturn\na: Never  # Used to be an error here\n\ndef f(a: Never): ...\nf(5)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"Never\"\n[case testImportUnionAlias]\nimport typing\nfrom _m import U\ndef f(x: U) -> None: pass\nf(1)\nf('x')\nf(()) # E: Argument 1 to \"f\" has incompatible type \"Tuple[()]\"; expected \"Union[int, str]\"\n[file _m.py]\nfrom typing import Union\nU = Union[int, str]\n[builtins fixtures/tuple.pyi]\n\n[case testProhibitReassigningAliases]\nA = float\nif int():\n    A = int  # E: Cannot assign multiple types to name \"A\" without an explicit \"Type[...]\" annotation\n[out]\n\n[case testProhibitReassigningSubscriptedAliases]\nfrom typing import Callable\nA = Callable[[], float]\nif int():\n    A = Callable[[], int] \\\n      # E: Cannot assign multiple types to name \"A\" without an explicit \"Type[...]\" annotation \\\n      # E: The type \"Type[Callable]\" is not generic and not indexable\n      # the second error is because of `class Callable:` in lib-stub/typing.pyi\n[builtins fixtures/list.pyi]\n[out]\n\n[case testProhibitReassigningGenericAliases]\nfrom typing import TypeVar, Union, Tuple\nT = TypeVar('T')\n\nA = Tuple[T, T]\nif int():\n    A = Union[T, int]  # E: Cannot assign multiple types to name \"A\" without an explicit \"Type[...]\" annotation\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testProhibitUsingVariablesAsTypesAndAllowAliasesAsTypes]\n\nfrom typing import TypeVar, Sequence, Type\nT = TypeVar('T')\n\nA: Type[float] = int\nif int():\n    A = float  # OK\nx: A  # E: Variable \"__main__.A\" is not valid as a type \\\n      # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\ndef bad(tp: A) -> None:  # E: Variable \"__main__.A\" is not valid as a type \\\n                         # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n    pass\n\nAlias = int\nGenAlias = Sequence[T]\ndef fun(x: Alias) -> GenAlias[int]: pass\n[out]\n\n[case testCorrectQualifiedAliasesAlsoInFunctions]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass X(Generic[T]):\n    A = X[S]\n    def f(self) -> X[T]:\n        pass\n\n    a: X[T]\n    b: A = a\n    c: A[T] = a\n    d: A[int] = a # E: Incompatible types in assignment (expression has type \"X[T]\", variable has type \"X[int]\")\n\n    def g(self) -> None:\n        a: X[T]\n        b: X.A = a\n        c: X.A[T] = a\n        d: X.A[int] = a  # E: Incompatible types in assignment (expression has type \"X[T]\", variable has type \"X[int]\")\n\ndef g(arg: X[int]) -> None:\n    p: X[int] = arg.f()\n    q: X.A = arg.f()\n    r: X.A[str] = arg.f() # E: Incompatible types in assignment (expression has type \"X[int]\", variable has type \"X[str]\")\n[out]\n\n[case testProhibitBoundTypeVariableReuseForAliases]\nfrom typing import TypeVar, Generic, List\nT = TypeVar('T')\nclass C(Generic[T]):\n    A = List[T] # E: Can't use bound type variable \"T\" to define generic alias\n\nx: C.A\nreveal_type(x) # N: Revealed type is \"builtins.list[Any]\"\n\ndef f(x: T) -> T:\n    A = List[T] # E: Can't use bound type variable \"T\" to define generic alias\n    return x\n[builtins fixtures/list.pyi]\n[out]\n\n[case testTypeAliasInBuiltins]\ndef f(x: bytes): pass\nbytes\nf(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/alias.pyi]\n\n[case testEmptyTupleTypeAlias]\nfrom typing import Tuple, Callable\nEmptyTuple = Tuple[()]\nx: EmptyTuple\nreveal_type(x)  # N: Revealed type is \"Tuple[()]\"\n\nEmptyTupleCallable = Callable[[Tuple[()]], None]\nf: EmptyTupleCallable\nreveal_type(f)  # N: Revealed type is \"def (Tuple[()])\"\n[builtins fixtures/list.pyi]\n\n[case testForwardTypeAlias]\ndef f(p: 'Alias') -> None:\n    pass\n\nreveal_type(f) # N: Revealed type is \"def (p: builtins.int)\"\nAlias = int\n[out]\n\n[case testForwardTypeAliasGeneric]\nfrom typing import TypeVar, Tuple\ndef f(p: 'Alias[str]') -> None:\n    pass\n\nreveal_type(f) # N: Revealed type is \"def (p: Tuple[builtins.int, builtins.str])\"\nT = TypeVar('T')\nAlias = Tuple[int, T]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testRecursiveAliasesErrors1]\nfrom typing import Type, Callable, Union\n\ndef test() -> None:\n    A = Union[A, int]  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                       # N: Recursive types are not allowed at function scope \\\n                       # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                       # N: Recursive types are not allowed at function scope\n    B = Callable[[B], int]  # E: Cannot resolve name \"B\" (possible cyclic definition) \\\n                            # N: Recursive types are not allowed at function scope \\\n                            # E: Cannot resolve name \"B\" (possible cyclic definition) \\\n                            # N: Recursive types are not allowed at function scope\n    C = Type[C]  # E: Cannot resolve name \"C\" (possible cyclic definition) \\\n                 # N: Recursive types are not allowed at function scope \\\n                 # E: Cannot resolve name \"C\" (possible cyclic definition) \\\n                 # N: Recursive types are not allowed at function scope\n\n[case testRecursiveAliasesErrors2]\n# flags: --disable-error-code=used-before-def\nfrom typing import Type, Callable, Union\n\ndef test() -> None:\n    A = Union[B, int]\n    B = Callable[[C], int]\n    C = Type[A]\n    x: A\n    reveal_type(x)\n[out]\nmain:5: error: Cannot resolve name \"A\" (possible cyclic definition)\nmain:5: note: Recursive types are not allowed at function scope\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:6: note: Recursive types are not allowed at function scope\nmain:7: error: Cannot resolve name \"C\" (possible cyclic definition)\nmain:7: note: Recursive types are not allowed at function scope\nmain:9: note: Revealed type is \"Union[Any, builtins.int]\"\n\n[case testDoubleForwardAlias]\n# flags: --disable-error-code=used-before-def\nfrom typing import List\nx: A\nA = List[B]\nB = List[int]\nreveal_type(x) # N: Revealed type is \"builtins.list[builtins.list[builtins.int]]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testDoubleForwardAliasWithNamedTuple]\n# flags: --disable-error-code=used-before-def\nfrom typing import List, NamedTuple\nx: A\nA = List[B]\nclass B(NamedTuple):\n    x: str\nreveal_type(x[0].x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testJSONAliasApproximation]\nfrom typing import List, Union, Dict\n\ndef test() -> None:\n    x: JSON  # E: Cannot resolve name \"JSON\" (possible cyclic definition)  \\\n             # N: Recursive types are not allowed at function scope\n    JSON = Union[int, str, List[JSON], Dict[str, JSON]]  # E: Cannot resolve name \"JSON\" (possible cyclic definition) \\\n                                                         # N: Recursive types are not allowed at function scope \\\n                                                         # E: Cannot resolve name \"JSON\" (possible cyclic definition) \\\n                                                         # N: Recursive types are not allowed at function scope \\\n                                                         # E: Cannot resolve name \"JSON\" (possible cyclic definition) \\\n                                                         # N: Recursive types are not allowed at function scope\n    reveal_type(x) # N: Revealed type is \"Any\"\n    if isinstance(x, list):\n        reveal_type(x) # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/isinstancelist.pyi]\n[out]\n\n[case testForwardRefToTypeVar]\n# flags: --disable-error-code=used-before-def\n\nfrom typing import TypeVar, List\nreveal_type(a)  # N: Revealed type is \"builtins.list[builtins.int]\"\na: A[int]\nA = List[T]\nT = TypeVar('T')\n[builtins fixtures/list.pyi]\n[out]\n\n[case testFunctionForwardRefAlias]\n\nfrom typing import List, TypeVar\n\nT = TypeVar('T')\n\ndef f(x: T) -> List[T]:\n    y: A[T]\n    reveal_type(y)  # N: Revealed type is \"builtins.list[T`-1]\"\n    return [x] + y\n\nA = List[T]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testFunctionForwardRefAlias2]\n\nfrom typing import List, TypeVar\n\ndef f() -> None:\n    X = List[int]\n    x: A[X]\n    reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.list[builtins.int]]\"\n\nT = TypeVar('T')\nA = List[T]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNoneAlias]\nfrom typing import Union\nvoid = type(None)\nx: void\nreveal_type(x)  # N: Revealed type is \"None\"\ny: Union[int, void]\nreveal_type(y)  # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/bool.pyi]\n\n[case testNoneAliasStrict]\nfrom typing import Optional, Union\nvoid = type(None)\nx: int\ny: Union[int, void]\nz: Optional[int]\nx = y  # E: Incompatible types in assignment (expression has type \"Optional[int]\", variable has type \"int\")\ny = z\n[builtins fixtures/bool.pyi]\n\n[case testAliasToTupleAndCallable]\nfrom typing import Callable, Tuple\nC = Callable\nT = Tuple\nc: C\nt: T\nreveal_type(c)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\nreveal_type(t)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\nbad: C[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nalso_bad: T[int]  # E: Bad number of arguments for type alias, expected 0, given 1\n[builtins fixtures/tuple.pyi]\n\n[case testAliasRefOnClass]\nfrom typing import Generic, TypeVar, Type\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    pass\n\nclass N:\n    A = C[T]\n    B = C[int]\n\nx: N.A[C]\nreveal_type(x)  # N: Revealed type is \"__main__.C[__main__.C[Any]]\"\n\nxx = N.A[C]()\nreveal_type(xx)  # N: Revealed type is \"__main__.C[__main__.C[Any]]\"\n\ny = N.A()\nreveal_type(y)  # N: Revealed type is \"__main__.C[Any]\"\n\nM = N\nb = M.A[int]()\nreveal_type(b)  # N: Revealed type is \"__main__.C[builtins.int]\"\n\nn: Type[N]\nw = n.B()\nreveal_type(w)  # N: Revealed type is \"__main__.C[builtins.int]\"\n[out]\n\n[case testTypeAliasesToNamedTuple]\nfrom nt import C, D, E\n\nA1 = C\nA2 = D\nA3 = E\n\nclass Cls:\n    A1 = C\n    A2 = D\n    A3 = E\n\nA1('no')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\na1 = A1(1)\nreveal_type(a1)  # N: Revealed type is \"Tuple[builtins.int, fallback=nt.C]\"\n\nA2(0)  # E: Argument 1 to \"D\" has incompatible type \"int\"; expected \"str\"\na2 = A2('yes')\nreveal_type(a2)  # N: Revealed type is \"Tuple[builtins.str, fallback=nt.D]\"\n\na3 = A3()\nreveal_type(a3)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=nt.E]\"\n\nCls.A1('no')  # E: Argument 1 has incompatible type \"str\"; expected \"int\"\nca1 = Cls.A1(1)\nreveal_type(ca1)  # N: Revealed type is \"Tuple[builtins.int, fallback=nt.C]\"\n\nCls.A2(0)  # E: Argument 1 has incompatible type \"int\"; expected \"str\"\nca2 = Cls.A2('yes')\nreveal_type(ca2)  # N: Revealed type is \"Tuple[builtins.str, fallback=nt.D]\"\n\nca3 = Cls.A3()\nreveal_type(ca3)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=nt.E]\"\n[file nt.pyi]\nfrom typing import NamedTuple, Tuple\n\nclass C(NamedTuple):\n    x: int\n\nD = NamedTuple('D', [('y', str)])\n\nclass E(Tuple[int, str]):\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTypeAliasesToAny]\nfrom typing import Any\n\nA = Any\nA # this should not fail\n[out]\n\n[case testDoubleImportsOfAnAlias]\nfrom b import *\nfrom c import *\n[file b.py]\nfrom a import A\n[file c.py]\nfrom a import A\n[file a.py]\nA = int\n[out]\n\n[case testDoubleImportsOfAnAlias2]\nfrom b import A\nfrom c import A\n[file b.py]\nfrom a import A\n[file c.py]\nfrom a import A\n[file a.py]\nA = int\n[out]\n\n[case testDoubleImportsOfAnAlias3]\nfrom b import *\nfrom c import *\n[file b.py]\nfrom a import A\n[file c.py]\nfrom a import A\n[file a.py]\nfrom typing import Union\nA = Union[None]\n[out]\n\n[case testAliasToClassMethod]\nfrom typing import TypeVar, Generic, Union, Type\n\nT = TypeVar('T', bound='C')\n\nMYPY = False\nif MYPY:\n    test = classmethod\n\nclass C:\n    @test\n    def meth(cls: Type[T], arg: int) -> Union[T, int]: ...\n\nclass D(C): ...\n\nreveal_type(D.meth(1))  # N: Revealed type is \"Union[__main__.D, builtins.int]\"\nreveal_type(D().meth(1))  # N: Revealed type is \"Union[__main__.D, builtins.int]\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testAliasInImportCycle]\n# cmd: mypy -m t t2\n[file t.py]\nMYPY = False\nif MYPY:\n    from t2 import A\nx: A\n[file t2.py]\nimport t\nfrom typing import Callable\nA = Callable[[], None]\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testAliasInImportCycle2]\nimport a\n[file a.pyi]\nfrom b import Parameter\n\nclass _ParamType:\n    p: Parameter\n\n_ConvertibleType = _ParamType\n\ndef convert_type(ty: _ConvertibleType):\n    ...\n\n[file b.pyi]\nfrom a import _ConvertibleType\n\nclass Parameter:\n    type: _ConvertibleType\n[out]\n\n[case testAliasInImportCycle3]\n# cmd: mypy -m t t2\n\n[file t.py]\nMYPY = False\nif MYPY:\n    from t2 import A\nx: A\nreveal_type(x)  # N: Revealed type is \"t2.D\"\n\nreveal_type(A)  # N: Revealed type is \"def () -> t2.D\"\nA()\n[file t2.py]\nimport t\nclass D: pass\nA = D\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testFlexibleAlias1]\nfrom typing import TypeVar, List, Tuple\nfrom mypy_extensions import FlexibleAlias\n\nT = TypeVar('T')\nU = TypeVar('U')\n\nAnInt = FlexibleAlias[T, int]\n\nx: AnInt[str]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nTwoArgs = FlexibleAlias[Tuple[T, U], bool]\nTwoArgs2 = FlexibleAlias[Tuple[T, U], List[U]]\n\ndef welp(x: TwoArgs[str, int]) -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.bool\"\n\ndef welp2(x: TwoArgs2[str, int]) -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n\nId = FlexibleAlias[T, T]\n\ndef take_id(x: Id[int]) -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ndef id(x: Id[T]) -> T:\n    return x\n\n# TODO: This doesn't work and maybe it should?\n# Indirection = AnInt[T]\n# y: Indirection[str]\n# reveal_type(y)  # E : Revealed type is \"builtins.int\"\n\n# But this does\nIndirection2 = FlexibleAlias[T, AnInt[T]]\nz: Indirection2[str]\nreveal_type(z)  # N: Revealed type is \"builtins.int\"\n\nIndirection3 = FlexibleAlias[Tuple[T, U], AnInt[T]]\nw: Indirection3[str, int]\nreveal_type(w)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/dict.pyi]\n\n[case testFlexibleAlias2]\n# flags: --always-true=BOGUS\nfrom typing import TypeVar, Any\nfrom mypy_extensions import FlexibleAlias\n\nT = TypeVar('T')\n\nBOGUS = True\nif BOGUS:\n    Bogus = FlexibleAlias[T, Any]\nelse:\n    Bogus = FlexibleAlias[T, T]\n\nclass A:\n    x: Bogus[str]\n\nreveal_type(A().x)  # N: Revealed type is \"Any\"\n\ndef foo(x: Bogus[int]) -> None:\n    reveal_type(x)  # N: Revealed type is \"Any\"\n\n[builtins fixtures/dict.pyi]\n\n[case testFlexibleAlias3]\n# flags: --always-false=BOGUS\nfrom typing import TypeVar, Any\nfrom mypy_extensions import FlexibleAlias\n\nT = TypeVar('T')\n\nBOGUS = True\nif BOGUS:\n    Bogus = FlexibleAlias[T, Any]\nelse:\n    Bogus = FlexibleAlias[T, T]\n\nclass A:\n    x: Bogus[str]\n\nreveal_type(A().x)  # N: Revealed type is \"builtins.str\"\n\ndef foo(x: Bogus[int]) -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/dict.pyi]\n\n[case testOverrideByIdemAliasCorrectType]\nC = C\nclass C:  # type: ignore\n    pass\nx: C\nreveal_type(x)  # N: Revealed type is \"__main__.C\"\n[out]\n\n[case testOverrideByIdemAliasCorrectTypeReversed]\nclass C:\n    pass\nC = C  # type: ignore\nx: C\nreveal_type(x)  # N: Revealed type is \"__main__.C\"\n[out]\n\n[case testOverrideByIdemAliasCorrectTypeImported]\nfrom other import C as B\nC = B\nx: C\nreveal_type(x)  # N: Revealed type is \"other.C\"\n[file other.py]\nclass C:\n    pass\n[out]\n\n[case testConditionalExceptionAlias]\n\ntry:\n    E = E\nexcept BaseException:\n    class E(BaseException): pass  # type: ignore\n\ntry:\n    pass\nexcept E as e:\n    reveal_type(e)  # N: Revealed type is \"__main__.E\"\n[builtins fixtures/exception.pyi]\n[out]\n\n[case testNestedClassOnAliasAsType]\nclass Out:\n    class In:\n        class Inner:\n            pass\n\nO = Out\nI = Out.In\nOI = O.In\nA = Out\nB = A\n\nw: O.In\nx: I.Inner\ny: OI.Inner\nz: B.In\nreveal_type(w)  # N: Revealed type is \"__main__.Out.In\"\nreveal_type(x)  # N: Revealed type is \"__main__.Out.In.Inner\"\nreveal_type(y)  # N: Revealed type is \"__main__.Out.In.Inner\"\nreveal_type(z)  # N: Revealed type is \"__main__.Out.In\"\n\n\n[case testSimplePep613]\nfrom typing_extensions import TypeAlias\nx: TypeAlias = str\na: x\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\n\ny: TypeAlias = \"str\"\nb: y\nreveal_type(b)  # N: Revealed type is \"builtins.str\"\n\nz: TypeAlias = \"int | str\"\nc: z\nreveal_type(c)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testForwardRefPep613]\nfrom typing_extensions import TypeAlias\n\nx: TypeAlias = \"MyClass\"\na: x\nreveal_type(a)  # N: Revealed type is \"__main__.MyClass\"\n\nclass MyClass: ...\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidPep613]\nfrom typing_extensions import TypeAlias\n\nx: TypeAlias = list(int)  # E: Invalid type alias: expression is not a valid type \\\n                          # E: Too many arguments for \"list\"\na: x\n[builtins fixtures/tuple.pyi]\n\n[case testAliasedImportPep613]\nimport typing as tpp\nimport typing_extensions as tpx\nfrom typing import TypeAlias as TPA\nfrom typing_extensions import TypeAlias as TXA\nimport typing\nimport typing_extensions\n\nInt1: tpp.TypeAlias = int\nInt2: tpx.TypeAlias = int\nInt3: TPA = int\nInt4: TXA = int\nInt5: typing.TypeAlias = int\nInt6: typing_extensions.TypeAlias = int\n\nx1: Int1 = \"str\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nx2: Int2 = \"str\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nx3: Int3 = \"str\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nx4: Int4 = \"str\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nx5: Int5 = \"str\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nx6: Int6 = \"str\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testFunctionScopePep613]\nfrom typing_extensions import TypeAlias\n\ndef f() -> None:\n    x: TypeAlias = str\n    a: x\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n    y: TypeAlias = \"str\"\n    b: y\n    reveal_type(b)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testImportCyclePep613]\n# cmd: mypy -m t t2\n[file t.py]\nMYPY = False\nif MYPY:\n    from t2 import A\nx: A\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n[file t2.py]\nfrom typing_extensions import TypeAlias\nA: TypeAlias = str\n[builtins fixtures/bool.pyi]\n[out]\n\n\n[case testLiteralStringPep675]\n# flags: --python-version 3.11\nfrom typing import LiteralString as tpLS\nfrom typing_extensions import LiteralString as tpxLS\n\ndef f(a: tpLS, b: tpxLS) -> None:\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    reveal_type(b)  # N: Revealed type is \"builtins.str\"\n\n# This isn't the correct behaviour, but should unblock use of LiteralString in typeshed\nf(\"asdf\", \"asdf\")\nstring: str\nf(string, string)\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testForwardTypeVarRefWithRecursiveFlag]\nimport c\n[file a.py]\nfrom typing import TypeVar, List, Any, Generic\nfrom b import Alias\n\nT = TypeVar(\"T\", bound=Alias[Any])\ndef foo(x: T) -> T: ...\n\n[file b.py]\nfrom c import C\nfrom typing import TypeVar, List\n\nS = TypeVar(\"S\")\nAlias = List[C[S]]\n\n[file c.py]\nfrom typing import TypeVar, List, Generic\nimport a\n\nS = TypeVar(\"S\")\nclass C(Generic[S], List[Defer]): ...\nclass Defer: ...\n[builtins fixtures/list.pyi]\n\n[case testClassLevelTypeAliasesInUnusualContexts]\nfrom typing import Union\nfrom typing_extensions import TypeAlias\n\nclass Foo: pass\n\nNormalImplicit = Foo\nNormalExplicit: TypeAlias = Foo\nSpecialImplicit = Union[int, str]\nSpecialExplicit: TypeAlias = Union[int, str]\n\nclass Parent:\n    NormalImplicit = Foo\n    NormalExplicit: TypeAlias = Foo\n    SpecialImplicit = Union[int, str]\n    SpecialExplicit: TypeAlias = Union[int, str]\n\nclass Child(Parent): pass\n\np = Parent()\nc = Child()\n\n# Use type aliases in a runtime context\n\nreveal_type(NormalImplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(NormalExplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(SpecialImplicit)  # N: Revealed type is \"typing._SpecialForm\"\nreveal_type(SpecialExplicit)  # N: Revealed type is \"typing._SpecialForm\"\n\nreveal_type(Parent.NormalImplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(Parent.NormalExplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(Parent.SpecialImplicit)  # N: Revealed type is \"typing._SpecialForm\"\nreveal_type(Parent.SpecialExplicit)  # N: Revealed type is \"typing._SpecialForm\"\n\nreveal_type(Child.NormalImplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(Child.NormalExplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(Child.SpecialImplicit)  # N: Revealed type is \"typing._SpecialForm\"\nreveal_type(Child.SpecialExplicit)  # N: Revealed type is \"typing._SpecialForm\"\n\nreveal_type(p.NormalImplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(p.NormalExplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(p.SpecialImplicit)  # N: Revealed type is \"typing._SpecialForm\"\nreveal_type(p.SpecialExplicit)  # N: Revealed type is \"typing._SpecialForm\"\n\nreveal_type(c.NormalImplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(p.NormalExplicit)   # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(c.SpecialImplicit)  # N: Revealed type is \"typing._SpecialForm\"\nreveal_type(c.SpecialExplicit)  # N: Revealed type is \"typing._SpecialForm\"\n\n# Use type aliases in a type alias context in a plausible way\n\ndef plausible_top_1() -> NormalImplicit: pass\ndef plausible_top_2() -> NormalExplicit: pass\ndef plausible_top_3() -> SpecialImplicit: pass\ndef plausible_top_4() -> SpecialExplicit: pass\nreveal_type(plausible_top_1)  # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(plausible_top_2)  # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(plausible_top_3)  # N: Revealed type is \"def () -> Union[builtins.int, builtins.str]\"\nreveal_type(plausible_top_4)  # N: Revealed type is \"def () -> Union[builtins.int, builtins.str]\"\n\ndef plausible_parent_1() -> Parent.NormalImplicit: pass  # E: Variable \"__main__.Parent.NormalImplicit\" is not valid as a type \\\n                                                         # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\ndef plausible_parent_2() -> Parent.NormalExplicit: pass\ndef plausible_parent_3() -> Parent.SpecialImplicit: pass\ndef plausible_parent_4() -> Parent.SpecialExplicit: pass\nreveal_type(plausible_parent_1)  # N: Revealed type is \"def () -> Parent.NormalImplicit?\"\nreveal_type(plausible_parent_2)  # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(plausible_parent_3)  # N: Revealed type is \"def () -> Union[builtins.int, builtins.str]\"\nreveal_type(plausible_parent_4)  # N: Revealed type is \"def () -> Union[builtins.int, builtins.str]\"\n\ndef plausible_child_1() -> Child.NormalImplicit: pass  # E: Variable \"__main__.Parent.NormalImplicit\" is not valid as a type \\\n                                                       # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\ndef plausible_child_2() -> Child.NormalExplicit: pass\ndef plausible_child_3() -> Child.SpecialImplicit: pass\ndef plausible_child_4() -> Child.SpecialExplicit: pass\nreveal_type(plausible_child_1)  # N: Revealed type is \"def () -> Child.NormalImplicit?\"\nreveal_type(plausible_child_2)  # N: Revealed type is \"def () -> __main__.Foo\"\nreveal_type(plausible_child_3)  # N: Revealed type is \"def () -> Union[builtins.int, builtins.str]\"\nreveal_type(plausible_child_4)  # N: Revealed type is \"def () -> Union[builtins.int, builtins.str]\"\n\n# Use type aliases in a type alias context in an implausible way\n\ndef weird_parent_1() -> p.NormalImplicit: pass   # E: Name \"p.NormalImplicit\" is not defined\ndef weird_parent_2() -> p.NormalExplicit: pass   # E: Name \"p.NormalExplicit\" is not defined\ndef weird_parent_3() -> p.SpecialImplicit: pass  # E: Name \"p.SpecialImplicit\" is not defined\ndef weird_parent_4() -> p.SpecialExplicit: pass  # E: Name \"p.SpecialExplicit\" is not defined\nreveal_type(weird_parent_1)  # N: Revealed type is \"def () -> Any\"\nreveal_type(weird_parent_2)  # N: Revealed type is \"def () -> Any\"\nreveal_type(weird_parent_3)  # N: Revealed type is \"def () -> Any\"\nreveal_type(weird_parent_4)  # N: Revealed type is \"def () -> Any\"\n\ndef weird_child_1() -> c.NormalImplicit: pass   # E: Name \"c.NormalImplicit\" is not defined\ndef weird_child_2() -> c.NormalExplicit: pass   # E: Name \"c.NormalExplicit\" is not defined\ndef weird_child_3() -> c.SpecialImplicit: pass  # E: Name \"c.SpecialImplicit\" is not defined\ndef weird_child_4() -> c.SpecialExplicit: pass  # E: Name \"c.SpecialExplicit\" is not defined\nreveal_type(weird_child_1)  # N: Revealed type is \"def () -> Any\"\nreveal_type(weird_child_2)  # N: Revealed type is \"def () -> Any\"\nreveal_type(weird_child_3)  # N: Revealed type is \"def () -> Any\"\nreveal_type(weird_child_4)  # N: Revealed type is \"def () -> Any\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testMalformedTypeAliasRuntimeReassignments]\nfrom typing import Union\nfrom typing_extensions import TypeAlias\n\nclass Foo: pass\n\nNormalImplicit = Foo\nNormalExplicit: TypeAlias = Foo\nSpecialImplicit = Union[int, str]\nSpecialExplicit: TypeAlias = Union[int, str]\n\nclass Parent:\n    NormalImplicit = Foo\n    NormalExplicit: TypeAlias = Foo\n    SpecialImplicit = Union[int, str]\n    SpecialExplicit: TypeAlias = Union[int, str]\n\nclass Child(Parent): pass\n\np = Parent()\nc = Child()\n\nNormalImplicit = 4   # E: Cannot assign multiple types to name \"NormalImplicit\" without an explicit \"Type[...]\" annotation \\\n                     # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nNormalExplicit = 4   # E: Cannot assign multiple types to name \"NormalExplicit\" without an explicit \"Type[...]\" annotation \\\n                     # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nSpecialImplicit = 4  # E: Cannot assign multiple types to name \"SpecialImplicit\" without an explicit \"Type[...]\" annotation\nSpecialExplicit = 4  # E: Cannot assign multiple types to name \"SpecialExplicit\" without an explicit \"Type[...]\" annotation\n\nParent.NormalImplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nParent.NormalExplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nParent.SpecialImplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"<typing special form>\")\nParent.SpecialExplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"<typing special form>\")\n\nChild.NormalImplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nChild.NormalExplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nChild.SpecialImplicit = 4\nChild.SpecialExplicit = 4\n\np.NormalImplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\np.NormalExplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\np.SpecialImplicit = 4\np.SpecialExplicit = 4\n\nc.NormalImplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nc.NormalExplicit = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Type[Foo]\")\nc.SpecialImplicit = 4\nc.SpecialExplicit = 4\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testNewStyleUnionInTypeAliasWithMalformedInstance]\n# flags: --python-version 3.10\nfrom typing import List\n\nA = List[int, str] | int  # E: \"list\" expects 1 type argument, but 2 given\nB = int | list[int, str]  # E: \"list\" expects 1 type argument, but 2 given\na: A\nb: B\nreveal_type(a)  # N: Revealed type is \"Union[builtins.list[Any], builtins.int]\"\nreveal_type(b)  # N: Revealed type is \"Union[builtins.int, builtins.list[Any]]\"\n[builtins fixtures/type.pyi]\n\n[case testValidTypeAliasValues]\nfrom typing import TypeVar, Generic, List\n\nT = TypeVar(\"T\", int, str)\nS = TypeVar(\"S\", int, bytes)\n\nclass C(Generic[T]): ...\nclass D(C[S]): ...  # E: Invalid type argument value for \"C\" \\\n                    # N: \"T\" of \"C\" is a constrained type variable, it is not generic\n\nU = TypeVar(\"U\")\nA = List[C[U]]\nx: A[bytes]  # E: Value of type variable \"T\" of \"C\" cannot be \"bytes\" \\\n             # N: \"T\" of \"C\" is a constrained type variable, it is not generic\n\nV = TypeVar(\"V\", bound=int)\nclass E(Generic[V]): ...\nB = List[E[U]]\ny: B[str]  # E: Type argument \"str\" of \"E\" must be a subtype of \"int\" \\\n\n[case testValidTypeAliasValuesMoreRestrictive]\nfrom typing import TypeVar, Generic, List\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\", int, str)\nU = TypeVar(\"U\", bound=int)\n\nclass C(Generic[T]): ...\n\nA = List[C[S]]\nx: A[int]\nx_bad: A[bytes]  # E: Value of type variable \"S\" of \"A\" cannot be \"bytes\" \\\n                 # N: \"S\" of \"A\" is a constrained type variable, it is not generic\n\nB = List[C[U]]\ny: B[int]\ny_bad: B[str]  # E: Type argument \"str\" of \"B\" must be a subtype of \"int\"\n\n[case testTupleWithDifferentArgsPy38]\n# flags: --python-version 3.8\nNotYet1 = tuple[float]  # E: \"tuple\" is not subscriptable\nNotYet2 = tuple[float, float]  # E: \"tuple\" is not subscriptable\nNotYet3 = tuple[float, ...]  # E: Unexpected \"...\" \\\n                             # E: \"tuple\" is not subscriptable\nNotYet4 = tuple[float, float, ...]  # E: Unexpected \"...\" \\\n                                    # E: \"tuple\" is not subscriptable\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithDifferentArgsStub]\n# https://github.com/python/mypy/issues/11098\nimport tup\n\n[file tup.pyi]\nCorrect1 = str | tuple[float, float, str]\nCorrect2 = tuple[float] | str\nCorrect3 = tuple[float, ...] | str\nCorrect4 = tuple[float, str] | str\nCorrect5 = tuple[int, str]\nCorrect6 = tuple[int, ...]\n\nRHSAlias1: type = tuple[int, int]\nRHSAlias2: type = tuple[int]\nRHSAlias3: type = tuple[int, ...]\n\n# Wrong:\n\nWrongTypeElement = str | tuple[float, 1]  # E: Invalid type: try using Literal[1] instead?\nWrongEllipsis = str | tuple[float, float, ...]  # E: Unexpected \"...\"\n[builtins fixtures/tuple.pyi]\n\n[case testCompiledNoCrashOnSingleItemUnion]\n# flags: --no-strict-optional\nfrom typing import Callable, Union, Generic, TypeVar\n\nAlias = Callable[[], int]\n\nT = TypeVar(\"T\")\nclass C(Generic[T]):\n    attr: Union[Alias, None] = None\n\n    @classmethod\n    def test(cls) -> None:\n        cls.attr\n[builtins fixtures/classmethod.pyi]\n\n[case testRecursiveAliasTuple]\nfrom typing_extensions import Literal, TypeAlias\nfrom typing import Tuple, Union\n\nExpr: TypeAlias = Union[\n    Tuple[Literal[123], int],\n    Tuple[Literal[456], \"Expr\"],\n]\n\ndef eval(e: Expr) -> int:\n    if e[0] == 123:\n        return e[1]\n    elif e[0] == 456:\n        return -eval(e[1])\n[builtins fixtures/dict-full.pyi]\n\n[case testTypeAliasType]\nfrom typing import Union\nfrom typing_extensions import TypeAliasType\n\nTestType = TypeAliasType(\"TestType\", Union[int, str])\nx: TestType = 42\ny: TestType = 'a'\nz: TestType = object()  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"Union[int, str]\")\n\nreveal_type(TestType)  # N: Revealed type is \"typing_extensions.TypeAliasType\"\nTestType()  # E: \"TypeAliasType\" not callable\n\nclass A:\n    ClassAlias = TypeAliasType(\"ClassAlias\", int)\nxc: A.ClassAlias = 1\nyc: A.ClassAlias = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeAliasTypePython311]\n# flags: --python-version 3.11\n# Pinning to 3.11, because 3.12 has `TypeAliasType`\nfrom typing_extensions import TypeAliasType\n\nTestType = TypeAliasType(\"TestType\", int)\nx: TestType = 1\n[builtins fixtures/tuple.pyi]\n\n[case testTypeAliasTypeInvalid]\nfrom typing_extensions import TypeAliasType\n\nTestType = TypeAliasType(\"T\", int)  # E: String argument 1 \"T\" to TypeAliasType(...) does not match variable name \"TestType\"\n\nT1 = T2 = TypeAliasType(\"T\", int)\nt1: T1  # E: Variable \"__main__.T1\" is not valid as a type \\\n        # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\nT3 = TypeAliasType(\"T3\", -1)  # E: \"-1\" is a bare literal and cannot be used here, try Literal[-1] instead?\nt3: T3\nreveal_type(t3)  # N: Revealed type is \"Literal[-1]\"\n\nT4 = TypeAliasType(\"T4\")  # E: Missing positional argument \"value\" in call to \"TypeAliasType\"\nT5 = TypeAliasType(\"T5\", int, str)  # E: Too many positional arguments for \"TypeAliasType\" \\\n                                    # E: Argument 3 to \"TypeAliasType\" has incompatible type \"Type[str]\"; expected \"Tuple[Union[TypeVar?, ParamSpec?, TypeVarTuple?], ...]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeAliasTypeGeneric]\nfrom typing import Callable, Dict, Generic, TypeVar, Tuple\nfrom typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec, Unpack\n\nK = TypeVar('K')\nV = TypeVar('V')\nT = TypeVar('T')\nTs = TypeVarTuple(\"Ts\")\nTs1 = TypeVarTuple(\"Ts1\")\nP = ParamSpec(\"P\")\n\nTestType = TypeAliasType(\"TestType\", Dict[K, V], type_params=(K, V))\nx: TestType[int, str] = {1: 'a'}\ny: TestType[str, int] = {'a': 1}\nz: TestType[str, int] = {1: 'a'}  # E: Dict entry 0 has incompatible type \"int\": \"str\"; expected \"str\": \"int\"\nw: TestType[int]  # E: Bad number of arguments for type alias, expected 2, given 1\n\nInvertedDict = TypeAliasType(\"InvertedDict\", Dict[K, V], type_params=(V, K))\nxi: InvertedDict[str, int] = {1: 'a'}\nyi: InvertedDict[str, int] = {'a': 1}  # E: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"int\": \"str\"\nzi: InvertedDict[int, str] = {1: 'a'}  # E: Dict entry 0 has incompatible type \"int\": \"str\"; expected \"str\": \"int\"\nreveal_type(xi)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\nVariadicAlias1 = TypeAliasType(\"VariadicAlias1\", Tuple[Unpack[Ts]], type_params=(Ts,))\nVariadicAlias2 = TypeAliasType(\"VariadicAlias2\", Tuple[Unpack[Ts], K], type_params=(Ts, K))\nVariadicAlias3 = TypeAliasType(\"VariadicAlias3\", Callable[[Unpack[Ts]], int], type_params=(Ts,))\nxv: VariadicAlias1[int, str] = (1, 'a')\nyv: VariadicAlias1[str, int] = (1, 'a')  # E: Incompatible types in assignment (expression has type \"Tuple[int, str]\", variable has type \"Tuple[str, int]\")\nzv: VariadicAlias2[int, str] = (1, 'a')\ndef int_in_int_out(x: int) -> int: return x\nwv: VariadicAlias3[int] = int_in_int_out\nreveal_type(wv)  # N: Revealed type is \"def (x: builtins.int) -> builtins.int\"\n\nParamAlias = TypeAliasType(\"ParamAlias\", Callable[P, int], type_params=(P,))\ndef f(x: str, y: float) -> int: return 1\ndef g(x: int, y: float) -> int: return 1\nxp1: ParamAlias[str, float] = f\nxp2: ParamAlias[str, float] = g  # E: Incompatible types in assignment (expression has type \"Callable[[int, float], int]\", variable has type \"Callable[[str, float], int]\")\nxp3: ParamAlias[str, float] = lambda x, y: 1\n\nclass G(Generic[P, T]): ...\nParamAlias2 = TypeAliasType(\"ParamAlias2\", G[P, T], type_params=(P, T))\nxp: ParamAlias2[[int], str]\nreveal_type(xp)  # N: Revealed type is \"__main__.G[[builtins.int], builtins.str]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeAliasTypeInvalidGeneric]\nfrom typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec\nfrom typing import Callable, Dict, Generic, TypeVar, Tuple, Unpack\n\nK = TypeVar('K')\nV = TypeVar('V')\nT = TypeVar('T')\nTs = TypeVarTuple(\"Ts\")\nTs1 = TypeVarTuple(\"Ts1\")\nP = ParamSpec(\"P\")\n\nTa0 = TypeAliasType(\"Ta0\", int, type_params=(T, T))  # E: Duplicate type variable \"T\" in type_params argument to TypeAliasType\n\nTa1 = TypeAliasType(\"Ta1\", int, type_params=K)  # E: Tuple literal expected as the type_params argument to TypeAliasType\n\nTa2 = TypeAliasType(\"Ta2\", int, type_params=(None,))  # E: Free type variable expected in type_params argument to TypeAliasType\n\nTa3 = TypeAliasType(\"Ta3\", Dict[K, V], type_params=(V,))  # E: Type variable \"K\" is not included in type_params\npartially_generic1: Ta3[int] = {\"a\": 1}\nreveal_type(partially_generic1)  # N: Revealed type is \"builtins.dict[Any, builtins.int]\"\npartially_generic2: Ta3[int] = {1: \"a\"}  # E: Dict entry 0 has incompatible type \"int\": \"str\"; expected \"Any\": \"int\"\n\nTa4 = TypeAliasType(\"Ta4\", Tuple[Unpack[Ts]], type_params=(Ts, Ts1))  # E: Can only use one TypeVarTuple in type_params argument to TypeAliasType\n\nTa5 = TypeAliasType(\"Ta5\", Dict)  # Unlike old style aliases, this is not generic\nnon_generic_dict: Ta5[int, str]  # E: Bad number of arguments for type alias, expected 0, given 2\nreveal_type(non_generic_dict)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\nTa6 = TypeAliasType(\"Ta6\", Tuple[Unpack[Ts]])  # E: TypeVarTuple \"Ts\" is not included in type_params\nunbound_tvt_alias: Ta6[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(unbound_tvt_alias)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n\nclass G(Generic[P, T]): ...\nTa7 = TypeAliasType(\"Ta7\", G[P, T])  # E: ParamSpec \"P\" is not included in type_params \\\n                                     # E: Type variable \"T\" is not included in type_params\nunbound_ps_alias: Ta7[[int], str]  # E: Bracketed expression \"[...]\" is not valid as a type \\\n                                   # N: Did you mean \"list[...]\"? \\\n                                   # E: Bad number of arguments for type alias, expected 0, given 2\nreveal_type(unbound_ps_alias)  # N: Revealed type is \"__main__.G[Any, Any]\"\n\nTa8 = TypeAliasType(\"Ta8\", Callable[P, int])  # E: ParamSpec \"P\" is not included in type_params\nunbound_ps_alias2: Ta8[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(unbound_ps_alias2)  # N: Revealed type is \"def [P] (*Any, **Any) -> builtins.int\"\n\nTa9 = TypeAliasType(\"Ta9\", Callable[P, T])  # E: ParamSpec \"P\" is not included in type_params \\\n                                            # E: Type variable \"T\" is not included in type_params\nunbound_ps_alias3: Ta9[int, str]  # E: Bad number of arguments for type alias, expected 0, given 2\nreveal_type(unbound_ps_alias3)  # N: Revealed type is \"def [P] (*Any, **Any) -> Any\"\n\nTa10 = TypeAliasType(\"Ta10\", Callable[[Unpack[Ts]], str])  # E: TypeVarTuple \"Ts\" is not included in type_params\nunbound_tvt_alias2: Ta10[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(unbound_tvt_alias2)  # N: Revealed type is \"def (*Any) -> builtins.str\"\n\nclass A(Generic[T]):\n    Ta11 = TypeAliasType(\"Ta11\", Dict[str, T], type_params=(T,))  # E: Can't use bound type variable \"T\" to define generic alias\nx: A.Ta11 = {\"a\": 1}\nreveal_type(x)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeAliasTypeNoUnpackInTypeParams311]\n# flags: --python-version 3.11\nfrom typing_extensions import TypeAliasType, TypeVar, TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\nTa1 = TypeAliasType(\"Ta1\", None, type_params=(*Ts,))  # E: can't use starred expression here\nTa2 = TypeAliasType(\"Ta2\", None, type_params=(Unpack[Ts],))  # E: Free type variable expected in type_params argument to TypeAliasType \\\n                                                             # N: Don't Unpack type variables in type_params\n\n[builtins fixtures/tuple.pyi]\n\n[case testAliasInstanceNameClash]\nfrom lib import func\nclass A: ...\nfunc(A())  # E: Argument 1 to \"func\" has incompatible type \"__main__.A\"; expected \"lib.A\"\n[file lib.py]\nfrom typing import List, Union\n\nA = Union[int, List[A]]\ndef func(x: A) -> int: ...\n[builtins fixtures/tuple.pyi]\n\n[case testAliasExplicitNoArgsBasic]\nfrom typing import Any, List, assert_type\nfrom typing_extensions import TypeAlias\n\nImplicit = List\nExplicit: TypeAlias = List\n\nx1: Implicit[str]\nx2: Explicit[str]  # E: Bad number of arguments for type alias, expected 0, given 1\nassert_type(x1, List[str])\nassert_type(x2, List[Any])\n[builtins fixtures/tuple.pyi]\n\n[case testAliasExplicitNoArgsGenericClass]\n# flags: --python-version 3.9\nfrom typing import Any, assert_type\nfrom typing_extensions import TypeAlias\n\nImplicit = list\nExplicit: TypeAlias = list\n\nx1: Implicit[str]\nx2: Explicit[str]  # E: Bad number of arguments for type alias, expected 0, given 1\nassert_type(x1, list[str])\nassert_type(x2, list[Any])\n[builtins fixtures/tuple.pyi]\n\n[case testAliasExplicitNoArgsTuple]\nfrom typing import Any, Tuple, assert_type\nfrom typing_extensions import TypeAlias\n\nImplicit = Tuple\nExplicit: TypeAlias = Tuple\n\nx1: Implicit[str]  # E: Bad number of arguments for type alias, expected 0, given 1\nx2: Explicit[str]  # E: Bad number of arguments for type alias, expected 0, given 1\nassert_type(x1, Tuple[Any, ...])\nassert_type(x2, Tuple[Any, ...])\n[builtins fixtures/tuple.pyi]\n\n[case testAliasExplicitNoArgsCallable]\nfrom typing import Any, Callable, assert_type\nfrom typing_extensions import TypeAlias\n\nImplicit = Callable\nExplicit: TypeAlias = Callable\n\nx1: Implicit[str]  # E: Bad number of arguments for type alias, expected 0, given 1\nx2: Explicit[str]  # E: Bad number of arguments for type alias, expected 0, given 1\nassert_type(x1, Callable[..., Any])\nassert_type(x2, Callable[..., Any])\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-type-checks.test",
    "content": "-- Conditional type checks.\n\n\n[case testSimpleIsinstance]\nx: object\nn: int\ns: str\nif int():\n    n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\nif isinstance(x, int):\n    n = x\n    s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n\n[case testSimpleIsinstance2]\nimport typing\ndef f(x: object, n: int, s: str) -> None:\n    if int():\n        n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n        if isinstance(x, int):\n            n = x\n            s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testSimpleIsinstance3]\nclass A:\n    x = None  # type: object\n    n = None  # type: int\n    s = None  # type: str\n    if int():\n        n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n    if isinstance(x, int):\n        n = x\n        s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    else:\n        n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testMultipleIsinstanceTests]\nimport typing\nclass A: pass\nclass B(A): pass\ndef f(x: object, a: A, b: B, c: int) -> None:\n    if isinstance(x, A):\n        if isinstance(x, B):\n            b = x\n            x = a\n        a = x\n        c = x # E: Incompatible types in assignment (expression has type \"A\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testMultipleIsinstanceTests2]\nimport typing\nclass A: pass\nclass B(A): pass\ndef f(x: object, y: object, n: int, s: str) -> None:\n    if isinstance(x, int):\n        if isinstance(y, str):\n            n = x\n            s = y\n            s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n            n = y # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        s = y # E: Incompatible types in assignment (expression has type \"object\", variable has type \"str\")\n        n = y # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n        n = x\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceAndElif]\nimport typing\ndef f(x: object, n: int, s: str) -> None:\n    if int():\n        n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n        if isinstance(x, int):\n            n = x\n            s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        elif isinstance(x, str):\n            s = x\n            n = x # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        else:\n            n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n            s = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"str\")\n        n = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceAndAnyType]\nfrom typing import Any\ndef f(x: Any, n: int, s: str) -> None:\n    if int():\n        s = x\n        if isinstance(x, int):\n            n = x\n            s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        s = x\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceAndGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]):\n    def f(self, x: T) -> None: pass\ndef f(x: object) -> None:\n    if isinstance(x, C):\n        x.f(1)\n        x.f('')\n        x.g() # E: \"C[Any]\" has no attribute \"g\"\n    x.g() # E: \"object\" has no attribute \"g\"\n[builtins fixtures/isinstance.pyi]\n[out]\n"
  },
  {
    "path": "test-data/unit/check-type-object-type-inference.test",
    "content": "[case testInferTupleType]\n# flags: --python-version 3.9\nfrom typing import TypeVar, Generic, Type\nfrom abc import abstractmethod\nimport types  # Explicitly bring in stubs for 'types'\n\nT = TypeVar('T')\nclass E(Generic[T]):\n    @abstractmethod\n    def e(self, t: T) -> str:\n        ...\n\nclass F:\n    @abstractmethod\n    def f(self, tp: Type[T]) -> E[T]:\n        ...\n\ndef g(f: F):\n    f.f(int).e(7)\n    f.f(tuple[int,str])\n    f.f(tuple[int,str]).e('x')  # E: Argument 1 to \"e\" of \"E\" has incompatible type \"str\"; expected \"Tuple[int, str]\"\n    f.f(tuple[int,str]).e( (7,8) )  # E: Argument 1 to \"e\" of \"E\" has incompatible type \"Tuple[int, int]\"; expected \"Tuple[int, str]\"\n    f.f(tuple[int,str]).e( (7,'x') )  # OK\n    reveal_type(f.f(tuple[int,str]).e)  # N: Revealed type is \"def (t: Tuple[builtins.int, builtins.str]) -> builtins.str\"\n\ndef h(f: F):\n    f.f(int).e(7)\n    f.f(tuple)\n    f.f(tuple).e('y') # E: Argument 1 to \"e\" of \"E\" has incompatible type \"str\"; expected \"Tuple[Any, ...]\"\n    f.f(tuple).e( (8,'y') )  # OK\n    reveal_type(f.f(tuple).e)  # N: Revealed type is \"def (t: builtins.tuple[Any, ...]) -> builtins.str\"\n\ndef i(f: F):\n    f.f(tuple[int,tuple[int,str]])\n    f.f(tuple[int,tuple[int,str]]).e('z')  # E: Argument 1 to \"e\" of \"E\" has incompatible type \"str\"; expected \"Tuple[int, Tuple[int, str]]\"\n    f.f(tuple[int,tuple[int,str]]).e( (8,9) )  # E: Argument 1 to \"e\" of \"E\" has incompatible type \"Tuple[int, int]\"; expected \"Tuple[int, Tuple[int, str]]\"\n    f.f(tuple[int,tuple[int,str]]).e( (17, (28, 29)) )  # E: Argument 1 to \"e\" of \"E\" has incompatible type \"Tuple[int, Tuple[int, int]]\"; expected \"Tuple[int, Tuple[int, str]]\"\n    f.f(tuple[int,tuple[int,str]]).e( (27,(28,'z')) )  # OK\n    reveal_type(f.f(tuple[int,tuple[int,str]]).e)  # N: Revealed type is \"def (t: Tuple[builtins.int, Tuple[builtins.int, builtins.str]]) -> builtins.str\"\n\nx = tuple[int,str][str]  # False negative\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-type-promotion.test",
    "content": "-- Test cases for type promotion (e.g. int -> float).\n\n\n[case testPromoteIntToFloat]\ndef f(x: float) -> None: pass\nf(1)\n[builtins fixtures/primitives.pyi]\n\n[case testCantPromoteFloatToInt]\ndef f(x: int) -> None: pass\nf(1.1) # E: Argument 1 to \"f\" has incompatible type \"float\"; expected \"int\"\n[builtins fixtures/primitives.pyi]\n\n[case testPromoteFloatToComplex]\ndef f(x: complex) -> None: pass\nf(1)\n[builtins fixtures/primitives.pyi]\n\n[case testPromoteIntToComplex]\ndef f(x: complex) -> None: pass\nf(1)\n[builtins fixtures/primitives.pyi]\n\n[case testPromoteBytearrayToByte]\ndef f(x: bytes) -> None: pass\nf(bytearray(b''))\n[builtins fixtures/primitives.pyi]\n\n[case testPromoteMemoryviewToBytes]\ndef f(x: bytes) -> None: pass\nf(memoryview(b''))\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingDownFromPromoteTargetType]\ny = 0.0\ny = 1\ny() # E: \"int\" not callable\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingDownFromPromoteTargetType2]\ny = 0.0\ny = 1\ny.x # E: \"int\" has no attribute \"x\"\n[builtins fixtures/primitives.pyi]\n\n[case testTypePromotionsDontInterfereWithProtocols]\nfrom typing import TypeVar, Union, Protocol\n\nclass SupportsFloat(Protocol):\n    def __float__(self) -> float: pass\n\nT = TypeVar('T')\ndef f(x: Union[SupportsFloat, T]) -> Union[SupportsFloat, T]: pass\nf(0)  # should not crash\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testIntersectionUsingPromotion1]\n# flags: --warn-unreachable\nfrom typing import Union\n\nx: complex\nreveal_type(x)  # N: Revealed type is \"builtins.complex\"\nif isinstance(x, int):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.complex\"\nreveal_type(x)  # N: Revealed type is \"builtins.complex\"\n\ny: Union[int, float]\nif isinstance(y, float):\n    reveal_type(y)  # N: Revealed type is \"builtins.float\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(y)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\n\nif isinstance(y, int):\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion2]\n# flags: --warn-unreachable\nx: complex\nreveal_type(x)  # N: Revealed type is \"builtins.complex\"\nif isinstance(x, (int, float)):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.complex\"\n\n# Note we make type precise, since type promotions are involved\nreveal_type(x)  # N: Revealed type is \"builtins.complex\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion3]\n# flags: --warn-unreachable\nx: object\nif isinstance(x, int) and isinstance(x, complex):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nif isinstance(x, complex) and isinstance(x, int):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion4]\n# flags: --warn-unreachable\nx: object\nif isinstance(x, int):\n    if isinstance(x, complex):\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\nif isinstance(x, complex):\n    if isinstance(x, int):\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.complex\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion5]\n# flags: --warn-unreachable\nfrom typing import Union\n\nx: Union[float, complex]\nif isinstance(x, int):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.float, builtins.complex]\"\nreveal_type(x)  # N: Revealed type is \"Union[builtins.float, builtins.complex]\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion6]\n# flags: --warn-unreachable\nfrom typing import Union\n\nx: Union[str, complex]\nif isinstance(x, int):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.complex]\"\nreveal_type(x)  # N: Revealed type is \"Union[builtins.str, builtins.complex]\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion7]\n# flags: --warn-unreachable\nfrom typing import Union\n\nx: Union[int, float, complex]\nif isinstance(x, int):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.float, builtins.complex]\"\n\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float, builtins.complex]\"\n\nif isinstance(x, float):\n    reveal_type(x)  # N: Revealed type is \"builtins.float\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.complex]\"\n\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float, builtins.complex]\"\n\nif isinstance(x, complex):\n    reveal_type(x)  # N: Revealed type is \"builtins.complex\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\n\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float, builtins.complex]\"\n[builtins fixtures/primitives.pyi]\n\n[case testIntersectionUsingPromotion8]\n# flags: --warn-unreachable\nfrom typing import Union\n\nx: Union[int, float, complex]\nif isinstance(x, (int, float)):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.complex\"\nif isinstance(x, (int, complex)):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.complex]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.float\"\nif isinstance(x, (float, complex)):\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.float, builtins.complex]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testRejectPromotionsForProtocols]\nfrom typing import Protocol\n\nclass H(Protocol):\n    def hex(self, /) -> str: ...\n\nf: H = 1.0\no: H = object()  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"H\")\nc: H = 1j   # E: Incompatible types in assignment (expression has type \"complex\", variable has type \"H\")\ni: H = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"H\")\nb: H = False  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"H\")\n\nclass N(float): ...\nn: H = N()\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typeddict.test",
    "content": "-- Create Instance\n\n[case testCanCreateTypedDictInstanceWithKeywordArguments]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(x=42, y=1337)\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\n# Use values() to check fallback value type.\nreveal_type(p.values()) # N: Revealed type is \"typing.Iterable[builtins.object]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[targets __main__]\n\n[case testCanCreateTypedDictInstanceWithDictCall]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\n# Use values() to check fallback value type.\nreveal_type(p.values()) # N: Revealed type is \"typing.Iterable[builtins.object]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCanCreateTypedDictInstanceWithDictLiteral]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point({'x': 42, 'y': 1337})\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\n# Use values() to check fallback value type.\nreveal_type(p.values()) # N: Revealed type is \"typing.Iterable[builtins.object]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCanCreateTypedDictInstanceWithNoArguments]\nfrom typing import TypeVar, Union\nfrom mypy_extensions import TypedDict\nEmptyDict = TypedDict('EmptyDict', {})\np = EmptyDict()\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.EmptyDict', {})\"\nreveal_type(p.values()) # N: Revealed type is \"typing.Iterable[builtins.object]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n-- Create Instance (Errors)\n\n[case testCannotCreateTypedDictInstanceWithUnknownArgumentPattern]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(42, 1337)  # E: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictInstanceNonLiteralItemName]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nx = 'x'\np = Point({x: 42, 'y': 1337})  # E: Expected TypedDict key to be string literal\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictInstanceWithExtraItems]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(x=42, y=1337, z=666)  # E: Extra key \"z\" for TypedDict \"Point\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictInstanceWithMissingItems]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(x=42)  # E: Missing key \"y\" for TypedDict \"Point\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictInstanceWithIncompatibleItemType]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(x='meaning_of_life', y=1337)  # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictInstanceWithInlineTypedDict]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {\n    'x': TypedDict('E', {  # E: Use dict literal for nested TypedDict\n        'y': int\n    })\n})\n[builtins fixtures/dict.pyi]\n\n-- Define TypedDict (Class syntax)\n\n[case testCanCreateTypedDictWithClass]\nfrom mypy_extensions import TypedDict\n\nclass Point(TypedDict):\n    x: int\n    y: int\n\np = Point(x=42, y=1337)\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCanCreateTypedDictWithSubclass]\nfrom mypy_extensions import TypedDict\n\nclass Point1D(TypedDict):\n    x: int\nclass Point2D(Point1D):\n    y: int\nr: Point1D\np: Point2D\nreveal_type(r)  # N: Revealed type is \"TypedDict('__main__.Point1D', {'x': builtins.int})\"\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCanCreateTypedDictWithSubclass2]\nfrom mypy_extensions import TypedDict\n\nclass Point1D(TypedDict):\n    x: int\nclass Point2D(TypedDict, Point1D): # We also allow to include TypedDict in bases, it is simply ignored at runtime\n    y: int\n\np: Point2D\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCanCreateTypedDictClassEmpty]\nfrom mypy_extensions import TypedDict\n\nclass EmptyDict(TypedDict):\n    pass\n\np = EmptyDict()\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.EmptyDict', {})\"\n[builtins fixtures/dict.pyi]\n\n\n[case testCanCreateTypedDictWithClassOldVersion]\n# Test that we can use class-syntax to merge function-based TypedDicts\n\nfrom mypy_extensions import TypedDict\n\nMovieBase1 = TypedDict(\n    'MovieBase1', {'name': str, 'year': int})\nMovieBase2 = TypedDict(\n    'MovieBase2', {'based_on': str}, total=False)\n\nclass Movie(MovieBase1, MovieBase2):\n    pass\n\ndef foo(x):\n    # type: (Movie) -> None\n    pass\n\nfoo({})  # E: Missing keys (\"name\", \"year\") for TypedDict \"Movie\"\nfoo({'name': 'lol', 'year': 2009, 'based_on': 0})  # E: Incompatible types (expression has type \"int\", TypedDict item \"based_on\" has type \"str\")\n\n[builtins fixtures/dict.pyi]\n\n-- Define TypedDict (Class syntax errors)\n\n[case testCannotCreateTypedDictWithClassOtherBases]\nfrom mypy_extensions import TypedDict\n\nclass A: pass\n\nclass Point1D(TypedDict, A): # E: All bases of a new TypedDict must be TypedDict types\n    x: int\nclass Point2D(Point1D, A): # E: All bases of a new TypedDict must be TypedDict types\n    y: int\n\np: Point2D\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictWithDuplicateBases]\n# https://github.com/python/mypy/issues/3673\nfrom typing import TypedDict\n\nclass A(TypedDict):\n    x: str\n    y: int\n\nclass B(A, A): # E: Duplicate base class \"A\"\n    z: str\n\nclass C(TypedDict, TypedDict): # E: Duplicate base class \"TypedDict\"\n    c1: int\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCannotCreateTypedDictWithClassWithOtherStuff]\nfrom mypy_extensions import TypedDict\n\nclass Point(TypedDict):\n    x: int\n    y: int = 1 # E: Right hand side values are not supported in TypedDict\n    def f(): pass # E: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n    z = int # E: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n\np = Point(x=42, y=1337, z='whatever')\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int, 'z': Any})\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictWithClassWithFunctionUsedToCrash]\n# https://github.com/python/mypy/issues/11079\nfrom typing import TypedDict\nclass D(TypedDict):\n    y: int\n    def x(self, key: int):  # E: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n        pass\n\nd = D(y=1)\nreveal_type(d)  # N: Revealed type is \"TypedDict('__main__.D', {'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCannotCreateTypedDictWithDecoratedFunction]\n# flags: --disallow-any-expr\n# https://github.com/python/mypy/issues/13066\nfrom typing import TypedDict\nclass D(TypedDict):\n    @classmethod  # E: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n    def m(self) -> D:\n        pass\nd = D()\nreveal_type(d)  # N: Revealed type is \"TypedDict('__main__.D', {})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n-- This will crash under based mode\n-- [case testTypedDictWithClassmethodAlternativeConstructorDoesNotCrash]\n-- # https://github.com/python/mypy/issues/5653\n-- from typing import TypedDict\n\n-- class Foo(TypedDict):\n--     bar: str\n--     @classmethod  # E: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n--     def baz(cls) -> \"Foo\": ...\n-- [builtins fixtures/dict.pyi]\n-- [typing fixtures/typing-typeddict.pyi]\n\n[case testCanCreateTypedDictTypeWithUnderscoreItemName]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int, '_fallback': object})\n[builtins fixtures/dict.pyi]\n\n[case testCanCreateTypedDictWithClassUnderscores]\nfrom mypy_extensions import TypedDict\n\nclass Point(TypedDict):\n    x: int\n    _y: int\n\np: Point\nreveal_type(p) # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, '_y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictWithDuplicateKey1]\nfrom mypy_extensions import TypedDict\n\nclass Bad(TypedDict):\n    x: int\n    x: str # E: Duplicate TypedDict key \"x\"\n\nb: Bad\nreveal_type(b) # N: Revealed type is \"TypedDict('__main__.Bad', {'x': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictWithDuplicateKey2]\nfrom typing import TypedDict\n\nD1 = TypedDict(\"D1\", {\n    \"x\": int,\n    \"x\": int,  # E: Duplicate TypedDict key \"x\"\n})\nD2 = TypedDict(\"D2\", {\"x\": int, \"x\": str})  # E: Duplicate TypedDict key \"x\"\n\nd1: D1\nd2: D2\nreveal_type(d1) # N: Revealed type is \"TypedDict('__main__.D1', {'x': builtins.int})\"\nreveal_type(d2) # N: Revealed type is \"TypedDict('__main__.D2', {'x': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCanCreateTypedDictWithClassOverwriting]\nfrom mypy_extensions import TypedDict\n\nclass Point1(TypedDict):\n    x: int\nclass Point2(TypedDict):\n    x: float\nclass Bad(Point1, Point2): # E: Overwriting TypedDict field \"x\" while merging\n    pass\n\nb: Bad\nreveal_type(b) # N: Revealed type is \"TypedDict('__main__.Bad', {'x': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCanCreateTypedDictWithClassOverwriting2]\nfrom mypy_extensions import TypedDict\n\nclass Point1(TypedDict):\n    x: int\nclass Point2(Point1):\n    x: float # E: Overwriting TypedDict field \"x\" while extending\n\np2: Point2\nreveal_type(p2) # N: Revealed type is \"TypedDict('__main__.Point2', {'x': builtins.float})\"\n[builtins fixtures/dict.pyi]\n\n\n-- Subtyping\n\n[case testCanConvertTypedDictToItself]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\ndef identity(p: Point) -> Point:\n    return p\n[builtins fixtures/dict.pyi]\n\n[case testCanConvertTypedDictToEquivalentTypedDict]\nfrom mypy_extensions import TypedDict\nPointA = TypedDict('PointA', {'x': int, 'y': int})\nPointB = TypedDict('PointB', {'x': int, 'y': int})\ndef identity(p: PointA) -> PointB:\n    return p\n[builtins fixtures/dict.pyi]\n\n[case testCannotConvertTypedDictToSimilarTypedDictWithNarrowerItemTypes]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object})\ndef convert(op: ObjectPoint) -> Point:\n    return op  # E: Incompatible return value type (got \"ObjectPoint\", expected \"Point\")\n[builtins fixtures/dict.pyi]\n\n[case testCannotConvertTypedDictToSimilarTypedDictWithWiderItemTypes]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object})\ndef convert(p: Point) -> ObjectPoint:\n    return p  # E: Incompatible return value type (got \"Point\", expected \"ObjectPoint\")\n[builtins fixtures/dict.pyi]\n\n[case testCannotConvertTypedDictToSimilarTypedDictWithIncompatibleItemTypes]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nChameleon = TypedDict('Chameleon', {'x': str, 'y': str})\ndef convert(p: Point) -> Chameleon:\n    return p  # E: Incompatible return value type (got \"Point\", expected \"Chameleon\")\n[builtins fixtures/dict.pyi]\n\n[case testCanConvertTypedDictToNarrowerTypedDict]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nPoint1D = TypedDict('Point1D', {'x': int})\ndef narrow(p: Point) -> Point1D:\n    return p\n[builtins fixtures/dict.pyi]\n\n[case testCannotConvertTypedDictToWiderTypedDict]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nPoint3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int})\ndef widen(p: Point) -> Point3D:\n    return p  # E: Incompatible return value type (got \"Point\", expected \"Point3D\")\n[builtins fixtures/dict.pyi]\n\n[case testCanConvertTypedDictToCompatibleMapping]\nfrom mypy_extensions import TypedDict\nfrom typing import Mapping\nPoint = TypedDict('Point', {'x': int, 'y': int})\ndef as_mapping(p: Point) -> Mapping[str, object]:\n    return p\n[builtins fixtures/dict.pyi]\n\n[case testCannotConvertTypedDictToIncompatibleMapping]\nfrom mypy_extensions import TypedDict\nfrom typing import Mapping\nPoint = TypedDict('Point', {'x': int, 'y': int})\ndef as_mapping(p: Point) -> Mapping[str, int]:\n    return p  # E: Incompatible return value type (got \"Point\", expected \"Mapping[str, int]\")\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictAcceptsIntForFloatDuckTypes]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, Mapping\nPoint = TypedDict('Point', {'x': float, 'y': float})\ndef create_point() -> Point:\n    return Point(x=1, y=2)\nreveal_type(Point(x=1, y=2))  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.float, 'y': builtins.float})\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictDoesNotAcceptsFloatForInt]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, Mapping\nPoint = TypedDict('Point', {'x': int, 'y': int})\ndef create_point() -> Point:\n    return Point(x=1.2, y=2.5)\n[out]\nmain:5: error: Incompatible types (expression has type \"float\", TypedDict item \"x\" has type \"int\")\nmain:5: error: Incompatible types (expression has type \"float\", TypedDict item \"y\" has type \"int\")\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictAcceptsAnyType]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, Mapping\nPoint = TypedDict('Point', {'x': float, 'y': float})\ndef create_point(something: Any) -> Point:\n    return Point({\n      'x': something.x,\n      'y': something.y\n    })\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictValueTypeContext]\nfrom mypy_extensions import TypedDict\nfrom typing import List\nD = TypedDict('D', {'x': List[int]})\nreveal_type(D(x=[]))  # N: Revealed type is \"TypedDict('__main__.D', {'x': builtins.list[builtins.int]})\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotConvertTypedDictToDictOrMutableMapping]\nfrom mypy_extensions import TypedDict\nfrom typing import Dict, MutableMapping\nPoint = TypedDict('Point', {'x': int, 'y': int})\ndef as_dict(p: Point) -> Dict[str, int]:\n    return p  # E: Incompatible return value type (got \"Point\", expected \"Dict[str, int]\")\ndef as_mutable_mapping(p: Point) -> MutableMapping[str, object]:\n    return p  # E: Incompatible return value type (got \"Point\", expected \"MutableMapping[str, object]\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testCanConvertTypedDictToAny]\nfrom mypy_extensions import TypedDict\nfrom typing import Any\nPoint = TypedDict('Point', {'x': int, 'y': int})\ndef unprotect(p: Point) -> Any:\n    return p\n[builtins fixtures/dict.pyi]\n\n[case testAnonymousTypedDictInErrorMessages]\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str})\nB = TypedDict('B', {'x': int, 'z': str, 'a': int})\nC = TypedDict('C', {'x': int, 'z': str, 'a': str})\na: A\nb: B\nc: C\n\ndef f(a: A) -> None: pass\n\nl = [a, b]  # Join generates an anonymous TypedDict\nf(l) # E: Argument 1 to \"f\" has incompatible type \"List[TypedDict({'x': int})]\"; expected \"A\"\nll = [b, c]\nf(ll) # E: Argument 1 to \"f\" has incompatible type \"List[TypedDict({'x': int, 'z': str})]\"; expected \"A\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictWithSimpleProtocol]\nfrom typing_extensions import Protocol, TypedDict\n\nclass StrObjectMap(Protocol):\n    def __getitem__(self, key: str) -> object: ...\nclass StrIntMap(Protocol):\n    def __getitem__(self, key: str) -> int: ...\n\nA = TypedDict('A', {'x': int, 'y': int})\nB = TypedDict('B', {'x': int, 'y': str})\n\ndef fun(arg: StrObjectMap) -> None: ...\ndef fun2(arg: StrIntMap) -> None: ...\na: A\nb: B\nfun(a)\nfun(b)\nfun2(a) # Error\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\nmain:17: error: Argument 1 to \"fun2\" has incompatible type \"A\"; expected \"StrIntMap\"\nmain:17: note: Following member(s) of \"A\" have conflicts:\nmain:17: note:     Expected:\nmain:17: note:         def __getitem__(self, str, /) -> int\nmain:17: note:     Got:\nmain:17: note:         def __getitem__(self, str, /) -> object\n\n[case testTypedDictWithSimpleProtocolInference]\nfrom typing_extensions import Protocol, TypedDict\nfrom typing import TypeVar\n\nT_co = TypeVar('T_co', covariant=True)\nT = TypeVar('T')\n\nclass StrMap(Protocol[T_co]):\n    def __getitem__(self, key: str) -> T_co: ...\n\nA = TypedDict('A', {'x': int, 'y': int})\nB = TypedDict('B', {'x': int, 'y': str})\n\ndef fun(arg: StrMap[T]) -> T:\n    return arg['whatever']\na: A\nb: B\nreveal_type(fun(a))  # N: Revealed type is \"builtins.object\"\nreveal_type(fun(b))  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n-- Join\n\n[case testJoinOfTypedDictHasOnlyCommonKeysAndNewFallback]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\nPoint3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int})\np1 = TaggedPoint(type='2d', x=0, y=0)\np2 = Point3D(x=1, y=1, z=1)\njoined_points = [p1, p2][0]\nreveal_type(p1.values())   # N: Revealed type is \"typing.Iterable[builtins.object]\"\nreveal_type(p2.values())   # N: Revealed type is \"typing.Iterable[builtins.object]\"\nreveal_type(joined_points)  # N: Revealed type is \"TypedDict({'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testJoinOfTypedDictRemovesNonequivalentKeys]\nfrom mypy_extensions import TypedDict\nCellWithInt = TypedDict('CellWithInt', {'value': object, 'meta': int})\nCellWithObject = TypedDict('CellWithObject', {'value': object, 'meta': object})\nc1 = CellWithInt(value=1, meta=42)\nc2 = CellWithObject(value=2, meta='turtle doves')\njoined_cells = [c1, c2]\nreveal_type(c1)             # N: Revealed type is \"TypedDict('__main__.CellWithInt', {'value': builtins.object, 'meta': builtins.int})\"\nreveal_type(c2)             # N: Revealed type is \"TypedDict('__main__.CellWithObject', {'value': builtins.object, 'meta': builtins.object})\"\nreveal_type(joined_cells)   # N: Revealed type is \"builtins.list[TypedDict({'value': builtins.object})]\"\n[builtins fixtures/dict.pyi]\n\n[case testJoinOfDisjointTypedDictsIsEmptyTypedDict]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\nCell = TypedDict('Cell', {'value': object})\nd1 = Point(x=0, y=0)\nd2 = Cell(value='pear tree')\njoined_dicts = [d1, d2]\nreveal_type(d1)             # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\nreveal_type(d2)             # N: Revealed type is \"TypedDict('__main__.Cell', {'value': builtins.object})\"\nreveal_type(joined_dicts)   # N: Revealed type is \"builtins.list[TypedDict({})]\"\n[builtins fixtures/dict.pyi]\n\n[case testJoinOfTypedDictWithCompatibleMappingIsMapping]\nfrom mypy_extensions import TypedDict\nfrom typing import Mapping\nCell = TypedDict('Cell', {'value': int})\nleft = Cell(value=42)\nright = {'score': 999}  # type: Mapping[str, int]\njoined1 = [left, right]\njoined2 = [right, left]\nreveal_type(joined1)  # N: Revealed type is \"builtins.list[typing.Mapping[builtins.str, builtins.object]]\"\nreveal_type(joined2)  # N: Revealed type is \"builtins.list[typing.Mapping[builtins.str, builtins.object]]\"\n[builtins fixtures/dict.pyi]\n\n[case testJoinOfTypedDictWithCompatibleMappingSupertypeIsSupertype]\nfrom mypy_extensions import TypedDict\nfrom typing import Sized\nCell = TypedDict('Cell', {'value': int})\nleft = Cell(value=42)\nright: Sized\njoined1 = [left, right]\njoined2 = [right, left]\nreveal_type(joined1)  # N: Revealed type is \"builtins.list[typing.Sized]\"\nreveal_type(joined2)  # N: Revealed type is \"builtins.list[typing.Sized]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testJoinOfTypedDictWithIncompatibleTypeIsObject]\nfrom mypy_extensions import TypedDict\nfrom typing import Mapping\nCell = TypedDict('Cell', {'value': int})\nleft = Cell(value=42)\nright = 42\njoined1 = [left, right]\njoined2 = [right, left]\nreveal_type(joined1)  # N: Revealed type is \"builtins.list[builtins.object]\"\nreveal_type(joined2)  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/dict.pyi]\n\n\n-- Meet\n\n[case testMeetOfTypedDictsWithCompatibleCommonKeysHasAllKeysAndNewFallback]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable\nXY = TypedDict('XY', {'x': int, 'y': int})\nYZ = TypedDict('YZ', {'y': int, 'z': int})\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: XY, y: YZ) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"TypedDict({'x': builtins.int, 'y': builtins.int, 'z': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictsWithIncompatibleCommonKeysIsUninhabited]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable\nXYa = TypedDict('XYa', {'x': int, 'y': int})\nYbZ = TypedDict('YbZ', {'y': object, 'z': int})\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: XYa, y: YbZ) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"Never\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable\nX = TypedDict('X', {'x': int})\nZ = TypedDict('Z', {'z': int})\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: X, y: Z) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"TypedDict({'x': builtins.int, 'z': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n# TODO: It would be more accurate for the meet to be TypedDict instead.\n[case testMeetOfTypedDictWithCompatibleMappingIsUninhabitedForNow]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable, Mapping\nX = TypedDict('X', {'x': int})\nM = Mapping[str, int]\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: X, y: M) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"Never\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictWithIncompatibleMappingIsUninhabited]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable, Mapping\nX = TypedDict('X', {'x': int})\nM = Mapping[str, str]\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: X, y: M) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"Never\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictWithCompatibleMappingSuperclassIsUninhabitedForNow]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable, Iterable\nX = TypedDict('X', {'x': int})\nI = Iterable[str]\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: X, y: I) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"TypedDict('__main__.X', {'x': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictsWithNonTotal]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable\nXY = TypedDict('XY', {'x': int, 'y': int}, total=False)\nYZ = TypedDict('YZ', {'y': int, 'z': int}, total=False)\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: XY, y: YZ) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"TypedDict({'x'?: builtins.int, 'y'?: builtins.int, 'z'?: builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictsWithNonTotalAndTotal]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable\nXY = TypedDict('XY', {'x': int}, total=False)\nYZ = TypedDict('YZ', {'y': int, 'z': int})\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: XY, y: YZ) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"TypedDict({'x'?: builtins.int, 'y': builtins.int, 'z': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testMeetOfTypedDictsWithIncompatibleNonTotalAndTotal]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar, Callable\nXY = TypedDict('XY', {'x': int, 'y': int}, total=False)\nYZ = TypedDict('YZ', {'y': int, 'z': int})\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: XY, y: YZ) -> None: pass\nreveal_type(f(g)) # N: Revealed type is \"Never\"\n[builtins fixtures/dict.pyi]\n\n\n-- Constraint Solver\n\n[case testTypedDictConstraintsAgainstIterable]\nfrom typing import TypeVar, Iterable\nfrom mypy_extensions import TypedDict\nT = TypeVar('T')\ndef f(x: Iterable[T]) -> T: pass\nA = TypedDict('A', {'x': int})\na: A\nreveal_type(f(a)) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n-- TODO: Figure out some way to trigger the ConstraintBuilderVisitor.visit_typeddict_type() path.\n\n\n-- Special Method: __getitem__\n\n[case testCanGetItemOfTypedDictWithValidStringLiteralKey]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\nreveal_type(p['type'])  # N: Revealed type is \"builtins.str\"\nreveal_type(p['x'])     # N: Revealed type is \"builtins.int\"\nreveal_type(p['y'])     # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotGetItemOfTypedDictWithInvalidStringLiteralKey]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np: TaggedPoint\np['typ']  # E: TypedDict \"TaggedPoint\" has no key \"typ\" \\\n          # N: Did you mean \"type\"?\n[builtins fixtures/dict.pyi]\n\n[case testCannotGetItemOfAnonymousTypedDictWithInvalidStringLiteralKey]\nfrom typing import TypeVar\nfrom mypy_extensions import TypedDict\nA = TypedDict('A', {'x': str, 'y': int, 'z': str})\nB = TypedDict('B', {'x': str, 'z': int})\nC = TypedDict('C', {'x': str, 'y': int, 'z': int})\nT = TypeVar('T')\ndef join(x: T, y: T) -> T: return x\nab = join(A(x='', y=1, z=''), B(x='', z=1))\nac = join(A(x='', y=1, z=''), C(x='', y=0, z=1))\nab['y']  # E: \"y\" is not a valid TypedDict key; expected one of (\"x\")\nac['a']  # E: \"a\" is not a valid TypedDict key; expected one of (\"x\", \"y\")\n[builtins fixtures/dict.pyi]\n\n[case testCannotGetItemOfTypedDictWithNonLiteralKey]\nfrom mypy_extensions import TypedDict\nfrom typing import Union\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\ndef get_coordinate(p: TaggedPoint, key: str) -> Union[str, int]:\n    return p[key]  # E: TypedDict key must be a string literal; expected one of (\"type\", \"x\", \"y\")\n[builtins fixtures/dict.pyi]\n\n\n-- Special Method: __setitem__\n\n[case testCanSetItemOfTypedDictWithValidStringLiteralKeyAndCompatibleValueType]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\np['type'] = 'two_d'\np['x'] = 1\n[builtins fixtures/dict.pyi]\n\n[case testCannotSetItemOfTypedDictWithIncompatibleValueType]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\np['x'] = 'y'  # E: Value of \"x\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotSetItemOfTypedDictWithInvalidStringLiteralKey]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\np['z'] = 1  # E: TypedDict \"TaggedPoint\" has no key \"z\"\n[builtins fixtures/dict.pyi]\n\n[case testCannotSetItemOfTypedDictWithNonLiteralKey]\nfrom mypy_extensions import TypedDict\nfrom typing import Union\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\ndef set_coordinate(p: TaggedPoint, key: str, value: int) -> None:\n    p[key] = value  # E: TypedDict key must be a string literal; expected one of (\"type\", \"x\", \"y\")\n[builtins fixtures/dict.pyi]\n\n\n-- isinstance\n\n[case testTypedDictWithIsInstanceAndIsSubclass]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int})\nd: object\nif isinstance(d, D):   # E: Cannot use isinstance() with TypedDict type\n    reveal_type(d)     # N: Revealed type is \"TypedDict('__main__.D', {'x': builtins.int})\"\nissubclass(object, D)  # E: Cannot use issubclass() with TypedDict type\n[builtins fixtures/isinstancelist.pyi]\n\n\n-- Scoping\n\n[case testTypedDictInClassNamespace]\n# https://github.com/python/mypy/pull/2553#issuecomment-266474341\nfrom mypy_extensions import TypedDict\nclass C:\n    def f(self):\n        A = TypedDict('A', {'x': int})\n    def g(self):\n        A = TypedDict('A', {'y': int})\nC.A  # E: \"Type[C]\" has no attribute \"A\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictInFunction]\nfrom mypy_extensions import TypedDict\ndef f() -> None:\n    A = TypedDict('A', {'x': int})\nA  # E: Name \"A\" is not defined\n[builtins fixtures/dict.pyi]\n\n\n-- Union simplification / proper subtype checks\n\n[case testTypedDictUnionSimplification]\nfrom typing import TypeVar, Union, Any, cast\nfrom mypy_extensions import TypedDict\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\nC = TypedDict('C', {'a': int})\nD = TypedDict('D', {'a': int, 'b': int})\nE = TypedDict('E', {'a': str})\nF = TypedDict('F', {'x': int})\nG = TypedDict('G', {'a': Any})\n\nc = C(a=1)\nd = D(a=1, b=1)\ne = E(a='')\nf = F(x=1)\ng = G(a=cast(Any, 1))  # Work around #2610\n\nreveal_type(u(d, d)) # N: Revealed type is \"TypedDict('__main__.D', {'a': builtins.int, 'b': builtins.int})\"\nreveal_type(u(c, d)) # N: Revealed type is \"TypedDict('__main__.C', {'a': builtins.int})\"\nreveal_type(u(d, c)) # N: Revealed type is \"TypedDict('__main__.C', {'a': builtins.int})\"\nreveal_type(u(c, e)) # N: Revealed type is \"Union[TypedDict('__main__.E', {'a': builtins.str}), TypedDict('__main__.C', {'a': builtins.int})]\"\nreveal_type(u(e, c)) # N: Revealed type is \"Union[TypedDict('__main__.C', {'a': builtins.int}), TypedDict('__main__.E', {'a': builtins.str})]\"\nreveal_type(u(c, f)) # N: Revealed type is \"Union[TypedDict('__main__.F', {'x': builtins.int}), TypedDict('__main__.C', {'a': builtins.int})]\"\nreveal_type(u(f, c)) # N: Revealed type is \"Union[TypedDict('__main__.C', {'a': builtins.int}), TypedDict('__main__.F', {'x': builtins.int})]\"\nreveal_type(u(c, g)) # N: Revealed type is \"Union[TypedDict('__main__.G', {'a': Any}), TypedDict('__main__.C', {'a': builtins.int})]\"\nreveal_type(u(g, c)) # N: Revealed type is \"Union[TypedDict('__main__.C', {'a': builtins.int}), TypedDict('__main__.G', {'a': Any})]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictUnionSimplification2]\nfrom typing import TypeVar, Union, Mapping, Any\nfrom mypy_extensions import TypedDict\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\nC = TypedDict('C', {'a': int, 'b': int})\n\nc = C(a=1, b=1)\nm_s_o: Mapping[str, object]\nm_s_s: Mapping[str, str]\nm_i_i: Mapping[int, int]\nm_s_a: Mapping[str, Any]\n\nreveal_type(u(c, m_s_o)) # N: Revealed type is \"typing.Mapping[builtins.str, builtins.object]\"\nreveal_type(u(m_s_o, c)) # N: Revealed type is \"typing.Mapping[builtins.str, builtins.object]\"\nreveal_type(u(c, m_s_s)) # N: Revealed type is \"Union[typing.Mapping[builtins.str, builtins.str], TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})]\"\nreveal_type(u(c, m_i_i)) # N: Revealed type is \"Union[typing.Mapping[builtins.int, builtins.int], TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})]\"\nreveal_type(u(c, m_s_a)) # N: Revealed type is \"Union[typing.Mapping[builtins.str, Any], TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictUnionUnambiguousCase]\nfrom typing import Union, Mapping, Any, cast\nfrom typing_extensions import TypedDict, Literal\n\nA = TypedDict('A', {'@type': Literal['a-type'], 'a': str})\nB = TypedDict('B', {'@type': Literal['b-type'], 'b': int})\n\nc: Union[A, B]\nreveal_type(c) # N: Revealed type is \"Union[TypedDict('__main__.A', {'@type': Literal['a-type'], 'a': builtins.str}), TypedDict('__main__.B', {'@type': Literal['b-type'], 'b': builtins.int})]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictUnionAmbiguousCaseBothMatch]\nfrom typing import Union, Mapping, Any, cast\nfrom typing_extensions import TypedDict, Literal\n\nA = TypedDict('A', {'@type': Literal['a-type'], 'value': str})\nB = TypedDict('B', {'@type': Literal['b-type'], 'value': str})\n\nc: Union[A, B] = {'@type': 'a-type', 'value': 'Test'}\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictUnionAmbiguousCaseNoMatch]\nfrom typing import Union, Mapping, Any, cast\nfrom typing_extensions import TypedDict, Literal\n\nA = TypedDict('A', {'@type': Literal['a-type'], 'value': int})\nB = TypedDict('B', {'@type': Literal['b-type'], 'value': int})\n\nc: Union[A, B] = {'@type': 'a-type', 'value': 'Test'}  # E: Type of TypedDict is ambiguous, none of (\"A\", \"B\") matches cleanly \\\n                                                       # E: Incompatible types in assignment (expression has type \"Dict[str, str]\", variable has type \"Union[A, B]\")\n[builtins fixtures/dict.pyi]\n\n-- Use dict literals\n\n[case testTypedDictDictLiterals]\nfrom mypy_extensions import TypedDict\n\nPoint = TypedDict('Point', {'x': int, 'y': int})\n\ndef f(p: Point) -> None:\n    if int():\n        p = {'x': 2, 'y': 3}\n        p = {'x': 2}  # E: Missing key \"y\" for TypedDict \"Point\"\n        p = dict(x=2, y=3)\n\nf({'x': 1, 'y': 3})\nf({'x': 1, 'y': 'z'})  # E: Incompatible types (expression has type \"str\", TypedDict item \"y\" has type \"int\")\n\nf(dict(x=1, y=3))\nf(dict(x=1, y=3, z=4))  # E: Extra key \"z\" for TypedDict \"Point\"\nf(dict(x=1, y=3, z=4, a=5))  # E: Extra keys (\"z\", \"a\") for TypedDict \"Point\"\n\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictExplicitTypes]\nfrom mypy_extensions import TypedDict\n\nPoint = TypedDict('Point', {'x': int, 'y': int})\n\np1a: Point = {'x': 'hi'}  # E: Missing key \"y\" for TypedDict \"Point\"\np1b: Point = {}           # E: Missing keys (\"x\", \"y\") for TypedDict \"Point\"\n\np2: Point\np2 = dict(x='bye')  # E: Missing key \"y\" for TypedDict \"Point\"\n\np3 = Point(x=1, y=2)\nif int():\n    p3 = {'x': 'hi'}  # E: Missing key \"y\" for TypedDict \"Point\"\n\np4: Point = {'x': 1, 'y': 2}\n\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithExtraItems]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar\nA = TypedDict('A', {'x': int, 'y': int})\nB = TypedDict('B', {'x': int, 'y': str})\nT = TypeVar('T')\ndef join(x: T, y: T) -> T: return x\nab = join(A(x=1, y=1), B(x=1, y=''))\nif int():\n    ab = {'x': 1, 'z': 1} # E: Expected TypedDict key \"x\" but found keys (\"x\", \"z\")\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithMissingItems]\nfrom mypy_extensions import TypedDict\nfrom typing import TypeVar\nA = TypedDict('A', {'x': int, 'y': int, 'z': int})\nB = TypedDict('B', {'x': int, 'y': int, 'z': str})\nT = TypeVar('T')\ndef join(x: T, y: T) -> T: return x\nab = join(A(x=1, y=1, z=1), B(x=1, y=1, z=''))\nif int():\n    ab = {} # E: Expected TypedDict keys (\"x\", \"y\") but found no keys\n[builtins fixtures/dict.pyi]\n\n\n-- Other TypedDict methods\n\n[case testTypedDictGetMethod]\nfrom mypy_extensions import TypedDict\nclass A: pass\nD = TypedDict('D', {'x': int, 'y': str})\nd: D\nreveal_type(d.get('x')) # N: Revealed type is \"Union[builtins.int, None]\"\nreveal_type(d.get('y')) # N: Revealed type is \"Union[builtins.str, None]\"\nreveal_type(d.get('x', A())) # N: Revealed type is \"Union[builtins.int, __main__.A]\"\nreveal_type(d.get('x', 1)) # N: Revealed type is \"builtins.int\"\nreveal_type(d.get('y', None)) # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictGetMethodTypeContext]\nfrom typing import List\nfrom mypy_extensions import TypedDict\nclass A: pass\nD = TypedDict('D', {'x': List[int], 'y': int})\nd: D\nreveal_type(d.get('x', [])) # N: Revealed type is \"builtins.list[builtins.int]\"\nd.get('x', ['x']) # E: List item 0 has incompatible type \"str\"; expected \"int\"\na = ['']\nreveal_type(d.get('x', a)) # N: Revealed type is \"Union[builtins.list[builtins.int], builtins.list[builtins.str]]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictGetMethodInvalidArgs]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str})\nd: D\nd.get() # E: All overload variants of \"get\" of \"Mapping\" require at least one argument \\\n        # N: Possible overload variants: \\\n        # N:     def get(self, k: str) -> object \\\n        # N:     def [V] get(self, k: str, default: object) -> object\nd.get('x', 1, 2) # E: No overload variant of \"get\" of \"Mapping\" matches argument types \"str\", \"int\", \"int\" \\\n                 # N: Possible overload variants: \\\n                 # N:     def get(self, k: str) -> object \\\n                 # N:     def [V] get(self, k: str, default: Union[int, V]) -> object\nx = d.get('z')\nreveal_type(x) # N: Revealed type is \"builtins.object\"\ns = ''\ny = d.get(s)\nreveal_type(y) # N: Revealed type is \"builtins.object\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictMissingMethod]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str})\nd: D\nd.bad(1) # E: \"D\" has no attribute \"bad\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictChainedGetMethodWithDictFallback]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str})\nE = TypedDict('E', {'d': D})\np = E(d=D(x=0, y=''))\nreveal_type(p.get('d', {'x': 1, 'y': ''})) # N: Revealed type is \"TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictGetDefaultParameterStillTypeChecked]\nfrom mypy_extensions import TypedDict\nTaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})\np = TaggedPoint(type='2d', x=42, y=1337)\np.get('x', 1 + 'y')     # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictChainedGetWithEmptyDictDefault]\nfrom mypy_extensions import TypedDict\nC = TypedDict('C', {'a': int})\nD = TypedDict('D', {'x': C, 'y': str})\nd: D\nreveal_type(d.get('x', {})) \\\n    # N: Revealed type is \"TypedDict('__main__.C', {'a'?: builtins.int})\"\nreveal_type(d.get('x', None)) \\\n    # N: Revealed type is \"Union[TypedDict('__main__.C', {'a': builtins.int}), None]\"\nreveal_type(d.get('x', {}).get('a')) # N: Revealed type is \"Union[builtins.int, None]\"\nreveal_type(d.get('x', {})['a']) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n-- Totality (the \"total\" keyword argument)\n\n[case testTypedDictWithTotalTrue]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str}, total=True)\nd: D\nreveal_type(d) \\\n    # N: Revealed type is \"TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictWithInvalidTotalArgument]\nfrom mypy_extensions import TypedDict\nA = TypedDict('A', {'x': int}, total=0) # E: \"total\" argument must be a True or False literal\nB = TypedDict('B', {'x': int}, total=bool) # E: \"total\" argument must be a True or False literal\nC = TypedDict('C', {'x': int}, x=False) # E: Unexpected keyword argument \"x\" for \"TypedDict\"\nD = TypedDict('D', {'x': int}, False) # E: Unexpected arguments to TypedDict()\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictWithTotalFalse]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str}, total=False)\ndef f(d: D) -> None:\n    reveal_type(d) # N: Revealed type is \"TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})\"\nf({})\nf({'x': 1})\nf({'y': ''})\nf({'x': 1, 'y': ''})\nf({'x': 1, 'z': ''}) # E: Extra key \"z\" for TypedDict \"D\"\nf({'x': ''}) # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictConstructorWithTotalFalse]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str}, total=False)\ndef f(d: D) -> None: pass\nreveal_type(D()) # N: Revealed type is \"TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})\"\nreveal_type(D(x=1)) # N: Revealed type is \"TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})\"\nf(D(y=''))\nf(D(x=1, y=''))\nf(D(x=1, z='')) # E: Extra key \"z\" for TypedDict \"D\"\nf(D(x='')) # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictIndexingWithNonRequiredKey]\nfrom mypy_extensions import TypedDict\nD = TypedDict('D', {'x': int, 'y': str}, total=False)\nd: D\nreveal_type(d['x']) # N: Revealed type is \"builtins.int\"\nreveal_type(d['y']) # N: Revealed type is \"builtins.str\"\nreveal_type(d.get('x')) # N: Revealed type is \"Union[builtins.int, None]\"\nreveal_type(d.get('y')) # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictSubtypingWithTotalFalse]\nfrom mypy_extensions import TypedDict\nA = TypedDict('A', {'x': int})\nB = TypedDict('B', {'x': int}, total=False)\nC = TypedDict('C', {'x': int, 'y': str}, total=False)\ndef fa(a: A) -> None: pass\ndef fb(b: B) -> None: pass\ndef fc(c: C) -> None: pass\na: A\nb: B\nc: C\nfb(b)\nfc(c)\nfb(c)\nfb(a) # E: Argument 1 to \"fb\" has incompatible type \"A\"; expected \"B\"\nfa(b) # E: Argument 1 to \"fa\" has incompatible type \"B\"; expected \"A\"\nfc(b) # E: Argument 1 to \"fc\" has incompatible type \"B\"; expected \"C\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictJoinWithTotalFalse]\nfrom typing import TypeVar\nfrom mypy_extensions import TypedDict\nA = TypedDict('A', {'x': int})\nB = TypedDict('B', {'x': int}, total=False)\nC = TypedDict('C', {'x': int, 'y': str}, total=False)\nT = TypeVar('T')\ndef j(x: T, y: T) -> T: return x\na: A\nb: B\nc: C\nreveal_type(j(a, b)) \\\n    # N: Revealed type is \"TypedDict({})\"\nreveal_type(j(b, b)) \\\n    # N: Revealed type is \"TypedDict({'x'?: builtins.int})\"\nreveal_type(j(c, c)) \\\n    # N: Revealed type is \"TypedDict({'x'?: builtins.int, 'y'?: builtins.str})\"\nreveal_type(j(b, c)) \\\n    # N: Revealed type is \"TypedDict({'x'?: builtins.int})\"\nreveal_type(j(c, b)) \\\n    # N: Revealed type is \"TypedDict({'x'?: builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictClassWithTotalArgument]\nfrom mypy_extensions import TypedDict\nclass D(TypedDict, total=False):\n    x: int\n    y: str\nd: D\nreveal_type(d) # N: Revealed type is \"TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictClassWithInvalidTotalArgument]\nfrom mypy_extensions import TypedDict\nclass D(TypedDict, total=1): # E: \"total\" argument must be a True or False literal\n    x: int\nclass E(TypedDict, total=bool): # E: \"total\" argument must be a True or False literal\n    x: int\nclass F(TypedDict, total=xyz): # E: Name \"xyz\" is not defined \\\n                               # E: \"total\" argument must be a True or False literal\n    x: int\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictClassInheritanceWithTotalArgument]\nfrom mypy_extensions import TypedDict\nclass A(TypedDict):\n    x: int\nclass B(TypedDict, A, total=False):\n    y: int\nclass C(TypedDict, B, total=True):\n    z: str\nc: C\nreveal_type(c) # N: Revealed type is \"TypedDict('__main__.C', {'x': builtins.int, 'y'?: builtins.int, 'z': builtins.str})\"\n[builtins fixtures/dict.pyi]\n\n[case testNonTotalTypedDictInErrorMessages]\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str}, total=False)\nB = TypedDict('B', {'x': int, 'z': str, 'a': int}, total=False)\nC = TypedDict('C', {'x': int, 'z': str, 'a': str}, total=False)\na: A\nb: B\nc: C\n\ndef f(a: A) -> None: pass\n\nl = [a, b]  # Join generates an anonymous TypedDict\nf(l) # E: Argument 1 to \"f\" has incompatible type \"List[TypedDict({'x'?: int})]\"; expected \"A\"\nll = [b, c]\nf(ll) # E: Argument 1 to \"f\" has incompatible type \"List[TypedDict({'x'?: int, 'z'?: str})]\"; expected \"A\"\n[builtins fixtures/dict.pyi]\n\n[case testNonTotalTypedDictCanBeEmpty]\n# flags: --warn-unreachable\nfrom mypy_extensions import TypedDict\n\nclass A(TypedDict):\n    ...\n\nclass B(TypedDict, total=False):\n    x: int\n\na: A = {}\nb: B = {}\n\nif not a:\n    reveal_type(a) # N: Revealed type is \"TypedDict('__main__.A', {})\"\n\nif not b:\n    reveal_type(b) # N: Revealed type is \"TypedDict('__main__.B', {'x'?: builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n-- Create Type (Errors)\n\n[case testCannotCreateTypedDictTypeWithTooFewArguments]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point')  # E: Too few arguments for TypedDict()\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithTooManyArguments]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int}, dict)  # E: Unexpected arguments to TypedDict()\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithInvalidName]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict(dict, {'x': int, 'y': int})  # E: TypedDict() expects a string literal as the first argument\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithInvalidItems]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x'})  # E: TypedDict() expects a dictionary literal as the second argument\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithKwargs]\nfrom mypy_extensions import TypedDict\nd = {'x': int, 'y': int}\nPoint = TypedDict('Point', {**d})  # E: Invalid TypedDict() field name\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithBytes]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict(b'Point', {'x': int, 'y': int})  # E: TypedDict() expects a string literal as the first argument\n# This technically works at runtime but doesn't make sense.\nPoint2 = TypedDict('Point2', {b'x': int})  # E: Invalid TypedDict() field name\n[builtins fixtures/dict.pyi]\n\n-- NOTE: The following code works at runtime but is not yet supported by mypy.\n--       Keyword arguments may potentially be supported in the future.\n[case testCannotCreateTypedDictTypeWithNonpositionalArgs]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict(typename='Point', fields={'x': int, 'y': int})  # E: Unexpected arguments to TypedDict()\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithInvalidItemName]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {int: int, int: int})  # E: Invalid TypedDict() field name\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithInvalidItemType]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': 1, 'y': 1})  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead? \\\n                                              # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?\n[builtins fixtures/dict.pyi]\n\n[case testCannotCreateTypedDictTypeWithInvalidName2]\nfrom mypy_extensions import TypedDict\nX = TypedDict('Y', {'x': int})  # E: First argument \"Y\" to TypedDict() does not match variable name \"X\"\n[builtins fixtures/dict.pyi]\n\n\n-- Overloading\n\n[case testTypedDictOverloading]\nfrom typing import overload, Iterable\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int})\n\n@overload\ndef f(x: Iterable[str]) -> str: ...\n@overload\ndef f(x: int) -> int: ...\ndef f(x): pass\n\na: A\nreveal_type(f(a))  # N: Revealed type is \"builtins.str\"\nreveal_type(f(1))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverloading2]\nfrom typing import overload, Iterable\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int})\n\n@overload\ndef f(x: Iterable[int]) -> None: ...\n@overload\ndef f(x: int) -> None: ...\ndef f(x): pass\n\na: A\nf(a)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\nmain:13: error: Argument 1 to \"f\" has incompatible type \"A\"; expected \"Iterable[int]\"\nmain:13: note: Following member(s) of \"A\" have conflicts:\nmain:13: note:     Expected:\nmain:13: note:         def __iter__(self) -> Iterator[int]\nmain:13: note:     Got:\nmain:13: note:         def __iter__(self) -> Iterator[str]\n\n[case testTypedDictOverloading3]\nfrom typing import overload\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int})\n\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> None: ...\ndef f(x): pass\n\na: A\nf(a)  # E: No overload variant of \"f\" matches argument type \"A\" \\\n      # N: Possible overload variants: \\\n      # N:     def f(x: str) -> None \\\n      # N:     def f(x: int) -> None\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverloading4]\nfrom typing import overload\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int})\nB = TypedDict('B', {'x': str})\n\n@overload\ndef f(x: A) -> int: ...\n@overload\ndef f(x: int) -> str: ...\ndef f(x): pass\n\na: A\nb: B\nreveal_type(f(a)) # N: Revealed type is \"builtins.int\"\nreveal_type(f(1)) # N: Revealed type is \"builtins.str\"\nf(b) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverloading5]\nfrom typing import overload\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int})\nB = TypedDict('B', {'y': str})\nC = TypedDict('C', {'y': int})\n\n@overload\ndef f(x: A) -> None: ...\n@overload\ndef f(x: B) -> None: ...\ndef f(x): pass\n\na: A\nb: B\nc: C\nf(a)\nf(b)\nf(c) # E: Argument 1 to \"f\" has incompatible type \"C\"; expected \"A\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverloading6]\nfrom typing import overload\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int})\nB = TypedDict('B', {'y': str})\n\n@overload\ndef f(x: A) -> int: ...\n@overload\ndef f(x: B) -> str: ...\ndef f(x): pass\n\na: A\nb: B\nreveal_type(f(a)) # N: Revealed type is \"builtins.int\"\nreveal_type(f(b)) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n-- Special cases\n\n[case testForwardReferenceInTypedDict]\nfrom typing import Mapping\nfrom mypy_extensions import TypedDict\nX = TypedDict('X', {'b': 'B', 'c': 'C'})\nclass B: pass\nclass C(B): pass\nx: X\nreveal_type(x) # N: Revealed type is \"TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})\"\nm1: Mapping[str, object] = x\nm2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type \"X\", variable has type \"Mapping[str, B]\")\n[builtins fixtures/dict.pyi]\n\n[case testForwardReferenceInClassTypedDict]\nfrom typing import Mapping\nfrom mypy_extensions import TypedDict\nclass X(TypedDict):\n    b: 'B'\n    c: 'C'\nclass B: pass\nclass C(B): pass\nx: X\nreveal_type(x) # N: Revealed type is \"TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})\"\nm1: Mapping[str, object] = x\nm2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type \"X\", variable has type \"Mapping[str, B]\")\n[builtins fixtures/dict.pyi]\n\n[case testForwardReferenceToTypedDictInTypedDict]\nfrom typing import Mapping\nfrom mypy_extensions import TypedDict\nX = TypedDict('X', {'a': 'A'})\nA = TypedDict('A', {'b': int})\nx: X\nreveal_type(x) # N: Revealed type is \"TypedDict('__main__.X', {'a': TypedDict('__main__.A', {'b': builtins.int})})\"\nreveal_type(x['a']['b']) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testSelfRecursiveTypedDictInheriting]\nfrom mypy_extensions import TypedDict\n\ndef test() -> None:\n    class MovieBase(TypedDict):\n        name: str\n        year: int\n\n    class Movie(MovieBase):\n        director: 'Movie' # E: Cannot resolve name \"Movie\" (possible cyclic definition) \\\n                          # N: Recursive types are not allowed at function scope\n    m: Movie\n    reveal_type(m['director']['name']) # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n\n[case testSubclassOfRecursiveTypedDict]\nfrom typing import List\nfrom mypy_extensions import TypedDict\n\ndef test() -> None:\n    class Command(TypedDict):\n        subcommands: List['Command']  # E: Cannot resolve name \"Command\" (possible cyclic definition) \\\n                                      # N: Recursive types are not allowed at function scope\n\n    class HelpCommand(Command):\n        pass\n\n    hc = HelpCommand(subcommands=[])\n    reveal_type(hc)  # N: Revealed type is \"TypedDict('__main__.HelpCommand@8', {'subcommands': builtins.list[Any]})\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testTypedDictForwardAsUpperBound]\nfrom typing import TypeVar, Generic\nfrom mypy_extensions import TypedDict\nT = TypeVar('T', bound='M')\nclass G(Generic[T]):\n    x: T\n\nyb: G[int] # E: Type argument \"int\" of \"G\" must be a subtype of \"M\"\nyg: G[M]\nz: int = G[M]().x['x']  # type: ignore[used-before-def]\n\nclass M(TypedDict):\n    x: int\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testTypedDictWithImportCycleForward]\nimport a\n[file a.py]\nfrom mypy_extensions import TypedDict\nfrom b import f\n\nN = TypedDict('N', {'a': str})\n[file b.py]\nimport a\n\ndef f(x: a.N) -> None:\n    reveal_type(x)\n    reveal_type(x['a'])\n[builtins fixtures/dict.pyi]\n[out]\ntmp/b.py:4: note: Revealed type is \"TypedDict('a.N', {'a': builtins.str})\"\ntmp/b.py:5: note: Revealed type is \"builtins.str\"\n\n[case testTypedDictImportCycle]\n\nimport b\n[file a.py]\nclass C:\n    pass\n\nfrom b import tp\nx: tp\nreveal_type(x['x'])  # N: Revealed type is \"builtins.int\"\n\nreveal_type(tp)  # N: Revealed type is \"def (*, x: builtins.int) -> TypedDict('b.tp', {'x': builtins.int})\"\ntp(x='no')  # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\n\n[file b.py]\nfrom a import C\nfrom mypy_extensions import TypedDict\n\ntp = TypedDict('tp', {'x': int})\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testTypedDictAsStarStarArg]\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str})\nclass B: pass\n\ndef f1(x: int, y: str) -> None: ...\ndef f2(x: int, y: int) -> None: ...\ndef f3(x: B, y: str) -> None: ...\ndef f4(x: int) -> None: pass\ndef f5(x: int, y: str, z: int) -> None: pass\ndef f6(x: int, z: str) -> None: pass\n\na: A\nf1(**a)\nf2(**a) # E: Argument \"y\" to \"f2\" has incompatible type \"str\"; expected \"int\"\nf3(**a) # E: Argument \"x\" to \"f3\" has incompatible type \"int\"; expected \"B\"\nf4(**a) # E: Extra argument \"y\" from **args for \"f4\"\nf5(**a) # E: Missing positional arguments \"y\", \"z\" in call to \"f5\"\nf6(**a) # E: Extra argument \"y\" from **args for \"f6\"\nf1(1, **a) # E: \"f1\" gets multiple values for keyword argument \"x\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypedDictAsStarStarArgConstraints]\nfrom typing import TypeVar, Union\nfrom mypy_extensions import TypedDict\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef f1(x: T, y: S) -> Union[T, S]: ...\n\nA = TypedDict('A', {'y': int, 'x': str})\na: A\nreveal_type(f1(**a)) # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypedDictAsStarStarArgCalleeKwargs]\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str})\nB = TypedDict('B', {'x': str, 'y': str})\n\ndef f(**kwargs: str) -> None: ...\ndef g(x: int, **kwargs: str) -> None: ...\n\na: A\nb: B\nf(**a) # E: Argument 1 to \"f\" has incompatible type \"**A\"; expected \"str\"\nf(**b)\ng(**a)\ng(**b) # E: Argument \"x\" to \"g\" has incompatible type \"str\"; expected \"int\"\ng(1, **a) # E: \"g\" gets multiple values for keyword argument \"x\"\ng(1, **b) # E: \"g\" gets multiple values for keyword argument \"x\" \\\n          # E: Argument \"x\" to \"g\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictAsStarStarTwice]\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': str})\nB = TypedDict('B', {'z': bytes})\nC = TypedDict('C', {'x': str, 'z': bytes})\n\ndef f1(x: int, y: str, z: bytes) -> None: ...\ndef f2(x: int, y: float, z: bytes) -> None: ...\ndef f3(x: int, y: str, z: float) -> None: ...\n\na: A\nb: B\nc: C\nf1(**a, **b)\nf1(**b, **a)\nf2(**a, **b) # E: Argument \"y\" to \"f2\" has incompatible type \"str\"; expected \"float\"\nf3(**a, **b) # E: Argument \"z\" to \"f3\" has incompatible type \"bytes\"; expected \"float\"\nf3(**b, **a) # E: Argument \"z\" to \"f3\" has incompatible type \"bytes\"; expected \"float\"\nf1(**a, **c) # E: \"f1\" gets multiple values for keyword argument \"x\" \\\n             # E: Argument \"x\" to \"f1\" has incompatible type \"str\"; expected \"int\"\nf1(**c, **a) # E: \"f1\" gets multiple values for keyword argument \"x\" \\\n             # E: Argument \"x\" to \"f1\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypedDictAsStarStarAndDictAsStarStar]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, Dict\n\nTD = TypedDict('TD', {'x': int, 'y': str})\n\ndef f1(x: int, y: str, z: bytes) -> None: ...\ndef f2(x: int, y: str) -> None: ...\n\ntd: TD\nd: Dict[Any, Any]\n\nf1(**td, **d)\nf1(**d, **td)\nf2(**td, **d)\nf2(**d, **td)\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictNonMappingMethods]\nfrom typing import List\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': List[int]})\na: A\n\nreveal_type(a.copy()) # N: Revealed type is \"TypedDict('__main__.A', {'x': builtins.int, 'y': builtins.list[builtins.int]})\"\na.has_key('x') # E: \"A\" has no attribute \"has_key\"\n# TODO: Better error message\na.clear() # E: \"A\" has no attribute \"clear\"\n\na.setdefault('invalid', 1) # E: TypedDict \"A\" has no key \"invalid\"\nreveal_type(a.setdefault('x', 1)) # N: Revealed type is \"builtins.int\"\nreveal_type(a.setdefault('y', [])) # N: Revealed type is \"builtins.list[builtins.int]\"\na.setdefault('y', '') # E: Argument 2 to \"setdefault\" of \"TypedDict\" has incompatible type \"str\"; expected \"List[int]\"\nx = ''\na.setdefault(x, 1) # E: Expected TypedDict key to be string literal\nalias = a.setdefault\nalias(x, 1) # E: Argument 1 has incompatible type \"str\"; expected \"Never\"\n\na.update({})\na.update({'x': 1})\na.update({'x': ''}) # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\na.update({'x': 1, 'y': []})\na.update({'x': 1, 'y': [1]})\na.update({'z': 1}) # E: Unexpected TypedDict key \"z\"\na.update({'z': 1, 'zz': 1}) # E: Unexpected TypedDict keys (\"z\", \"zz\")\na.update({'z': 1, 'x': 1}) # E: Expected TypedDict key \"x\" but found keys (\"z\", \"x\")\nd = {'x': 1}\na.update(d) # E: Argument 1 to \"update\" of \"TypedDict\" has incompatible type \"Dict[str, int]\"; expected \"TypedDict({'x'?: int, 'y'?: List[int]})\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictPopMethod]\nfrom typing import List\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': List[int]}, total=False)\nB = TypedDict('B', {'x': int})\na: A\nb: B\n\nreveal_type(a.pop('x')) # N: Revealed type is \"builtins.int\"\nreveal_type(a.pop('y', [])) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(a.pop('x', '')) # N: Revealed type is \"Union[builtins.int, Literal['']?]\"\nreveal_type(a.pop('x', (1, 2))) # N: Revealed type is \"Union[builtins.int, Tuple[Literal[1]?, Literal[2]?]]\"\na.pop('invalid', '') # E: TypedDict \"A\" has no key \"invalid\"\nb.pop('x') # E: Key \"x\" of TypedDict \"B\" cannot be deleted\nx = ''\nb.pop(x) # E: Expected TypedDict key to be string literal\npop = b.pop\npop('x') # E: Argument 1 has incompatible type \"str\"; expected \"Never\"\npop('invalid') # E: Argument 1 has incompatible type \"str\"; expected \"Never\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictDel]\nfrom typing import List\nfrom mypy_extensions import TypedDict\n\nA = TypedDict('A', {'x': int, 'y': List[int]}, total=False)\nB = TypedDict('B', {'x': int})\na: A\nb: B\n\ndel a['x']\ndel a['invalid'] # E: TypedDict \"A\" has no key \"invalid\"\ndel b['x'] # E: Key \"x\" of TypedDict \"B\" cannot be deleted\ns = ''\ndel a[s] # E: Expected TypedDict key to be string literal\ndel b[s] # E: Expected TypedDict key to be string literal\nalias = b.__delitem__\nalias('x')\nalias(s)\n[builtins fixtures/dict.pyi]\n\n[case testPluginUnionsOfTypedDicts]\nfrom typing import Union\nfrom mypy_extensions import TypedDict\n\nclass TDA(TypedDict):\n    a: int\n    b: str\n\nclass TDB(TypedDict):\n    a: int\n    b: int\n    c: int\n\ntd: Union[TDA, TDB]\n\nreveal_type(td.get('a'))  # N: Revealed type is \"Union[builtins.int, None]\"\nreveal_type(td.get('b'))  # N: Revealed type is \"Union[builtins.str, None, builtins.int]\"\nreveal_type(td.get('c'))  # N: Revealed type is \"builtins.object\"\n\nreveal_type(td['a'])  # N: Revealed type is \"builtins.int\"\nreveal_type(td['b'])  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nreveal_type(td['c'])  # N: Revealed type is \"Union[Any, builtins.int]\" \\\n                      # E: TypedDict \"TDA\" has no key \"c\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testPluginUnionsOfTypedDictsNonTotal]\nfrom typing import Union\nfrom mypy_extensions import TypedDict\n\nclass TDA(TypedDict, total=False):\n    a: int\n    b: str\n\nclass TDB(TypedDict, total=False):\n    a: int\n    b: int\n    c: int\n\ntd: Union[TDA, TDB]\n\nreveal_type(td.pop('a'))  # N: Revealed type is \"builtins.int\"\nreveal_type(td.pop('b'))  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nreveal_type(td.pop('c'))  # N: Revealed type is \"Union[Any, builtins.int]\" \\\n                          # E: TypedDict \"TDA\" has no key \"c\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCanCreateTypedDictWithTypingExtensions]\nfrom typing_extensions import TypedDict\n\nclass Point(TypedDict):\n    x: int\n    y: int\n\np = Point(x=42, y=1337)\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testCanCreateTypedDictWithTypingProper]\nfrom typing import TypedDict\n\nclass Point(TypedDict):\n    x: int\n    y: int\n\np = Point(x=42, y=1337)\nreveal_type(p)  # N: Revealed type is \"TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOptionalUpdate]\nfrom typing import Union\nfrom mypy_extensions import TypedDict\n\nclass A(TypedDict):\n    x: int\n\nd: A\nd.update({'x': 1})\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictOverlapWithDict]\n# mypy: strict-equality\nfrom typing import TypedDict, Dict\n\nclass Config(TypedDict):\n    a: str\n    b: str\n\nx: Dict[str, str]\ny: Config\n\nx == y\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictNonOverlapping]\n# mypy: strict-equality\nfrom typing import TypedDict, Dict\n\nclass Config(TypedDict):\n    a: str\n    b: int\n\nx: Dict[str, str]\ny: Config\n\nx == y  # E: Non-overlapping equality check (left operand type: \"Dict[str, str]\", right operand type: \"Config\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictNonTotal]\n# mypy: strict-equality\nfrom typing import TypedDict, Dict\n\nclass Config(TypedDict, total=False):\n    a: str\n    b: int\n\nx: Dict[str, str]\ny: Config\n\nx == y\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictNonTotalNonOverlapping]\n# mypy: strict-equality\nfrom typing import TypedDict, Dict\n\nclass Config(TypedDict, total=False):\n    a: int\n    b: int\n\nx: Dict[str, str]\ny: Config\n\nx == y  # E: Non-overlapping equality check (left operand type: \"Dict[str, str]\", right operand type: \"Config\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictEmpty]\n# mypy: strict-equality\nfrom typing import TypedDict\n\nclass Config(TypedDict):\n    a: str\n    b: str\n\nx: Config\nx == {}  # E: Non-overlapping equality check (left operand type: \"Config\", right operand type: \"Dict[Never, Never]\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictNonTotalEmpty]\n# mypy: strict-equality\nfrom typing import TypedDict\n\nclass Config(TypedDict, total=False):\n    a: str\n    b: str\n\nx: Config\nx == {}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictNonStrKey]\n# mypy: strict-equality\nfrom typing import TypedDict, Dict, Union\n\nclass Config(TypedDict):\n    a: str\n    b: str\n\nx: Config\ny: Dict[Union[str, int], str]\nx == y\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictOverload]\nfrom typing import overload, TypedDict, Dict\n\nclass Map(TypedDict):\n    x: int\n    y: str\n\n@overload\ndef func(x: Map) -> int: ...\n@overload\ndef func(x: Dict[str, str]) -> str: ...\ndef func(x):\n    pass\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictOverloadBad]\nfrom typing import overload, TypedDict, Dict\n\nclass Map(TypedDict, total=False):\n    x: int\n    y: str\n\n@overload\ndef func(x: Map) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef func(x: Dict[str, str]) -> str: ...\ndef func(x):\n    pass\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictOverloadMappingBad]\nfrom typing import overload, TypedDict, Mapping\n\nclass Map(TypedDict, total=False):\n    x: int\n    y: str\n\n@overload\ndef func(x: Map) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef func(x: Mapping[str, str]) -> str: ...\ndef func(x):\n    pass\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictOverlapWithDictOverloadNonStrKey]\nfrom typing import overload, TypedDict, Dict\n\nclass Map(TypedDict):\n    x: str\n    y: str\n\n@overload\ndef func(x: Map) -> int: ...\n@overload\ndef func(x: Dict[int, str]) -> str: ...\ndef func(x):\n    pass\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictIsInstance]\nfrom typing import TypedDict, Union\n\nclass User(TypedDict):\n    id: int\n    name: str\n\nu: Union[str, User]\nu2: User\n\nif isinstance(u, dict):\n    reveal_type(u)  # N: Revealed type is \"TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})\"\nelse:\n    reveal_type(u)  # N: Revealed type is \"builtins.str\"\n\nassert isinstance(u2, dict)\nreveal_type(u2)  # N: Revealed type is \"TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictIsInstanceABCs]\nfrom typing import TypedDict, Union, Mapping, Iterable\n\nclass User(TypedDict):\n    id: int\n    name: str\n\nu: Union[int, User]\nu2: User\n\nif isinstance(u, Iterable):\n    reveal_type(u)  # N: Revealed type is \"TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})\"\nelse:\n    reveal_type(u)  # N: Revealed type is \"builtins.int\"\n\nassert isinstance(u2, Mapping)\nreveal_type(u2)  # N: Revealed type is \"TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypedDictLiteralTypeKeyInCreation]\nfrom typing import TypedDict, Final, Literal\n\nclass Value(TypedDict):\n    num: int\n\nnum: Final = 'num'\nv: Value = {num: 5}\nv = {num: ''}  # E: Incompatible types (expression has type \"str\", TypedDict item \"num\" has type \"int\")\n\nbad: Final = 2\nv = {bad: 3}  # E: Expected TypedDict key to be string literal\nunion: Literal['num', 'foo']\nv = {union: 2} # E: Expected TypedDict key to be string literal\nnum2: Literal['num']\nv = {num2: 2}\nbad2: Literal['bad']\nv = {bad2: 2}  # E: Missing key \"num\" for TypedDict \"Value\" \\\n               # E: Extra key \"bad\" for TypedDict \"Value\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testOperatorContainsNarrowsTypedDicts_unionWithList]\nfrom __future__ import annotations\nfrom typing import assert_type, TypedDict, Union\nfrom typing_extensions import final\n\n@final\nclass D(TypedDict):\n    foo: int\n\n\nd_or_list: D | list[str]\n\nif 'foo' in d_or_list:\n    assert_type(d_or_list, Union[D, list[str]])\nelif 'bar' in d_or_list:\n    assert_type(d_or_list, list[str])\nelse:\n    assert_type(d_or_list, list[str])\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testOperatorContainsNarrowsTypedDicts_total]\nfrom __future__ import annotations\nfrom typing import assert_type, Literal, TypedDict, TypeVar, Union\nfrom typing_extensions import final\n\n@final\nclass D1(TypedDict):\n    foo: int\n\n\n@final\nclass D2(TypedDict):\n    bar: int\n\n\nd: D1 | D2\n\nif 'foo' in d:\n    assert_type(d, D1)\nelse:\n    assert_type(d, D2)\n\nfoo_or_bar: Literal['foo', 'bar']\nif foo_or_bar in d:\n    assert_type(d, Union[D1, D2])\nelse:\n    assert_type(d, Union[D1, D2])\n\nfoo_or_invalid: Literal['foo', 'invalid']\nif foo_or_invalid in d:\n    assert_type(d, D1)\n    # won't narrow 'foo_or_invalid'\n    assert_type(foo_or_invalid, Literal['foo', 'invalid'])\nelse:\n    assert_type(d, Union[D1, D2])\n    # won't narrow 'foo_or_invalid'\n    assert_type(foo_or_invalid, Literal['foo', 'invalid'])\n\nTD = TypeVar('TD', D1, D2)\n\ndef f(arg: TD) -> None:\n    value: int\n    if 'foo' in arg:\n        assert_type(arg['foo'], int)\n    else:\n        assert_type(arg['bar'], int)\n\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testOperatorContainsNarrowsTypedDicts_final]\n# flags: --warn-unreachable\nfrom __future__ import annotations\nfrom typing import assert_type, TypedDict, Union\nfrom typing_extensions import final\n\n@final\nclass DFinal(TypedDict):\n    foo: int\n\n\nclass DNotFinal(TypedDict):\n    bar: int\n\n\nd_not_final: DNotFinal\n\nif 'bar' in d_not_final:\n    assert_type(d_not_final, DNotFinal)\nelse:\n    spam = 'ham'  # E: Statement is unreachable\n\nif 'spam' in d_not_final:\n    assert_type(d_not_final, DNotFinal)\nelse:\n    assert_type(d_not_final, DNotFinal)\n\nd_final: DFinal\n\nif 'spam' in d_final:\n    spam = 'ham'  # E: Statement is unreachable\nelse:\n    assert_type(d_final, DFinal)\n\nd_union: DFinal | DNotFinal\n\nif 'foo' in d_union:\n    assert_type(d_union, Union[DFinal, DNotFinal])\nelse:\n    assert_type(d_union, DNotFinal)\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse]\nfrom __future__ import annotations\nfrom typing import assert_type, Literal, TypedDict, Union\nfrom typing_extensions import final\n\n@final\nclass DTotal(TypedDict):\n    required_key: int\n\n\n@final\nclass DNotTotal(TypedDict, total=False):\n    optional_key: int\n\n\nd: DTotal | DNotTotal\n\nif 'required_key' in d:\n    assert_type(d, DTotal)\nelse:\n    assert_type(d, DNotTotal)\n\nif 'optional_key' in d:\n    assert_type(d, DNotTotal)\nelse:\n    assert_type(d, Union[DTotal, DNotTotal])\n\nkey: Literal['optional_key', 'required_key']\nif key in d:\n    assert_type(d, Union[DTotal, DNotTotal])\nelse:\n    assert_type(d, Union[DTotal, DNotTotal])\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired]\nfrom __future__ import annotations\nfrom typing import assert_type, Required, NotRequired, TypedDict, Union\nfrom typing_extensions import final\n\n@final\nclass D1(TypedDict):\n    required_key: Required[int]\n    optional_key: NotRequired[int]\n\n\n@final\nclass D2(TypedDict):\n    abc: int\n    xyz: int\n\n\nd: D1 | D2\n\nif 'required_key' in d:\n    assert_type(d, D1)\nelse:\n    assert_type(d, D2)\n\nif 'optional_key' in d:\n    assert_type(d, D1)\nelse:\n    assert_type(d, Union[D1, D2])\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCannotSubclassFinalTypedDict]\nfrom typing import TypedDict\nfrom typing_extensions import final\n\n@final\nclass DummyTypedDict(TypedDict):\n    int_val: int\n    float_val: float\n    str_val: str\n\nclass SubType(DummyTypedDict): # E: Cannot inherit from final class \"DummyTypedDict\"\n    pass\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCannotSubclassFinalTypedDictWithForwardDeclarations]\nfrom typing import TypedDict\nfrom typing_extensions import final\n\n@final\nclass DummyTypedDict(TypedDict):\n    forward_declared: \"ForwardDeclared\"\n\nclass SubType(DummyTypedDict): # E: Cannot inherit from final class \"DummyTypedDict\"\n    pass\n\nclass ForwardDeclared: pass\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictTypeNarrowingWithFinalKey]\nfrom typing import Final, Optional, TypedDict\n\nKEY_NAME: Final = \"bar\"\nclass Foo(TypedDict):\n    bar: Optional[str]\n\nfoo = Foo(bar=\"hello\")\nif foo[\"bar\"] is not None:\n    reveal_type(foo[\"bar\"])     # N: Revealed type is \"builtins.str\"\n    reveal_type(foo[KEY_NAME])  # N: Revealed type is \"builtins.str\"\nif foo[KEY_NAME] is not None:\n    reveal_type(foo[\"bar\"])     # N: Revealed type is \"builtins.str\"\n    reveal_type(foo[KEY_NAME])  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictDoubleForwardClass]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, List\n\nclass Foo(TypedDict):\n    bar: Bar\n    baz: Bar\n\nBar = List[Any]\n\nfoo: Foo\nreveal_type(foo['bar'])  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(foo['baz'])  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictDoubleForwardFunc]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, List\n\nFoo = TypedDict('Foo', {'bar': 'Bar', 'baz': 'Bar'})\n\nBar = List[Any]\n\nfoo: Foo\nreveal_type(foo['bar'])   # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(foo['baz'])  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictDoubleForwardMixed]\nfrom mypy_extensions import TypedDict\nfrom typing import Any, List\n\nBar = List[Any]\n\nclass Foo(TypedDict):\n    foo: Toto\n    bar: Bar\n    baz: Bar\n\nToto = int\n\nfoo: Foo\nreveal_type(foo['foo'])  # N: Revealed type is \"builtins.int\"\nreveal_type(foo['bar'])  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(foo['baz'])  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testAssignTypedDictAsAttribute]\nfrom typing import TypedDict\n\nclass A:\n    def __init__(self) -> None:\n        self.b = TypedDict('b', {'x': int, 'y': str})  # E: TypedDict type as attribute is not supported\n\nreveal_type(A().b)  # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictAsUpperBoundAndIndexedAssign]\nfrom typing import TypeVar, Generic, TypedDict\n\n\nclass BaseDict(TypedDict, total=False):\n    foo: int\n\n\n_DICT_T = TypeVar('_DICT_T', bound=BaseDict)\n\n\nclass SomeGeneric(Generic[_DICT_T]):\n    def __init__(self, data: _DICT_T) -> None:\n        self._data: _DICT_T = data\n\n    def set_state(self) -> None:\n        self._data['foo'] = 1\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictCreatedWithEmptyDict]\nfrom typing import TypedDict\n\nclass TD(TypedDict, total=False):\n    foo: int\n    bar: int\n\nd: TD = dict()\nd2: TD = dict(foo=1)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictBytesKey]\nfrom typing import TypedDict\n\nclass TD(TypedDict):\n    foo: int\n\nd: TD = {b'foo': 2} # E: Expected TypedDict key to be string literal\nd[b'foo'] = 3 # E: TypedDict key must be a string literal; expected one of (\"foo\") \\\n    # E: Argument 1 to \"__setitem__\" has incompatible type \"bytes\"; expected \"str\"\nd[b'foo'] # E: TypedDict key must be a string literal; expected one of (\"foo\")\nd[3] # E: TypedDict key must be a string literal; expected one of (\"foo\")\nd[True] # E: TypedDict key must be a string literal; expected one of (\"foo\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUppercaseKey]\nfrom mypy_extensions import TypedDict\n\nFoo = TypedDict('Foo', {'camelCaseKey': str})\nvalue: Foo = {}  # E: Missing key \"camelCaseKey\" for TypedDict \"Foo\"\n[builtins fixtures/dict.pyi]\n\n[case testTypedDictWithDeferredFieldTypeEval]\nfrom typing import Generic, TypeVar, TypedDict, NotRequired\n\nclass Foo(TypedDict):\n    y: NotRequired[int]\n    x: Outer[Inner[ForceDeferredEval]]\n\nvar: Foo\nreveal_type(var)  # N: Revealed type is \"TypedDict('__main__.Foo', {'y'?: builtins.int, 'x': __main__.Outer[__main__.Inner[__main__.ForceDeferredEval]]})\"\n\nT1 = TypeVar(\"T1\")\nclass Outer(Generic[T1]): pass\n\nT2 = TypeVar(\"T2\", bound=\"ForceDeferredEval\")\nclass Inner(Generic[T2]): pass\n\nclass ForceDeferredEval: pass\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictRequiredUnimportedAny]\n# flags: --disallow-any-unimported\nfrom typing import NotRequired, TypedDict, ReadOnly\nfrom nonexistent import Foo  # type: ignore[import-not-found]\nclass Bar(TypedDict):\n    foo: NotRequired[Foo]  # E: Type of variable becomes \"Any\" due to an unfollowed import\n    bar: ReadOnly[Foo]  # E: Type of variable becomes \"Any\" due to an unfollowed import\n    baz: NotRequired[ReadOnly[Foo]]  # E: Type of variable becomes \"Any\" due to an unfollowed import\n[typing fixtures/typing-typeddict.pyi]\n\n-- Required[]\n\n[case testDoesRecognizeRequiredInTypedDictWithClass]\nfrom typing import TypedDict\nfrom typing import Required\nclass Movie(TypedDict, total=False):\n    title: Required[str]\n    year: int\nm = Movie(title='The Matrix')\nm = Movie()  # E: Missing key \"title\" for TypedDict \"Movie\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesRecognizeRequiredInTypedDictWithAssignment]\nfrom typing import TypedDict\nfrom typing import Required\nMovie = TypedDict('Movie', {\n    'title': Required[str],\n    'year': int,\n}, total=False)\nm = Movie(title='The Matrix')\nm = Movie()  # E: Missing key \"title\" for TypedDict \"Movie\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesDisallowRequiredOutsideOfTypedDict]\nfrom typing import Required\nx: Required[int] = 42  # E: Required[] can be only used in a TypedDict definition\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesOnlyAllowRequiredInsideTypedDictAtTopLevel]\nfrom typing import TypedDict\nfrom typing import Union\nfrom typing import Required\nMovie = TypedDict('Movie', {\n    'title': Union[\n        Required[str],  # E: Required[] can be only used in a TypedDict definition\n        bytes\n    ],\n    'year': int,\n}, total=False)\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesDisallowRequiredInsideRequired]\nfrom typing import TypedDict\nfrom typing import Union\nfrom typing import Required\nMovie = TypedDict('Movie', {\n    'title': Required[Union[\n        Required[str],  # E: Required[] can be only used in a TypedDict definition\n        bytes\n    ]],\n    'year': int,\n}, total=False)\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRequiredOnlyAllowsOneItem]\nfrom typing import TypedDict\nfrom typing import Required\nclass Movie(TypedDict, total=False):\n    title: Required[str, bytes]  # E: Required[] must have exactly one type argument\n    year: int\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRequiredExplicitAny]\n# flags: --disallow-any-explicit\nfrom typing import TypedDict\nfrom typing import Required\nFoo = TypedDict(\"Foo\", {\"a.x\": Required[int]})\n[typing fixtures/typing-typeddict.pyi]\n\n-- NotRequired[]\n\n[case testDoesRecognizeNotRequiredInTypedDictWithClass]\nfrom typing import TypedDict\nfrom typing import NotRequired\nclass Movie(TypedDict):\n    title: str\n    year: NotRequired[int]\nm = Movie(title='The Matrix')\nm = Movie()  # E: Missing key \"title\" for TypedDict \"Movie\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesRecognizeNotRequiredInTypedDictWithAssignment]\nfrom typing import TypedDict\nfrom typing import NotRequired\nMovie = TypedDict('Movie', {\n    'title': str,\n    'year': NotRequired[int],\n})\nm = Movie(title='The Matrix')\nm = Movie()  # E: Missing key \"title\" for TypedDict \"Movie\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesDisallowNotRequiredOutsideOfTypedDict]\nfrom typing import NotRequired\nx: NotRequired[int] = 42  # E: NotRequired[] can be only used in a TypedDict definition\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesOnlyAllowNotRequiredInsideTypedDictAtTopLevel]\nfrom typing import TypedDict\nfrom typing import Union\nfrom typing import NotRequired\nMovie = TypedDict('Movie', {\n    'title': Union[\n        NotRequired[str],  # E: NotRequired[] can be only used in a TypedDict definition\n        bytes\n    ],\n    'year': int,\n})\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDoesDisallowNotRequiredInsideNotRequired]\nfrom typing import TypedDict\nfrom typing import Union\nfrom typing import NotRequired\nMovie = TypedDict('Movie', {\n    'title': NotRequired[Union[\n        NotRequired[str],  # E: NotRequired[] can be only used in a TypedDict definition\n        bytes\n    ]],\n    'year': int,\n})\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNotRequiredOnlyAllowsOneItem]\nfrom typing import TypedDict\nfrom typing import NotRequired\nclass Movie(TypedDict):\n    title: NotRequired[str, bytes]  # E: NotRequired[] must have exactly one type argument\n    year: int\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNotRequiredExplicitAny]\n# flags: --disallow-any-explicit\nfrom typing import TypedDict\nfrom typing import NotRequired\nFoo = TypedDict(\"Foo\", {\"a.x\": NotRequired[int]})\n[typing fixtures/typing-typeddict.pyi]\n\n-- Union dunders\n\n[case testTypedDictUnionGetItem]\nfrom typing import TypedDict, Union\n\nclass Foo1(TypedDict):\n    z: str\n    a: int\nclass Foo2(TypedDict):\n    z: str\n    b: int\n\ndef func(foo: Union[Foo1, Foo2]) -> str:\n    reveal_type(foo[\"z\"])  # N: Revealed type is \"builtins.str\"\n    # ok, but type is incorrect:\n    reveal_type(foo.__getitem__(\"z\"))  # N: Revealed type is \"builtins.object\"\n\n    reveal_type(foo[\"a\"])  # N: Revealed type is \"Union[builtins.int, Any]\" \\\n                           # E: TypedDict \"Foo2\" has no key \"a\"\n    reveal_type(foo[\"b\"])  # N: Revealed type is \"Union[Any, builtins.int]\" \\\n                           # E: TypedDict \"Foo1\" has no key \"b\"\n    reveal_type(foo[\"missing\"])  # N: Revealed type is \"Any\" \\\n                                 # E: TypedDict \"Foo1\" has no key \"missing\" \\\n                                 # E: TypedDict \"Foo2\" has no key \"missing\"\n    reveal_type(foo[1])  # N: Revealed type is \"Any\" \\\n                         # E: TypedDict key must be a string literal; expected one of (\"z\", \"a\") \\\n                         # E: TypedDict key must be a string literal; expected one of (\"z\", \"b\")\n\n    return foo[\"z\"]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testTypedDictUnionSetItem]\nfrom typing import TypedDict, Union\n\nclass Foo1(TypedDict):\n    z: str\n    a: int\nclass Foo2(TypedDict):\n    z: str\n    b: int\n\ndef func(foo: Union[Foo1, Foo2]):\n    foo[\"z\"] = \"a\"  # ok\n    foo.__setitem__(\"z\", \"a\")  # ok\n\n    foo[\"z\"] = 1  # E: Value of \"z\" has incompatible type \"int\"; expected \"str\"\n\n    foo[\"a\"] = 1  # E: TypedDict \"Foo2\" has no key \"a\"\n    foo[\"b\"] = 2  # E: TypedDict \"Foo1\" has no key \"b\"\n\n    foo[\"missing\"] = 1  # E: TypedDict \"Foo1\" has no key \"missing\" \\\n                        # E: TypedDict \"Foo2\" has no key \"missing\"\n    foo[1] = \"m\"  # E: TypedDict key must be a string literal; expected one of (\"z\", \"a\") \\\n                  # E: TypedDict key must be a string literal; expected one of (\"z\", \"b\") \\\n                  # E: Argument 1 to \"__setitem__\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testTypedDictUnionDelItem]\nfrom typing import TypedDict, Union\n\nclass Foo1(TypedDict):\n    z: str\n    a: int\nclass Foo2(TypedDict):\n    z: str\n    b: int\n\ndef func(foo: Union[Foo1, Foo2]):\n    del foo[\"z\"]  # E: Key \"z\" of TypedDict \"Foo1\" cannot be deleted \\\n                  # E: Key \"z\" of TypedDict \"Foo2\" cannot be deleted\n    foo.__delitem__(\"z\")  # E: Key \"z\" of TypedDict \"Foo1\" cannot be deleted \\\n                          # E: Key \"z\" of TypedDict \"Foo2\" cannot be deleted\n\n    del foo[\"a\"]  # E: Key \"a\" of TypedDict \"Foo1\" cannot be deleted \\\n                  # E: TypedDict \"Foo2\" has no key \"a\"\n    del foo[\"b\"]  # E: TypedDict \"Foo1\" has no key \"b\" \\\n                  # E: Key \"b\" of TypedDict \"Foo2\" cannot be deleted\n\n    del foo[\"missing\"]  # E: TypedDict \"Foo1\" has no key \"missing\" \\\n                        # E: TypedDict \"Foo2\" has no key \"missing\"\n    del foo[1]  # E: Argument 1 to \"__delitem__\" has incompatible type \"int\"; expected \"str\" \\\n                # E: Expected TypedDict key to be string literal\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testTypedDictTypeVarUnionSetItem]\nfrom typing import TypedDict, Union, TypeVar\n\nF1 = TypeVar('F1', bound='Foo1')\nF2 = TypeVar('F2', bound='Foo2')\n\nclass Foo1(TypedDict):\n    z: str\n    a: int\nclass Foo2(TypedDict):\n    z: str\n    b: int\n\ndef func(foo: Union[F1, F2]):\n    foo[\"z\"] = \"a\"  # ok\n    foo[\"z\"] = 1  # E: Value of \"z\" has incompatible type \"int\"; expected \"str\"\n\n    foo[\"a\"] = 1  # E: TypedDict \"Foo2\" has no key \"a\"\n    foo[\"b\"] = 2  # E: TypedDict \"Foo1\" has no key \"b\"\n\n    foo[\"missing\"] = 1  # E: TypedDict \"Foo1\" has no key \"missing\" \\\n                        # E: TypedDict \"Foo2\" has no key \"missing\"\n    foo[1] = \"m\"  # E: TypedDict key must be a string literal; expected one of (\"z\", \"a\") \\\n                  # E: TypedDict key must be a string literal; expected one of (\"z\", \"b\") \\\n                  # E: Argument 1 to \"__setitem__\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictCreation]\nfrom typing import TypedDict, Generic, TypeVar\n\nT = TypeVar(\"T\")\n\nclass TD(TypedDict, Generic[T]):\n    key: int\n    value: T\n\ntds: TD[str]\nreveal_type(tds)  # N: Revealed type is \"TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})\"\n\ntdi = TD(key=0, value=0)\nreveal_type(tdi)  # N: Revealed type is \"TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})\"\nTD[str](key=0, value=0)  # E: Incompatible types (expression has type \"int\", TypedDict item \"value\" has type \"str\")\nTD[str]({\"key\": 0, \"value\": 0})  # E: Incompatible types (expression has type \"int\", TypedDict item \"value\" has type \"str\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictInference]\nfrom typing import TypedDict, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\n\nclass TD(TypedDict, Generic[T]):\n    key: int\n    value: T\n\ndef foo(x: TD[T]) -> List[T]: ...\n\nreveal_type(foo(TD(key=1, value=2)))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(foo({\"key\": 1, \"value\": 2}))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(foo(dict(key=1, value=2)))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictExtending]\nfrom typing import TypedDict, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\nclass TD(TypedDict, Generic[T]):\n    key: int\n    value: T\n\nS = TypeVar(\"S\")\nclass STD(TD[List[S]]):\n    other: S\n\nstd: STD[str]\nreveal_type(std)  # N: Revealed type is \"TypedDict('__main__.STD', {'key': builtins.int, 'value': builtins.list[builtins.str], 'other': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictExtendingErrors]\nfrom typing import TypedDict, Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass Base(TypedDict, Generic[T]):\n    x: T\nclass Sub(Base[{}]):  # E: Invalid TypedDict type argument \\\n                      # E: Invalid base class \"Base\" \\\n                      # E: Type expected within [...]\n\n    y: int\ns: Sub\nreveal_type(s)  # N: Revealed type is \"TypedDict('__main__.Sub', {'y': builtins.int})\"\n\nclass Sub2(Base[int, str]):  # E: Invalid number of type arguments for \"Base\" \\\n                             # E: \"Base\" expects 1 type argument, but 2 given\n    y: int\ns2: Sub2\nreveal_type(s2)  # N: Revealed type is \"TypedDict('__main__.Sub2', {'x': Any, 'y': builtins.int})\"\n\nclass Sub3(Base):  # OK\n    y: int\ns3: Sub3\nreveal_type(s3)  # N: Revealed type is \"TypedDict('__main__.Sub3', {'x': Any, 'y': builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictAttributeOnClassObject]\nfrom typing import TypedDict\n\nclass TD(TypedDict):\n    x: str\n    y: str\n\nreveal_type(TD.__iter__)  # N: Revealed type is \"def (typing._TypedDict) -> typing.Iterator[builtins.str]\"\nreveal_type(TD.__annotations__)  # N: Revealed type is \"typing.Mapping[builtins.str, builtins.object]\"\nreveal_type(TD.values)  # N: Revealed type is \"def (self: typing.Mapping[T`1, T_co`2]) -> typing.Iterable[T_co`2]\"\n[builtins fixtures/dict-full.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictAlias]\n# flags: --disallow-any-generics\nfrom typing import TypedDict, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\nclass TD(TypedDict, Generic[T]):\n    key: int\n    value: T\n\nAlias = TD[List[T]]\n\nad: Alias[str]\nreveal_type(ad)  # N: Revealed type is \"TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.list[builtins.str]})\"\nAlias[str](key=0, value=0)  # E: Incompatible types (expression has type \"int\", TypedDict item \"value\" has type \"List[str]\")\n\n# Generic aliases are *always* filled with Any, so this is different from TD(...) call.\nAlias(key=0, value=0)  # E: Missing type parameters for generic type \"Alias\" \\\n                       # E: Incompatible types (expression has type \"int\", TypedDict item \"value\" has type \"List[Any]\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictMultipleGenerics]\n# See https://github.com/python/mypy/issues/13755\nfrom typing import Generic, TypeVar, TypedDict\n\nT = TypeVar(\"T\")\nFoo = TypedDict(\"Foo\", {\"bar\": T})\nclass Stack(Generic[T]): pass\n\na = Foo[str]\nb = Foo[int]\nreveal_type(a)  # N: Revealed type is \"def (*, bar: builtins.str) -> TypedDict('__main__.Foo', {'bar': builtins.str})\"\nreveal_type(b)  # N: Revealed type is \"def (*, bar: builtins.int) -> TypedDict('__main__.Foo', {'bar': builtins.int})\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testGenericTypedDictCallSyntax]\nfrom typing import TypedDict, TypeVar\n\nT = TypeVar(\"T\")\nTD = TypedDict(\"TD\", {\"key\": int, \"value\": T})\nreveal_type(TD)  # N: Revealed type is \"def [T] (*, key: builtins.int, value: T`1) -> TypedDict('__main__.TD', {'key': builtins.int, 'value': T`1})\"\n\ntds: TD[str]\nreveal_type(tds)  # N: Revealed type is \"TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})\"\n\ntdi = TD(key=0, value=0)\nreveal_type(tdi)  # N: Revealed type is \"TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})\"\nTD[str](key=0, value=0)  # E: Incompatible types (expression has type \"int\", TypedDict item \"value\" has type \"str\")\nTD[str]({\"key\": 0, \"value\": 0})  # E: Incompatible types (expression has type \"int\", TypedDict item \"value\" has type \"str\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictSelfItemNotAllowed]\nfrom typing import Self, TypedDict, Optional\n\nclass TD(TypedDict):\n    val: int\n    next: Optional[Self]  # E: Self type cannot be used in TypedDict item type\nTDC = TypedDict(\"TDC\", {\"val\": int, \"next\": Optional[Self]})  # E: Self type cannot be used in TypedDict item type\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testUnionOfEquivalentTypedDictsInferred]\nfrom typing import TypedDict, Dict\n\nD = TypedDict(\"D\", {\"foo\": int}, total=False)\n\ndef f(d: Dict[str, D]) -> None:\n    args = d[\"a\"]\n    args.update(d.get(\"b\", {}))  # OK\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testUnionOfEquivalentTypedDictsDeclared]\nfrom typing import TypedDict, Union\n\nclass A(TypedDict, total=False):\n    name: str\nclass B(TypedDict, total=False):\n    name: str\n\ndef foo(data: Union[A, B]) -> None: ...\nfoo({\"name\": \"Robert\"})  # OK\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testUnionOfEquivalentTypedDictsEmpty]\nfrom typing import TypedDict, Union\n\nclass Foo(TypedDict, total=False):\n    foo: str\nclass Bar(TypedDict, total=False):\n    bar: str\n\ndef foo(body: Union[Foo, Bar] = {}) -> None:  # OK\n    ...\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testUnionOfEquivalentTypedDictsDistinct]\nfrom typing import TypedDict, Union, Literal\n\nclass A(TypedDict):\n    type: Literal['a']\n    value: bool\nclass B(TypedDict):\n    type: Literal['b']\n    value: str\n\nResponse = Union[A, B]\ndef method(message: Response) -> None: ...\n\nmethod({'type': 'a', 'value': True})  # OK\nmethod({'type': 'b', 'value': 'abc'})  # OK\nmethod({'type': 'a', 'value': 'abc'})  # E: Type of TypedDict is ambiguous, none of (\"A\", \"B\") matches cleanly \\\n                                       # E: Argument 1 to \"method\" has incompatible type \"Dict[str, str]\"; expected \"Union[A, B]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testUnionOfEquivalentTypedDictsNested]\nfrom typing import TypedDict, Union\n\nclass A(TypedDict, total=False):\n    foo: C\nclass B(TypedDict, total=False):\n    foo: D\nclass C(TypedDict, total=False):\n    c: str\nclass D(TypedDict, total=False):\n    d: str\n\ndef foo(data: Union[A, B]) -> None: ...\nfoo({\"foo\": {\"c\": \"foo\"}})  # OK\nfoo({\"foo\": {\"e\": \"foo\"}})  # E: Type of TypedDict is ambiguous, none of (\"A\", \"B\") matches cleanly \\\n                            # E: Argument 1 to \"foo\" has incompatible type \"Dict[str, Dict[str, str]]\"; expected \"Union[A, B]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictMissingEmptyKey]\nfrom typing_extensions import TypedDict\n\nclass A(TypedDict):\n    my_attr_1: str\n    my_attr_2: int\n\nd: A\nd['']  # E: TypedDict \"A\" has no key \"\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictFlexibleUpdate]\nfrom mypy_extensions import TypedDict\n\nA = TypedDict(\"A\", {\"foo\": int, \"bar\": int})\nB = TypedDict(\"B\", {\"foo\": int})\n\na = A({\"foo\": 1, \"bar\": 2})\nb = B({\"foo\": 2})\na.update({\"foo\": 2})\na.update(b)\na.update(a)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictStrictUpdate]\n# flags: --extra-checks\nfrom mypy_extensions import TypedDict\n\nA = TypedDict(\"A\", {\"foo\": int, \"bar\": int})\nB = TypedDict(\"B\", {\"foo\": int})\n\na = A({\"foo\": 1, \"bar\": 2})\nb = B({\"foo\": 2})\na.update({\"foo\": 2})  # OK\na.update(b)  # E: Argument 1 to \"update\" of \"TypedDict\" has incompatible type \"B\"; expected \"TypedDict({'foo': int, 'bar'?: int})\"\na.update(a)  # OK\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictFlexibleUpdateUnion]\nfrom typing import Union\nfrom mypy_extensions import TypedDict\n\nA = TypedDict(\"A\", {\"foo\": int, \"bar\": int})\nB = TypedDict(\"B\", {\"foo\": int})\nC = TypedDict(\"C\", {\"bar\": int})\n\na = A({\"foo\": 1, \"bar\": 2})\nu: Union[B, C]\na.update(u)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictFlexibleUpdateUnionExtra]\nfrom typing import Union\nfrom mypy_extensions import TypedDict\n\nA = TypedDict(\"A\", {\"foo\": int, \"bar\": int})\nB = TypedDict(\"B\", {\"foo\": int, \"extra\": int})\nC = TypedDict(\"C\", {\"bar\": int, \"extra\": int})\n\na = A({\"foo\": 1, \"bar\": 2})\nu: Union[B, C]\na.update(u)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictFlexibleUpdateUnionStrict]\n# flags: --extra-checks\nfrom typing import Union, NotRequired\nfrom mypy_extensions import TypedDict\n\nA = TypedDict(\"A\", {\"foo\": int, \"bar\": int})\nA1 = TypedDict(\"A1\", {\"foo\": int, \"bar\": NotRequired[int]})\nA2 = TypedDict(\"A2\", {\"foo\": NotRequired[int], \"bar\": int})\nB = TypedDict(\"B\", {\"foo\": int})\nC = TypedDict(\"C\", {\"bar\": int})\n\na = A({\"foo\": 1, \"bar\": 2})\nu: Union[B, C]\na.update(u)  # E: Argument 1 to \"update\" of \"TypedDict\" has incompatible type \"Union[B, C]\"; expected \"Union[TypedDict({'foo': int, 'bar'?: int}), TypedDict({'foo'?: int, 'bar': int})]\"\nu2: Union[A1, A2]\na.update(u2)  # OK\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackSame]\n# flags: --extra-checks\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n    b: int\n\nfoo1: Foo = {\"a\": 1, \"b\": 1}\nfoo2: Foo = {**foo1, \"b\": 2}\nfoo3 = Foo(**foo1, b=2)\nfoo4 = Foo({**foo1, \"b\": 2})\nfoo5 = Foo(dict(**foo1, b=2))\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackCompatible]\n# flags: --extra-checks\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n\nclass Bar(TypedDict):\n    a: int\n    b: int\n\nfoo: Foo = {\"a\": 1}\nbar: Bar = {**foo, \"b\": 2}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackIncompatible]\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n    b: str\n\nclass Bar(TypedDict):\n    a: int\n    b: int\n\nfoo: Foo = {\"a\": 1, \"b\": \"a\"}\nbar1: Bar = {**foo, \"b\": 2}  # Incompatible item is overridden\nbar2: Bar = {**foo, \"a\": 2}  # E: Incompatible types (expression has type \"str\", TypedDict item \"b\" has type \"int\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackNotRequiredKeyIncompatible]\nfrom typing import TypedDict, NotRequired\n\nclass Foo(TypedDict):\n    a: NotRequired[str]\n\nclass Bar(TypedDict):\n    a: NotRequired[int]\n\nfoo: Foo = {}\nbar: Bar = {**foo}  # E: Incompatible types (expression has type \"str\", TypedDict item \"a\" has type \"int\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testTypedDictUnpackMissingOrExtraKey]\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n\nclass Bar(TypedDict):\n    a: int\n    b: int\n\nfoo1: Foo = {\"a\": 1}\nbar1: Bar = {\"a\": 1, \"b\": 1}\nfoo2: Foo = {**bar1}  # E: Extra key \"b\" for TypedDict \"Foo\"\nbar2: Bar = {**foo1}  # E: Missing key \"b\" for TypedDict \"Bar\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackNotRequiredKeyExtra]\nfrom typing import TypedDict, NotRequired\n\nclass Foo(TypedDict):\n    a: int\n\nclass Bar(TypedDict):\n    a: int\n    b: NotRequired[int]\n\nfoo1: Foo = {\"a\": 1}\nbar1: Bar = {\"a\": 1}\nfoo2: Foo = {**bar1}  # E: Extra key \"b\" for TypedDict \"Foo\"\nbar2: Bar = {**foo1}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackRequiredKeyMissing]\nfrom typing import TypedDict, NotRequired\n\nclass Foo(TypedDict):\n    a: NotRequired[int]\n\nclass Bar(TypedDict):\n    a: int\n\nfoo: Foo = {\"a\": 1}\nbar: Bar = {**foo}  # E: Missing key \"a\" for TypedDict \"Bar\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackMultiple]\n# flags: --extra-checks\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n\nclass Bar(TypedDict):\n    b: int\n\nclass Baz(TypedDict):\n    a: int\n    b: int\n    c: int\n\nfoo: Foo = {\"a\": 1}\nbar: Bar = {\"b\": 1}\nbaz: Baz = {**foo, **bar, \"c\": 1}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackNested]\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n    b: int\n\nclass Bar(TypedDict):\n    c: Foo\n    d: int\n\nfoo: Foo = {\"a\": 1, \"b\": 1}\nbar: Bar = {\"c\": foo, \"d\": 1}\nbar2: Bar = {**bar, \"c\": {**bar[\"c\"], \"b\": 2}, \"d\": 2}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackNestedError]\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n    b: int\n\nclass Bar(TypedDict):\n    c: Foo\n    d: int\n\nfoo: Foo = {\"a\": 1, \"b\": 1}\nbar: Bar = {\"c\": foo, \"d\": 1}\nbar2: Bar = {**bar, \"c\": {**bar[\"c\"], \"b\": \"wrong\"}, \"d\": 2}  # E: Incompatible types (expression has type \"str\", TypedDict item \"b\" has type \"int\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackOverrideRequired]\nfrom mypy_extensions import TypedDict\n\nDetails = TypedDict('Details', {'first_name': str, 'last_name': str})\nDetailsSubset = TypedDict('DetailsSubset', {'first_name': str, 'last_name': str}, total=False)\ndefaults: Details = {'first_name': 'John', 'last_name': 'Luther'}\n\ndef generate(data: DetailsSubset) -> Details:\n    return {**defaults, **data}  # OK\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackUntypedDict]\nfrom typing import Any, Dict, TypedDict\n\nclass Bar(TypedDict):\n    pass\n\nfoo: Dict[str, Any] = {}\nbar: Bar = {**foo}  # E: Unsupported type \"Dict[str, Any]\" for ** expansion in TypedDict\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackIntoUnion]\nfrom typing import TypedDict, Union\n\nclass Foo(TypedDict):\n    a: int\n\nclass Bar(TypedDict):\n    b: int\n\nfoo: Foo = {'a': 1}\nfoo_or_bar: Union[Foo, Bar] = {**foo}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackFromUnion]\nfrom typing import TypedDict, Union\n\nclass Foo(TypedDict):\n    a: int\n    b: int\n\nclass Bar(TypedDict):\n    b: int\n\nfoo_or_bar: Union[Foo, Bar]\nfoo: Bar = {**foo_or_bar}  # E: Extra key \"a\" for TypedDict \"Bar\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackUnionRequiredMissing]\nfrom typing import TypedDict, NotRequired, Union\n\nclass Foo(TypedDict):\n    a: int\n    b: int\n\nclass Bar(TypedDict):\n    a: int\n    b: NotRequired[int]\n\nfoo_or_bar: Union[Foo, Bar] = {\"a\": 1}\nfoo: Foo = {**foo_or_bar}  # E: Missing key \"b\" for TypedDict \"Foo\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackInference]\nfrom typing import TypedDict, Generic, TypeVar\n\nclass Foo(TypedDict):\n    a: int\n    b: str\n\nT = TypeVar(\"T\")\nclass TD(TypedDict, Generic[T]):\n    a: T\n    b: str\n\nfoo: Foo\nbar = TD(**foo)\nreveal_type(bar)  # N: Revealed type is \"TypedDict('__main__.TD', {'a': builtins.int, 'b': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackStrictMode]\n# flags: --extra-checks\nfrom typing import TypedDict, NotRequired\n\nclass Foo(TypedDict):\n    a: int\n\nclass Bar(TypedDict):\n    a: int\n    b: NotRequired[int]\n\nfoo: Foo\nbar: Bar = {**foo}  # E: Non-required key \"b\" not explicitly found in any ** item\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackAny]\nfrom typing import Any, TypedDict, NotRequired, Dict, Union\n\nclass Foo(TypedDict):\n    a: int\n    b: NotRequired[int]\n\nx: Any\ny: Dict[Any, Any]\nz: Union[Any, Dict[Any, Any]]\nt1: Foo = {**x}  # E: Missing key \"a\" for TypedDict \"Foo\"\nt2: Foo = {**y}  # E: Missing key \"a\" for TypedDict \"Foo\"\nt3: Foo = {**z}  # E: Missing key \"a\" for TypedDict \"Foo\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictUnpackError]\nfrom typing import TypedDict\n\nclass Foo(TypedDict):\n    a: int\n\ndef foo(x: int) -> Foo: ...\n\nf: Foo = {**foo(\"no\")}  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testTypedDictWith__or__method]\nfrom typing import Dict\nfrom mypy_extensions import TypedDict\n\nclass Foo(TypedDict):\n    key: int\n\nfoo1: Foo = {'key': 1}\nfoo2: Foo = {'key': 2}\n\nreveal_type(foo1 | foo2)  # N: Revealed type is \"TypedDict('__main__.Foo', {'key': builtins.int})\"\nreveal_type(foo1 | {'key': 1})  # N: Revealed type is \"TypedDict('__main__.Foo', {'key': builtins.int})\"\nreveal_type(foo1 | {'key': 'a'})  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type(foo1 | {})  # N: Revealed type is \"TypedDict('__main__.Foo', {'key': builtins.int})\"\n\nd1: Dict[str, int]\nd2: Dict[int, str]\n\nreveal_type(foo1 | d1)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nfoo1 | d2  # E: Unsupported operand types for | (\"Foo\" and \"Dict[int, str]\")\n\n\nclass Bar(TypedDict):\n    key: int\n    value: str\n\nbar: Bar\nreveal_type(bar | {})  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type(bar | {'key': 1, 'value': 'v'})  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type(bar | {'key': 1})  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type(bar | {'value': 'v'})  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type(bar | {'key': 'a'})  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type(bar | {'value': 1})  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type(bar | {'key': 'a', 'value': 1})  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\n\nreveal_type(bar | foo1)  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type(bar | d1)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nbar | d2  # E: Unsupported operand types for | (\"Bar\" and \"Dict[int, str]\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict-iror.pyi]\n\n[case testTypedDictWith__or__method_error]\nfrom mypy_extensions import TypedDict\n\nclass Foo(TypedDict):\n    key: int\n\nfoo: Foo = {'key': 1}\nfoo | 1\n\nclass SubDict(dict): ...\nfoo | SubDict()\n[out]\nmain:7: error: No overload variant of \"__or__\" of \"TypedDict\" matches argument type \"int\"\nmain:7: note: Possible overload variants:\nmain:7: note:     def __or__(self, TypedDict({'key'?: int}), /) -> Foo\nmain:7: note:     def __or__(self, Dict[str, Any], /) -> Dict[str, object]\nmain:10: error: No overload variant of \"__ror__\" of \"dict\" matches argument type \"Foo\"\nmain:10: note: Possible overload variants:\nmain:10: note:     def __ror__(self, Dict[Any, Any], /) -> Dict[Any, Any]\nmain:10: note:     def [T, T2] __ror__(self, Dict[T, T2], /) -> Dict[Union[Any, T], Union[Any, T2]]\n[builtins fixtures/dict-full.pyi]\n[typing fixtures/typing-typeddict-iror.pyi]\n\n[case testTypedDictWith__ror__method]\nfrom typing import Dict\nfrom mypy_extensions import TypedDict\n\nclass Foo(TypedDict):\n    key: int\n\nfoo: Foo = {'key': 1}\n\nreveal_type({'key': 1} | foo)  # N: Revealed type is \"TypedDict('__main__.Foo', {'key': builtins.int})\"\nreveal_type({'key': 'a'} | foo)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type({} | foo)  # N: Revealed type is \"TypedDict('__main__.Foo', {'key': builtins.int})\"\n{1: 'a'} | foo  # E: Dict entry 0 has incompatible type \"int\": \"str\"; expected \"str\": \"Any\"\n\nd1: Dict[str, int]\nd2: Dict[int, str]\n\nreveal_type(d1 | foo)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nd2 | foo  # E: Unsupported operand types for | (\"Dict[int, str]\" and \"Foo\")\n1 | foo  # E: Unsupported left operand type for | (\"int\")\n\n\nclass Bar(TypedDict):\n    key: int\n    value: str\n\nbar: Bar\nreveal_type({} | bar)  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type({'key': 1, 'value': 'v'} | bar)  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type({'key': 1} | bar)  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type({'value': 'v'} | bar)  # N: Revealed type is \"TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})\"\nreveal_type({'key': 'a'} | bar)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type({'value': 1} | bar)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type({'key': 'a', 'value': 1} | bar)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\n\nreveal_type(d1 | bar)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nd2 | bar  # E: Unsupported operand types for | (\"Dict[int, str]\" and \"Bar\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict-iror.pyi]\n\n[case testTypedDictWith__ior__method]\nfrom typing import Dict\nfrom mypy_extensions import TypedDict\n\nclass Foo(TypedDict):\n    key: int\n\nfoo: Foo = {'key': 1}\nfoo |= {'key': 2}\n\nfoo |= {}\nfoo |= {'key': 'a', 'b': 'a'}  # E: Expected TypedDict key \"key\" but found keys (\"key\", \"b\")  \\\n                               # E: Incompatible types (expression has type \"str\", TypedDict item \"key\" has type \"int\")\nfoo |= {'b': 2}  # E: Unexpected TypedDict key \"b\"\n\nd1: Dict[str, int]\nd2: Dict[int, str]\n\nfoo |= d1  # E: Argument 1 to \"__ior__\" of \"TypedDict\" has incompatible type \"Dict[str, int]\"; expected \"TypedDict({'key'?: int})\"\nfoo |= d2  # E: Argument 1 to \"__ior__\" of \"TypedDict\" has incompatible type \"Dict[int, str]\"; expected \"TypedDict({'key'?: int})\"\n\n\nclass Bar(TypedDict):\n    key: int\n    value: str\n\nbar: Bar\nbar |= {}\nbar |= {'key': 1, 'value': 'a'}\nbar |= {'key': 'a', 'value': 'a', 'b': 'a'}  # E: Expected TypedDict keys (\"key\", \"value\") but found keys (\"key\", \"value\", \"b\") \\\n                                             # E: Incompatible types (expression has type \"str\", TypedDict item \"key\" has type \"int\")\n\nbar |= foo\nbar |= d1  # E: Argument 1 to \"__ior__\" of \"TypedDict\" has incompatible type \"Dict[str, int]\"; expected \"TypedDict({'key'?: int, 'value'?: str})\"\nbar |= d2  # E: Argument 1 to \"__ior__\" of \"TypedDict\" has incompatible type \"Dict[int, str]\"; expected \"TypedDict({'key'?: int, 'value'?: str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict-iror.pyi]\n\n[case testGenericTypedDictStrictOptionalExtending]\nfrom typing import Generic, TypeVar, TypedDict, Optional\n\nT = TypeVar(\"T\")\nclass Foo(TypedDict, Generic[T], total=False):\n    a: Optional[str]\n    g: Optional[T]\n\nclass Bar(Foo[T], total=False):\n    other: str\n\nb: Bar[int]\nreveal_type(b[\"a\"])  # N: Revealed type is \"Union[builtins.str, None]\"\nreveal_type(b[\"g\"])  # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNoCrashOnUnImportedAnyNotRequired]\n# flags: --disallow-any-unimported\nfrom typing import NotRequired, Required, TypedDict\nfrom thismoduledoesntexist import T  # type: ignore[import]\n\nB = TypedDict(\"B\", {  # E: Type of a TypedDict key becomes \"Any\" due to an unfollowed import\n    \"T1\": NotRequired[T],\n    \"T2\": Required[T],\n})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictWithClassLevelKeywords]\nfrom typing import TypedDict, Generic, TypeVar\n\nT = TypeVar('T')\n\nclass Meta(type): ...\n\nclass WithMetaKeyword(TypedDict, metaclass=Meta):  # E: Unexpected keyword argument \"metaclass\" for \"__init_subclass__\" of \"TypedDict\"\n    ...\n\nclass GenericWithMetaKeyword(TypedDict, Generic[T], metaclass=Meta):  # E: Unexpected keyword argument \"metaclass\" for \"__init_subclass__\" of \"TypedDict\"\n    ...\n\n# We still don't allow this, because the implementation is much easier\n# and it does not make any practical sense to do it:\nclass WithTypeMeta(TypedDict, metaclass=type):  # E: Unexpected keyword argument \"metaclass\" for \"__init_subclass__\" of \"TypedDict\"\n    ...\n\nclass OtherKeywords(TypedDict, a=1, b=2, c=3, total=True):  # E: Unexpected keyword argument \"a\" for \"__init_subclass__\" of \"TypedDict\" \\\n                                                            # E: Unexpected keyword argument \"b\" for \"__init_subclass__\" of \"TypedDict\" \\\n                                                            # E: Unexpected keyword argument \"c\" for \"__init_subclass__\" of \"TypedDict\"\n    ...\n\nclass TotalInTheMiddle(TypedDict, a=1, total=True, b=2, c=3):  # E: Unexpected keyword argument \"a\" for \"__init_subclass__\" of \"TypedDict\" \\\n                                                            # E: Unexpected keyword argument \"b\" for \"__init_subclass__\" of \"TypedDict\" \\\n                                                            # E: Unexpected keyword argument \"c\" for \"__init_subclass__\" of \"TypedDict\"\n    ...\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCanCreateClassWithFunctionBasedTypedDictBase]\nfrom mypy_extensions import TypedDict\n\nclass Params(TypedDict(\"Params\", {'x': int})):\n    pass\n\np: Params = {'x': 2}\nreveal_type(p) # N: Revealed type is \"TypedDict('__main__.Params', {'x': builtins.int})\"\n[builtins fixtures/dict.pyi]\n\n[case testInitTypedDictFromType]\nfrom typing import TypedDict, Type\nfrom typing_extensions import Required\n\nclass Point(TypedDict, total=False):\n    x: Required[int]\n    y: int\n\ndef func(cls: Type[Point]) -> None:\n    reveal_type(cls)  # N: Revealed type is \"Type[TypedDict('__main__.Point', {'x': builtins.int, 'y'?: builtins.int})]\"\n    cls(x=1, y=2)\n    cls(1, 2)  # E: Too many positional arguments\n    cls(x=1)\n    cls(y=2)  # E: Missing named argument \"x\"\n    cls(x=1, y=2, error=\"\")  # E: Unexpected keyword argument \"error\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testInitTypedDictFromTypeGeneric]\nfrom typing import Generic, TypedDict, Type, TypeVar\nfrom typing_extensions import Required\n\nclass Point(TypedDict, total=False):\n    x: Required[int]\n    y: int\n\nT = TypeVar(\"T\", bound=Point)\n\nclass A(Generic[T]):\n    def __init__(self, a: Type[T]) -> None:\n        self.a = a\n\n    def func(self) -> T:\n        reveal_type(self.a)  # N: Revealed type is \"Type[T`1]\"\n        self.a(x=1, y=2)\n        self.a(y=2)  # E: Missing named argument \"x\"\n        return self.a(x=1)\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testNameUndefinedErrorDoesNotLoseUnpackedKWArgsInformation]\nfrom typing import overload\nfrom typing_extensions import TypedDict, Unpack\n\nclass TD(TypedDict, total=False):\n    x: int\n    y: str\n\n@overload\ndef f(self, *, x: int) -> None: ...\n@overload\ndef f(self, *, y: str) -> None: ...\ndef f(self, **kwargs: Unpack[TD]) -> None:\n    z  # E: Name \"z\" is not defined\n\n@overload\ndef g(self, *, x: float) -> None: ...\n@overload\ndef g(self, *, y: str) -> None: ...\ndef g(self, **kwargs: Unpack[TD]) -> None:  # E: Overloaded function implementation does not accept all possible arguments of signature 1\n    z  # E: Name \"z\" is not defined\n\nclass A:\n    def f(self, *, x: int) -> None: ...\n    def g(self, *, x: float) -> None: ...\nclass B(A):\n    def f(self, **kwargs: Unpack[TD]) -> None:\n        z  # E: Name \"z\" is not defined\n    def g(self, **kwargs: Unpack[TD]) -> None:  # E: Signature of \"g\" incompatible with supertype \"A\" \\\n                                                # N:      Superclass: \\\n                                                # N:          def g(self, *, x: float) -> None \\\n                                                # N:      Subclass: \\\n                                                # N:          def g(*, x: int = ..., y: str = ...) -> None\n        z  # E: Name \"z\" is not defined\nreveal_type(B.f)  # N: Revealed type is \"def (self: __main__.B, **kwargs: Unpack[TypedDict('__main__.TD', {'x'?: builtins.int, 'y'?: builtins.str})])\"\nB().f(x=1.0)  # E: Argument \"x\" to \"f\" of \"B\" has incompatible type \"float\"; expected \"int\"\n[builtins fixtures/primitives.pyi]\n\n[case testTypedDictUnpackWithParamSpecInference]\nfrom typing import TypeVar, ParamSpec, Callable\nfrom typing_extensions import TypedDict, Unpack\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\ndef run(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ...\n\nclass Params(TypedDict):\n    temperature: float\n\ndef test(temperature: int) -> None: ...\ndef test2(temperature: float, other: str) -> None: ...\n\nclass Test:\n    def f(self, c: Callable[..., None], **params: Unpack[Params]) -> None:\n        run(c, **params)\n    def g(self, **params: Unpack[Params]) -> None:\n        run(test, **params)  # E: Argument \"temperature\" to \"run\" has incompatible type \"float\"; expected \"int\"\n    def h(self, **params: Unpack[Params]) -> None:\n        run(test2, other=\"yes\", **params)\n        run(test2, other=0, **params)  # E: Argument \"other\" to \"run\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypedDictUnpackSingleWithSubtypingNoCrash]\nfrom typing import Callable\nfrom typing_extensions import TypedDict, Unpack\n\nclass Kwargs(TypedDict):\n    name: str\n\ndef f(**kwargs: Unpack[Kwargs]) -> None:\n    pass\n\nclass C:\n    d: Callable[[Unpack[Kwargs]], None]\n\n# TODO: it is an old question whether we should allow this, for now simply don't crash.\nclass D(C):\n    d = f\n[builtins fixtures/tuple.pyi]\n\n[case testTypedDictInlineNoOldStyleAlias]\n# flags: --enable-incomplete-feature=InlineTypedDict\nX = {\"int\": int, \"str\": str}\nreveal_type(X)  # N: Revealed type is \"builtins.dict[builtins.str, def () -> builtins.object]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictInlineYesMidStyleAlias]\n# flags: --enable-incomplete-feature=InlineTypedDict\nfrom typing_extensions import TypeAlias\nX: TypeAlias = {\"int\": int, \"str\": str}\nx: X\nreveal_type(x)  # N:  # N: Revealed type is \"TypedDict({'int': builtins.int, 'str': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictInlineNoEmpty]\n# flags: --enable-incomplete-feature=InlineTypedDict\nx: {}  # E: Invalid type comment or annotation\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictInlineNotRequired]\n# flags: --enable-incomplete-feature=InlineTypedDict\nfrom typing import NotRequired\n\nx: {\"one\": int, \"other\": NotRequired[int]}\nx = {\"one\": 1}  # OK\ny: {\"one\": int, \"other\": int}\ny = {\"one\": 1}  # E: Expected TypedDict keys (\"one\", \"other\") but found only key \"one\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictInlineReadOnly]\n# flags: --enable-incomplete-feature=InlineTypedDict\nfrom typing import ReadOnly\n\nx: {\"one\": int, \"other\": ReadOnly[int]}\nx[\"one\"] = 1  # ok\nx[\"other\"] = 1  # E: ReadOnly TypedDict key \"other\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictInlineNestedSchema]\n# flags: --enable-incomplete-feature=InlineTypedDict\ndef nested() -> {\"one\": str, \"other\": {\"a\": int, \"b\": int}}:\n    if bool():\n        return {\"one\": \"yes\", \"other\": {\"a\": 1, \"b\": 2}}  # OK\n    else:\n        return {\"one\": \"no\", \"other\": {\"a\": 1, \"b\": \"2\"}}  # E: Incompatible types (expression has type \"str\", TypedDict item \"b\" has type \"int\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictInlineMergeAnother]\n# flags: --enable-incomplete-feature=InlineTypedDict\nfrom typing import TypeVar\nfrom typing_extensions import TypeAlias\n\nT = TypeVar(\"T\")\nX: TypeAlias = {\"item\": T}\nx: {\"a\": int, **X[str], \"b\": int}\nreveal_type(x)  # N: Revealed type is \"TypedDict({'a': builtins.int, 'b': builtins.int, 'item': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n# ReadOnly\n# See: https://peps.python.org/pep-0705\n\n[case testTypedDictReadOnly]\n# flags: --show-error-codes\nfrom typing import ReadOnly, TypedDict\n\nclass TP(TypedDict):\n    one: int\n    other: ReadOnly[str]\n\nx: TP\nreveal_type(x[\"one\"])   # N: Revealed type is \"builtins.int\"\nreveal_type(x[\"other\"]) # N: Revealed type is \"builtins.str\"\nx[\"one\"] = 1  # ok\nx[\"other\"] = \"a\"  # E: ReadOnly TypedDict key \"other\" TypedDict is mutated  [typeddict-readonly-mutated]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyCreation]\nfrom typing import ReadOnly, TypedDict\n\nclass TD(TypedDict):\n    x: ReadOnly[int]\n    y: int\n\n# Ok:\nx = TD({\"x\": 1, \"y\": 2})\ny = TD(x=1, y=2)\nz: TD = {\"x\": 1, \"y\": 2}\n\n# Error:\nx2 = TD({\"x\": \"a\", \"y\": 2})  # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\ny2 = TD(x=\"a\", y=2)          # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\nz2: TD = {\"x\": \"a\", \"y\": 2}  # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyDel]\nfrom typing import ReadOnly, TypedDict, NotRequired\n\nclass TP(TypedDict):\n    required_key: ReadOnly[str]\n    optional_key: ReadOnly[NotRequired[str]]\n\nx: TP\ndel x[\"required_key\"]  # E: Key \"required_key\" of TypedDict \"TP\" cannot be deleted\ndel x[\"optional_key\"]  # E: Key \"optional_key\" of TypedDict \"TP\" cannot be deleted\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyMutateMethods]\nfrom typing import ReadOnly, TypedDict\n\nclass TP(TypedDict):\n    key: ReadOnly[str]\n    other: ReadOnly[int]\n    mutable: bool\n\nx: TP\nreveal_type(x.pop(\"key\"))  # N: Revealed type is \"builtins.str\" \\\n                           # E: Key \"key\" of TypedDict \"TP\" cannot be deleted\n\n\nx.update({\"key\": \"abc\", \"other\": 1, \"mutable\": True})  # E: ReadOnly TypedDict keys (\"key\", \"other\") TypedDict are mutated\nx.setdefault(\"key\", \"abc\")  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated\nx.setdefault(\"other\", 1)  # E: ReadOnly TypedDict key \"other\" TypedDict is mutated\nx.setdefault(\"mutable\", False)  # ok\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictFromTypingExtensionsReadOnlyMutateMethods]\nfrom typing_extensions import ReadOnly, TypedDict\n\nclass TP(TypedDict):\n    key: ReadOnly[str]\n\nx: TP\nx.update({\"key\": \"abc\"})  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictFromMypyExtensionsReadOnlyMutateMethods]\nfrom mypy_extensions import TypedDict\nfrom typing_extensions import ReadOnly\n\nclass TP(TypedDict):\n    key: ReadOnly[str]\n\nx: TP\nx.update({\"key\": \"abc\"})  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyMutate__ior__Statements]\nfrom typing_extensions import ReadOnly, TypedDict\n\nclass TP(TypedDict):\n    key: ReadOnly[str]\n    other: ReadOnly[int]\n    mutable: bool\n\nx: TP\nx |= {\"mutable\": True}  # ok\nx |= {\"key\": \"a\"}  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated\nx |= {\"key\": \"a\", \"other\": 1, \"mutable\": True}  # E: ReadOnly TypedDict keys (\"key\", \"other\") TypedDict are mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict-iror.pyi]\n\n[case testTypedDictReadOnlyMutate__or__Statements]\nfrom typing_extensions import ReadOnly, TypedDict\n\nclass TP(TypedDict):\n    key: ReadOnly[str]\n    other: ReadOnly[int]\n    mutable: bool\n\nx: TP\n# These are new objects, not mutation:\nx = x | {\"mutable\": True}\nx = x | {\"key\": \"a\"}\nx = x | {\"key\": \"a\", \"other\": 1, \"mutable\": True}\ny1 = x | {\"mutable\": True}\ny2 = x | {\"key\": \"a\"}\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict-iror.pyi]\n\n[case testTypedDictReadOnlyMutateWithOtherDicts]\nfrom typing import ReadOnly, TypedDict, Dict\n\nclass TP(TypedDict):\n    key: ReadOnly[str]\n    mutable: bool\n\nclass Mutable(TypedDict):\n    mutable: bool\n\nclass Regular(TypedDict):\n    key: str\n\nm: Mutable\nr: Regular\nd: Dict[str, object]\n\n# Creating new objects is ok:\ntp: TP = {**r, **m}\ntp1: TP = {**tp, **m}\ntp2: TP = {**r, **m}\ntp3: TP = {**tp, **r}\ntp4: TP = {**tp, **d}  # E: Unsupported type \"Dict[str, object]\" for ** expansion in TypedDict\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictGenericReadOnly]\nfrom typing import ReadOnly, TypedDict, TypeVar, Generic\n\nT = TypeVar('T')\n\nclass TP(TypedDict, Generic[T]):\n    key: ReadOnly[T]\n\nx: TP[int]\nreveal_type(x[\"key\"])   # N: Revealed type is \"builtins.int\"\nx[\"key\"] = 1  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated\nx[\"key\"] = \"a\"  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated \\\n                # E: Value of \"key\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyOtherTypedDict]\nfrom typing import ReadOnly, TypedDict\n\nclass First(TypedDict):\n    field: int\n\nclass TP(TypedDict):\n    key: ReadOnly[First]\n\nx: TP\nreveal_type(x[\"key\"][\"field\"])   # N: Revealed type is \"builtins.int\"\nx[\"key\"][\"field\"] = 1  # ok\nx[\"key\"] = {\"field\": 2}  # E: ReadOnly TypedDict key \"key\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyInheritance]\nfrom typing import ReadOnly, TypedDict\n\nclass Base(TypedDict):\n    a: ReadOnly[str]\n\nclass Child(Base):\n    b: ReadOnly[int]\n\nbase: Base\nreveal_type(base[\"a\"])   # N: Revealed type is \"builtins.str\"\nbase[\"a\"] = \"x\"  # E: ReadOnly TypedDict key \"a\" TypedDict is mutated\nbase[\"b\"]  # E: TypedDict \"Base\" has no key \"b\"\n\nchild: Child\nreveal_type(child[\"a\"])   # N: Revealed type is \"builtins.str\"\nreveal_type(child[\"b\"])   # N: Revealed type is \"builtins.int\"\nchild[\"a\"] = \"x\"  # E: ReadOnly TypedDict key \"a\" TypedDict is mutated\nchild[\"b\"] = 1  # E: ReadOnly TypedDict key \"b\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlySubtyping]\nfrom typing import ReadOnly, TypedDict\n\nclass A(TypedDict):\n    key: ReadOnly[str]\n\nclass B(TypedDict):\n    key: str\n\na: A\nb: B\n\ndef accepts_A(d: A): ...\ndef accepts_B(d: B): ...\n\naccepts_A(a)\naccepts_A(b)\naccepts_B(a)  # E: Argument 1 to \"accepts_B\" has incompatible type \"A\"; expected \"B\"\naccepts_B(b)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictRequiredConsistentWithNotRequiredReadOnly]\nfrom typing import NotRequired, ReadOnly, Required, TypedDict\n\nclass A(TypedDict):\n    x: NotRequired[ReadOnly[str]]\n\nclass B(TypedDict):\n    x: Required[str]\n\ndef f(b: B):\n    a: A = b  # ok\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyCall]\nfrom typing import ReadOnly, TypedDict\n\nTP = TypedDict(\"TP\", {\"one\": int, \"other\": ReadOnly[str]})\n\nx: TP\nreveal_type(x[\"one\"])   # N: Revealed type is \"builtins.int\"\nreveal_type(x[\"other\"]) # N: Revealed type is \"builtins.str\"\nx[\"one\"] = 1  # ok\nx[\"other\"] = \"a\"  # E: ReadOnly TypedDict key \"other\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyABCSubtypes]\nfrom typing import ReadOnly, TypedDict, Mapping, Dict, MutableMapping\n\nclass TP(TypedDict):\n    one: int\n    other: ReadOnly[int]\n\ndef accepts_mapping(m: Mapping[str, object]): ...\ndef accepts_mutable_mapping(mm: MutableMapping[str, object]): ...\ndef accepts_dict(d: Dict[str, object]): ...\n\nx: TP\naccepts_mapping(x)\naccepts_mutable_mapping(x)  # E: Argument 1 to \"accepts_mutable_mapping\" has incompatible type \"TP\"; expected \"MutableMapping[str, object]\"\naccepts_dict(x)  # E: Argument 1 to \"accepts_dict\" has incompatible type \"TP\"; expected \"Dict[str, object]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyAndNotRequired]\nfrom typing import ReadOnly, TypedDict, NotRequired\n\nclass TP(TypedDict):\n    one: ReadOnly[NotRequired[int]]\n    two: NotRequired[ReadOnly[str]]\n\nx: TP\nreveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TP', {'one'?=: builtins.int, 'two'?=: builtins.str})\"\nreveal_type(x.get(\"one\"))  # N: Revealed type is \"Union[builtins.int, None]\"\nreveal_type(x.get(\"two\"))  # N: Revealed type is \"Union[builtins.str, None]\"\nx[\"one\"] = 1  # E: ReadOnly TypedDict key \"one\" TypedDict is mutated\nx[\"two\"] = \"a\"  # E: ReadOnly TypedDict key \"two\" TypedDict is mutated\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMeetOfTypedDictsWithReadOnly]\nfrom typing import TypeVar, Callable, TypedDict, ReadOnly\nXY = TypedDict('XY', {'x': ReadOnly[int], 'y': int})\nYZ = TypedDict('YZ', {'y': int, 'z': ReadOnly[int]})\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: XY, y: YZ) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"TypedDict({'x'=: builtins.int, 'y': builtins.int, 'z'=: builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyUnpack]\nfrom typing_extensions import TypedDict, Unpack, ReadOnly\n\nclass TD(TypedDict):\n    x: ReadOnly[int]\n    y: str\n\ndef func(**kwargs: Unpack[TD]):\n    kwargs[\"x\"] = 1  # E: ReadOnly TypedDict key \"x\" TypedDict is mutated\n    kwargs[\"y\" ] = \"a\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testIncorrectTypedDictSpecialFormsUsage]\nfrom typing import ReadOnly, TypedDict, NotRequired, Required\n\nx: ReadOnly[int]     # E: ReadOnly[] can be only used in a TypedDict definition\ny: Required[int]     # E: Required[] can be only used in a TypedDict definition\nz: NotRequired[int]  # E: NotRequired[] can be only used in a TypedDict definition\n\nclass TP(TypedDict):\n    a: ReadOnly[ReadOnly[int]]              # E: \"ReadOnly[]\" type cannot be nested\n    b: ReadOnly[NotRequired[ReadOnly[str]]] # E: \"ReadOnly[]\" type cannot be nested\n    c: NotRequired[Required[int]]           # E: \"Required[]\" type cannot be nested\n    d: Required[NotRequired[int]]           # E: \"NotRequired[]\" type cannot be nested\n    e: Required[ReadOnly[NotRequired[int]]] # E: \"NotRequired[]\" type cannot be nested\n    f: ReadOnly[ReadOnly[ReadOnly[int]]]    # E: \"ReadOnly[]\" type cannot be nested\n    g: Required[Required[int]]              # E: \"Required[]\" type cannot be nested\n    h: NotRequired[NotRequired[int]]        # E: \"NotRequired[]\" type cannot be nested\n\n    j: NotRequired[ReadOnly[Required[ReadOnly[int]]]]  # E: \"Required[]\" type cannot be nested \\\n                                                       # E: \"ReadOnly[]\" type cannot be nested\n\n    k: ReadOnly  # E: \"ReadOnly[]\" must have exactly one type argument\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictAnnotatedWithSpecialForms]\nfrom typing import NotRequired, ReadOnly, Required, TypedDict\nfrom typing_extensions import Annotated\n\nclass A(TypedDict):\n    a: Annotated[NotRequired[ReadOnly[int]], \"\"]  # ok\n    b: NotRequired[ReadOnly[Annotated[int, \"\"]]]  # ok\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypedDictReadOnlyCovariant]\nfrom typing import ReadOnly, TypedDict, Union\n\nclass A(TypedDict):\n    a: ReadOnly[Union[int, str]]\n\nclass A2(TypedDict):\n    a: ReadOnly[int]\n\nclass B(TypedDict):\n    a: int\n\nclass B2(TypedDict):\n    a: Union[int, str]\n\nclass B3(TypedDict):\n    a: int\n\ndef fa(a: A) -> None: ...\ndef fa2(a: A2) -> None: ...\n\nb: B = {\"a\": 1}\nfa(b)\nfa2(b)\nb2: B2 = {\"a\": 1}\nfa(b2)\nfa2(b2)  # E: Argument 1 to \"fa2\" has incompatible type \"B2\"; expected \"A2\"\n\nclass C(TypedDict):\n    a: ReadOnly[Union[int, str]]\n    b: Union[str, bytes]\n\nclass D(TypedDict):\n    a: int\n    b: str\n\nd: D = {\"a\": 1, \"b\": \"x\"}\nc: C = d  # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testTypedDictFinalAndClassVar]\nfrom typing import TypedDict, Final, ClassVar\n\nclass My(TypedDict):\n    a: Final      # E: Final[...] can't be used inside a TypedDict\n    b: Final[int] # E: Final[...] can't be used inside a TypedDict\n    c: ClassVar       # E: ClassVar[...] can't be used inside a TypedDict\n    d: ClassVar[int]  # E: ClassVar[...] can't be used inside a TypedDict\n\nFunc = TypedDict('Func', {\n    'a': Final,         # E: Final[...] can't be used inside a TypedDict\n    'b': Final[int],    # E: Final[...] can't be used inside a TypedDict\n    'c': ClassVar,      # E: ClassVar[...] can't be used inside a TypedDict\n    'd': ClassVar[int], # E: ClassVar[...] can't be used inside a TypedDict\n})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typeguard.test",
    "content": "[case testTypeGuardBasic]\nfrom typing_extensions import TypeGuard\nclass Point: pass\ndef is_point(a: object) -> TypeGuard[Point]: pass\ndef main(a: object) -> None:\n    if is_point(a):\n        reveal_type(a)  # N: Revealed type is \"__main__.Point\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardTypeArgsNone]\nfrom typing_extensions import TypeGuard\ndef foo(a: object) -> TypeGuard:  # E: TypeGuard must have exactly one type argument\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardTypeArgsTooMany]\nfrom typing_extensions import TypeGuard\ndef foo(a: object) -> TypeGuard[int, int]:  # E: TypeGuard must have exactly one type argument\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardTypeArgType]\nfrom typing_extensions import TypeGuard\ndef foo(a: object) -> TypeGuard[42]:  # E: Invalid type: try using Literal[42] instead?\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardRepr]\nfrom typing_extensions import TypeGuard\ndef foo(a: object) -> TypeGuard[int]:\n    pass\nreveal_type(foo)  # N: Revealed type is \"def (a: builtins.object) -> TypeGuard[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardCallArgsNone]\nfrom typing_extensions import TypeGuard\nclass Point: pass\n\ndef is_point() -> TypeGuard[Point]: pass  # E: TypeGuard functions must have a positional argument\ndef main(a: object) -> None:\n    if is_point():\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardCallArgsMultiple]\nfrom typing_extensions import TypeGuard\nclass Point: pass\ndef is_point(a: object, b: object) -> TypeGuard[Point]: pass\ndef main(a: object, b: object) -> None:\n    if is_point(a, b):\n        reveal_type(a)  # N: Revealed type is \"__main__.Point\"\n        reveal_type(b)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardTypeVarReturn]\nfrom typing import Callable, Optional, TypeVar\nfrom typing_extensions import TypeGuard\nT = TypeVar('T')\ndef is_str(x: object) -> TypeGuard[str]: pass\ndef main(x: object, type_check_func: Callable[[object], TypeGuard[T]]) -> T:\n    if not type_check_func(x):\n        raise Exception()\n    return x\nreveal_type(main(\"a\", is_str))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/exception.pyi]\n\n[case testTypeGuardIsBool]\nfrom typing_extensions import TypeGuard\ndef f(a: TypeGuard[int]) -> None: pass\nreveal_type(f)  # N: Revealed type is \"def (a: builtins.bool)\"\na: TypeGuard[int]\nreveal_type(a)  # N: Revealed type is \"builtins.bool\"\nclass C:\n    a: TypeGuard[int]\nreveal_type(C().a)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardWithTypeVar]\nfrom typing import TypeVar, Tuple\nfrom typing_extensions import TypeGuard\nT = TypeVar('T')\ndef is_two_element_tuple(a: Tuple[T, ...]) -> TypeGuard[Tuple[T, T]]: pass\ndef main(a: Tuple[T, ...]):\n    if is_two_element_tuple(a):\n        reveal_type(a)  # N: Revealed type is \"Tuple[T`-1, T`-1]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardPassedAsTypeVarIsBool]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import TypeGuard\nT = TypeVar('T')\ndef is_str(x: object) -> TypeGuard[str]: ...\ndef main(f: Callable[[object], T]) -> T: ...\nreveal_type(main(is_str))  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNonOverlapping]\nfrom typing import List\nfrom typing_extensions import TypeGuard\ndef is_str_list(a: List[object]) -> TypeGuard[List[str]]: pass\ndef main(a: List[object]):\n    if is_str_list(a):\n        reveal_type(a)\n    reveal_type(a)  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardUnionIn]\nfrom typing import Union\nfrom typing_extensions import TypeGuard\ndef is_foo(a: Union[int, str]) -> TypeGuard[str]: pass\ndef main(a: Union[str, int]) -> None:\n    if is_foo(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    reveal_type(a)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardUnionOut]\nfrom typing import Union\nfrom typing_extensions import TypeGuard\ndef is_foo(a: object) -> TypeGuard[Union[int, str]]: pass\ndef main(a: object) -> None:\n    if is_foo(a):\n        reveal_type(a)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNonzeroFloat]\nfrom typing_extensions import TypeGuard\ndef is_nonzero(a: object) -> TypeGuard[float]: pass\ndef main(a: int):\n    if is_nonzero(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardHigherOrder]\nfrom typing import Callable, TypeVar, Iterable, List\nfrom typing_extensions import TypeGuard\nT = TypeVar('T')\nR = TypeVar('R')\ndef filter(f: Callable[[T], TypeGuard[R]], it: Iterable[T]) -> Iterable[R]: pass\ndef is_float(a: object) -> TypeGuard[float]: pass\na: List[object] = [\"a\", 0, 0.0]\nb = filter(is_float, a)\nreveal_type(b)  # N: Revealed type is \"typing.Iterable[builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardMethod]\nfrom typing_extensions import TypeGuard\nclass C:\n    def main(self, a: object) -> None:\n        if self.is_float(a):\n            reveal_type(self)  # N: Revealed type is \"__main__.C\"\n            reveal_type(a)  # N: Revealed type is \"builtins.float\"\n    def is_float(self, a: object) -> TypeGuard[float]: pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardCrossModule]\nimport guard\nfrom points import Point\ndef main(a: object) -> None:\n    if guard.is_point(a):\n        reveal_type(a)  # N: Revealed type is \"points.Point\"\n[file guard.py]\nfrom typing_extensions import TypeGuard\nimport points\ndef is_point(a: object) -> TypeGuard[points.Point]: pass\n[file points.py]\nclass Point: pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardBodyRequiresBool]\nfrom typing_extensions import TypeGuard\ndef is_float(a: object) -> TypeGuard[float]:\n    return \"not a bool\"  # E: Incompatible return value type (got \"str\", expected \"bool\")\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNarrowToTypedDict]\nfrom typing import Dict, TypedDict\nfrom typing_extensions import TypeGuard\nclass User(TypedDict):\n    name: str\n    id: int\ndef is_user(a: Dict[str, object]) -> TypeGuard[User]:\n    return isinstance(a.get(\"name\"), str) and isinstance(a.get(\"id\"), int)\ndef main(a: Dict[str, object]) -> None:\n    if is_user(a):\n        reveal_type(a)  # N: Revealed type is \"Never\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypeGuardInAssert]\nfrom typing_extensions import TypeGuard\ndef is_float(a: object) -> TypeGuard[float]: pass\ndef main(a: object) -> None:\n    assert is_float(a)\n    reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardFromAny]\nfrom typing import Any\nfrom typing_extensions import TypeGuard\ndef is_objfloat(a: object) -> TypeGuard[float]: pass\ndef is_anyfloat(a: Any) -> TypeGuard[float]: pass\ndef objmain(a: object) -> None:\n    if is_objfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n    if is_anyfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\ndef anymain(a: Any) -> None:\n    if is_objfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n    if is_anyfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNegatedAndElse]\nfrom typing import Union\nfrom typing_extensions import TypeGuard\ndef is_int(a: object) -> TypeGuard[int]: pass\ndef is_str(a: object) -> TypeGuard[str]: pass\ndef intmain(a: Union[int, str]) -> None:\n    if not is_int(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\ndef strmain(a: Union[int, str]) -> None:\n    if is_str(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardClassMethod]\nfrom typing_extensions import TypeGuard\nclass C:\n    @classmethod\n    def is_float(cls, a: object) -> TypeGuard[float]: pass\n    def method(self, a: object) -> None:\n        if self.is_float(a):\n            reveal_type(a)  # N: Revealed type is \"builtins.float\"\ndef main(a: object) -> None:\n    if C.is_float(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeGuardRequiresPositionalArgs]\nfrom typing_extensions import TypeGuard\ndef is_float(a: object, b: object = 0) -> TypeGuard[float]: pass\ndef main1(a: object) -> None:\n    if is_float(a=a, b=1):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n\n    if is_float(b=1, a=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n\n    # This is debatable -- should we support these cases?\n\n    ta = (a,)\n    if is_float(*ta):  # E: Type guard on star argument is not yet supported\n        reveal_type(ta)  # N: Revealed type is \"Tuple[builtins.object]\"\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n\n    la = [a]\n    if is_float(*la):  # E: Type guard on star argument is not yet supported\n        reveal_type(la)  # N: Revealed type is \"builtins.list[builtins.object]\"\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardOverload]\nfrom typing import overload, Any, Callable, Iterable, Iterator, List, Optional, TypeVar\nfrom typing_extensions import TypeGuard\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\n@overload\ndef filter(f: Callable[[T], TypeGuard[R]], it: Iterable[T]) -> Iterator[R]: ...\n@overload\ndef filter(f: Callable[[T], bool], it: Iterable[T]) -> Iterator[T]: ...\ndef filter(*args): pass\n\ndef is_int_typeguard(a: object) -> TypeGuard[int]: pass\ndef is_int_bool(a: object) -> bool: pass\n\ndef main(a: List[Optional[int]]) -> None:\n    bb = filter(lambda x: x is not None, a)\n    reveal_type(bb)  # N: Revealed type is \"typing.Iterator[Union[builtins.int, None]]\"\n    # Also, if you replace 'bool' with 'Any' in the second overload, bb is Iterator[Any]\n    cc = filter(is_int_typeguard, a)\n    reveal_type(cc)  # N: Revealed type is \"typing.Iterator[builtins.int]\"\n    dd = filter(is_int_bool, a)\n    reveal_type(dd)  # N: Revealed type is \"typing.Iterator[Union[builtins.int, None]]\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeGuardDecorated]\nfrom typing import TypeVar\nfrom typing_extensions import TypeGuard\nT = TypeVar(\"T\")\ndef decorator(f: T) -> T: pass\n@decorator\ndef is_float(a: object) -> TypeGuard[float]:\n    pass\ndef main(a: object) -> None:\n    if is_float(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardMethodOverride]\nfrom typing_extensions import TypeGuard\nclass C:\n    def is_float(self, a: object) -> TypeGuard[float]: pass\nclass D(C):\n    def is_float(self, a: object) -> bool: pass  # Fail\n[builtins fixtures/tuple.pyi]\n[out]\nmain:5: error: Signature of \"is_float\" incompatible with supertype \"C\"\nmain:5: note:      Superclass:\nmain:5: note:          def is_float(self, a: object) -> TypeGuard[float]\nmain:5: note:      Subclass:\nmain:5: note:          def is_float(self, a: object) -> bool\n\n[case testTypeGuardInAnd]\nfrom typing import Any\nfrom typing_extensions import TypeGuard\nimport types\ndef isclass(a: object) -> bool:\n    pass\ndef ismethod(a: object) -> TypeGuard[float]:\n    pass\ndef isfunction(a: object) -> TypeGuard[str]:\n    pass\ndef isclassmethod(obj: Any) -> bool:\n    if ismethod(obj) and obj.__self__ is not None and isclass(obj.__self__):  # E: \"float\" has no attribute \"__self__\" \\\n                                                                              # E: \"float\" has no attribute \"__self__\"\n        return True\n\n    return False\ndef coverage(obj: Any) -> bool:\n    if not (ismethod(obj) or isfunction(obj)):\n        return True\n    return False\n[builtins fixtures/classmethod.pyi]\n\n[case testAssignToTypeGuardedVariable1]\nfrom typing_extensions import TypeGuard\n\nclass A: pass\nclass B(A): pass\n\ndef guard(a: A) -> TypeGuard[B]:\n    pass\n\na = A()\nif not guard(a):\n    a = A()\n[builtins fixtures/tuple.pyi]\n\n[case testAssignToTypeGuardedVariable2]\nfrom typing_extensions import TypeGuard\n\nclass A: pass\nclass B: pass\n\ndef guard(a: A) -> TypeGuard[B]:\n    pass\n\na = A()\nif not guard(a):\n    a = A()\n[builtins fixtures/tuple.pyi]\n\n[case testAssignToTypeGuardedVariable3]\nfrom typing_extensions import TypeGuard\n\nclass A: pass\nclass B: pass\n\ndef guard(a: A) -> TypeGuard[B]:\n    pass\n\na = A()\nif guard(a):\n    reveal_type(a)  # N: Revealed type is \"__main__.A & __main__.B\"\n    a = B()  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    reveal_type(a)  # N: Revealed type is \"__main__.A & __main__.B\"\n    a = A()\n    reveal_type(a)  # N: Revealed type is \"__main__.A\"\nreveal_type(a)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNestedRestrictionAny]\nfrom typing_extensions import TypeGuard\nfrom typing import Any\n\nclass A: ...\ndef f(x: object) -> TypeGuard[A]: ...\ndef g(x: object) -> None: ...\n\ndef test(x: Any) -> None:\n    if not(f(x) or x):\n        return\n    g(reveal_type(x))  # N: Revealed type is \"Union[__main__.A, Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNestedRestrictionUnionOther]\nfrom typing_extensions import TypeGuard\nfrom typing import Any\n\nclass A: ...\nclass B: ...\ndef f(x: object) -> TypeGuard[A]: ...\ndef f2(x: object) -> TypeGuard[B]: ...\ndef g(x: object) -> None: ...\n\ndef test(x: object) -> None:\n    if not(f(x) or f2(x)):\n        return\n    g(reveal_type(x))  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardComprehensionSubtype]\nfrom typing import List\nfrom typing_extensions import TypeGuard\n\nclass Base: ...\nclass Foo(Base): ...\nclass Bar(Base): ...\n\ndef is_foo(item: object) -> TypeGuard[Foo]:\n    return isinstance(item, Foo)\n\ndef is_bar(item: object) -> TypeGuard[Bar]:\n    return isinstance(item, Bar)\n\ndef foobar(items: List[object]):\n    a: List[Base] = [x for x in items if is_foo(x) or is_bar(x)]\n    b: List[Base] = [x for x in items if is_foo(x)]\n    c: List[Bar] = [x for x in items if is_foo(x)]  # E: list comprehension has incompatible type list[Foo]; expected list[Bar]\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardNestedRestrictionUnionIsInstance]\nfrom typing_extensions import TypeGuard\nfrom typing import Any, List\n\nclass A: ...\ndef f(x: List[object]) -> TypeGuard[List[str]]: ...\ndef g(x: object) -> None: ...\n\ndef test(x: List[object]) -> None:\n    if not(f(x) or isinstance(x, A)):\n        return\n    g(reveal_type(x))  # N: Revealed type is \"builtins.list[builtins.object] & __main__.A\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardMultipleCondition]\nfrom typing_extensions import TypeGuard\nfrom typing import Any, List\n\nclass Foo: ...\nclass Bar: ...\n\ndef is_foo(item: object) -> TypeGuard[Foo]:\n    return isinstance(item, Foo)\n\ndef is_bar(item: object) -> TypeGuard[Bar]:\n    return isinstance(item, Bar)\n\ndef foobar(x: object):\n    if not isinstance(x, Foo) or not isinstance(x, Bar):\n        return\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo & __main__.Bar\"\n\ndef foobar_typeguard(x: object):\n    if not is_foo(x) or not is_bar(x):\n        return\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo & __main__.Bar\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardAsFunctionArgAsBoolSubtype]\nfrom typing import Callable\nfrom typing_extensions import TypeGuard\n\ndef accepts_bool(f: Callable[[object], bool]): pass\n\ndef with_bool_typeguard(o: object) -> TypeGuard[bool]: pass\ndef with_str_typeguard(o: object) -> TypeGuard[str]: pass\ndef with_bool(o: object) -> bool: pass\n\naccepts_bool(with_bool_typeguard)\naccepts_bool(with_str_typeguard)\naccepts_bool(with_bool)\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardAsFunctionArg]\nfrom typing import Callable\nfrom typing_extensions import TypeGuard\n\ndef accepts_typeguard(f: Callable[[object], TypeGuard[bool]]): pass\ndef different_typeguard(f: Callable[[object], TypeGuard[str]]): pass\n\ndef with_typeguard(o: object) -> TypeGuard[bool]: pass\ndef with_bool(o: object) -> bool: pass\n\naccepts_typeguard(with_typeguard)\naccepts_typeguard(with_bool)  # E: Argument 1 to \"accepts_typeguard\" has incompatible type \"Callable[[object], bool]\"; expected \"Callable[[object], TypeGuard[bool]]\"\n\ndifferent_typeguard(with_typeguard)  # E: Argument 1 to \"different_typeguard\" has incompatible type \"Callable[[object], TypeGuard[bool]]\"; expected \"Callable[[object], TypeGuard[str]]\"\ndifferent_typeguard(with_bool)  # E: Argument 1 to \"different_typeguard\" has incompatible type \"Callable[[object], bool]\"; expected \"Callable[[object], TypeGuard[str]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardAsGenericFunctionArg]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import TypeGuard\n\nT = TypeVar('T')\n\ndef accepts_typeguard(f: Callable[[object], TypeGuard[T]]): pass\n\ndef with_bool_typeguard(o: object) -> TypeGuard[bool]: pass\ndef with_str_typeguard(o: object) -> TypeGuard[str]: pass\ndef with_bool(o: object) -> bool: pass\n\naccepts_typeguard(with_bool_typeguard)\naccepts_typeguard(with_str_typeguard)\naccepts_typeguard(with_bool)  # E: Argument 1 to \"accepts_typeguard\" has incompatible type \"Callable[[object], bool]\"; expected \"Callable[[object], TypeGuard[Never]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardAsOverloadedFunctionArg]\n# https://github.com/python/mypy/issues/11307\nfrom typing import Callable, TypeVar, Generic, Any, overload\nfrom typing_extensions import TypeGuard\n\n_T = TypeVar('_T')\n\nclass filter(Generic[_T]):\n    @overload\n    def __init__(self, function: Callable[[object], TypeGuard[_T]]) -> None: pass\n    @overload\n    def __init__(self, function: Callable[[_T], Any]) -> None: pass\n    def __init__(self, function): pass\n\ndef is_int_typeguard(a: object) -> TypeGuard[int]: pass\ndef returns_bool(a: object) -> bool: pass\n\nreveal_type(filter(is_int_typeguard))  # N: Revealed type is \"__main__.filter[builtins.int]\"\nreveal_type(filter(returns_bool))  # N: Revealed type is \"__main__.filter[builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardSubtypingVariance]\nfrom typing import Callable\nfrom typing_extensions import TypeGuard\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\ndef accepts_typeguard(f: Callable[[object], TypeGuard[B]]): pass\n\ndef with_typeguard_a(o: object) -> TypeGuard[A]: pass\ndef with_typeguard_b(o: object) -> TypeGuard[B]: pass\ndef with_typeguard_c(o: object) -> TypeGuard[C]: pass\n\naccepts_typeguard(with_typeguard_a)  # E: Argument 1 to \"accepts_typeguard\" has incompatible type \"Callable[[object], TypeGuard[A]]\"; expected \"Callable[[object], TypeGuard[B]]\"\naccepts_typeguard(with_typeguard_b)\naccepts_typeguard(with_typeguard_c)\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardWithIdentityGeneric]\nfrom typing import TypeVar\nfrom typing_extensions import TypeGuard\n\n_T = TypeVar(\"_T\")\n\ndef identity(val: _T) -> TypeGuard[_T]:\n    pass\n\ndef func1(name: _T):\n    reveal_type(name)  # N: Revealed type is \"_T`-1\"\n    if identity(name):\n        reveal_type(name)  # N: Revealed type is \"_T`-1\"\n\ndef func2(name: str):\n    reveal_type(name)  # N: Revealed type is \"builtins.str\"\n    if identity(name):\n        reveal_type(name)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardWithGenericInstance]\nfrom typing import TypeVar, List\nfrom typing_extensions import TypeGuard\n\n_T = TypeVar(\"_T\")\n\ndef is_list_of_str(val: _T) -> TypeGuard[List[_T]]:\n    pass\n\ndef func(name: str):\n    reveal_type(name)  # N: Revealed type is \"builtins.str\"\n    if is_list_of_str(name):\n        reveal_type(name)  # N: Revealed type is \"builtins.str & builtins.list[builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardWithTupleGeneric]\nfrom typing import TypeVar, Tuple\nfrom typing_extensions import TypeGuard\n\n_T = TypeVar(\"_T\")\n\ndef is_two_element_tuple(val: Tuple[_T, ...]) -> TypeGuard[Tuple[_T, _T]]:\n    pass\n\ndef func(names: Tuple[str, ...]):\n    reveal_type(names)  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n    if is_two_element_tuple(names):\n        reveal_type(names)  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardErroneousDefinitionFails]\nfrom typing_extensions import TypeGuard\n\nclass Z:\n    def typeguard1(self, *, x: object) -> TypeGuard[int]:  # line 4\n        ...\n\n    @staticmethod\n    def typeguard2(x: object) -> TypeGuard[int]:\n        ...\n\n    @staticmethod  # line 11\n    def typeguard3(*, x: object) -> TypeGuard[int]:\n        ...\n\ndef bad_typeguard(*, x: object) -> TypeGuard[int]: # line 15\n    ...\n\n# In Python 3.8 the line number associated with FunctionDef nodes changed\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:4: error: TypeGuard functions must have a positional argument\nmain:4: note: If you want to type-guard the implicit argument, use \"-> self is builtins.int\" instead.\nmain:12: error: TypeGuard functions must have a positional argument\nmain:15: error: TypeGuard functions must have a positional argument\n\n[case testTypeGuardWithKeywordArg]\nfrom typing_extensions import TypeGuard\n\nclass Z:\n    def typeguard(self, x: object) -> TypeGuard[int]:\n        ...\n\ndef typeguard(x: object) -> TypeGuard[int]:\n    ...\n\nn: object\nif typeguard(x=n):\n    reveal_type(n)  # N: Revealed type is \"builtins.int\"\n\nif Z().typeguard(x=n):\n    reveal_type(n)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testStaticMethodTypeGuard]\nfrom typing_extensions import TypeGuard\n\nclass Y:\n    @staticmethod\n    def typeguard(h: object) -> TypeGuard[int]:\n        ...\n\nx: object\nif Y().typeguard(x):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nif Y.typeguard(x):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeGuardKwargFollowingThroughOverloaded]\nfrom typing import overload, Union\nfrom typing_extensions import TypeGuard\n\n@overload\ndef typeguard(x: object, y: str) -> TypeGuard[str]:\n    ...\n\n@overload\ndef typeguard(x: object, y: int) -> TypeGuard[int]:\n    ...\n\ndef typeguard(x: object, y: Union[int, str]) -> Union[TypeGuard[int], TypeGuard[str]]:\n    ...\n\nx: object\nif typeguard(x=x, y=42):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif typeguard(y=42, x=x):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif typeguard(x=x, y=\"42\"):\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\nif typeguard(y=\"42\", x=x):\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testGenericAliasWithTypeGuard]\nfrom typing import Callable, List, TypeVar\nfrom typing_extensions import TypeGuard, TypeAlias\n\nA = Callable[[object], TypeGuard[List[T]]]\ndef foo(x: object) -> TypeGuard[List[str]]: ...\n\ndef test(f: A[T]) -> T: ...\nreveal_type(test(foo))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testNoCrashOnDunderCallTypeGuard]\nfrom typing_extensions import TypeGuard\n\nclass A:\n    def __call__(self, x) -> TypeGuard[int]:\n        return True\n\na: A\nassert a(x=1)\n\nx: object\nassert a(x=x)\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typeis.test",
    "content": "[case testTypeIsBasic]\nfrom typing_extensions import TypeIs\nclass Point: pass\ndef is_point(a: object) -> TypeIs[Point]: pass\ndef main(a: object) -> None:\n    if is_point(a):\n        reveal_type(a)  # N: Revealed type is \"__main__.Point\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsElif]\nfrom typing_extensions import TypeIs\nfrom typing import Union\nclass Point: pass\ndef is_point(a: object) -> TypeIs[Point]: pass\nclass Line: pass\ndef is_line(a: object) -> TypeIs[Line]: pass\ndef main(a: Union[Point, Line, int]) -> None:\n    if is_point(a):\n        reveal_type(a)  # N: Revealed type is \"__main__.Point\"\n    elif is_line(a):\n        reveal_type(a)  # N: Revealed type is \"__main__.Line\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsTypeArgsNone]\nfrom typing_extensions import TypeIs\ndef foo(a: object) -> TypeIs:  # E: TypeIs must have exactly one type argument\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsTypeArgsTooMany]\nfrom typing_extensions import TypeIs\ndef foo(a: object) -> TypeIs[int, int]:  # E: TypeIs must have exactly one type argument\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsTypeArgType]\nfrom typing_extensions import TypeIs\ndef foo(a: object) -> TypeIs[42]:  # E: Invalid type: try using Literal[42] instead?\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsRepr]\nfrom typing_extensions import TypeIs\ndef foo(a: object) -> TypeIs[int]:\n    pass\nreveal_type(foo)  # N: Revealed type is \"def (a: builtins.object) -> TypeIs[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsCallArgsNone]\nfrom typing_extensions import TypeIs\nclass Point: pass\n\ndef is_point() -> TypeIs[Point]: pass  # E: \"TypeIs\" functions must have a positional argument\ndef main(a: object) -> None:\n    if is_point():\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsCallArgsMultiple]\nfrom typing_extensions import TypeIs\nclass Point: pass\ndef is_point(a: object, b: object) -> TypeIs[Point]: pass\ndef main(a: object, b: object) -> None:\n    if is_point(a, b):\n        reveal_type(a)  # N: Revealed type is \"__main__.Point\"\n        reveal_type(b)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsIsBool]\nfrom typing_extensions import TypeIs\ndef f(a: TypeIs[int]) -> None: pass\nreveal_type(f)  # N: Revealed type is \"def (a: builtins.bool)\"\na: TypeIs[int]\nreveal_type(a)  # N: Revealed type is \"builtins.bool\"\nclass C:\n    a: TypeIs[int]\nreveal_type(C().a)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsWithTypeVar]\nfrom typing import TypeVar, Tuple, Type\nfrom typing_extensions import TypeIs\nT = TypeVar('T')\ndef is_tuple_of_type(a: Tuple[object, ...], typ: Type[T]) -> TypeIs[Tuple[T, ...]]: pass\ndef main(a: Tuple[object, ...]):\n    if is_tuple_of_type(a, int):\n        reveal_type(a)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsTypeVarReturn]\nfrom typing import Callable, Optional, TypeVar\nfrom typing_extensions import TypeIs\nT = TypeVar('T')\ndef is_str(x: object) -> TypeIs[str]: pass\ndef main(x: object, type_check_func: Callable[[object], TypeIs[T]]) -> T:\n    if not type_check_func(x):\n        raise Exception()\n    return x\nreveal_type(main(\"a\", is_str))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/exception.pyi]\n\n[case testTypeIsPassedAsTypeVarIsBool]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import TypeIs\nT = TypeVar('T')\ndef is_str(x: object) -> TypeIs[str]: pass\ndef main(f: Callable[[object], T]) -> T: pass\nreveal_type(main(is_str))  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsUnionIn]\nfrom typing import Union\nfrom typing_extensions import TypeIs\ndef is_foo(a: Union[int, str]) -> TypeIs[str]: pass\ndef main(a: Union[str, int]) -> None:\n    if is_foo(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n    reveal_type(a)  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsUnionOut]\nfrom typing import Union\nfrom typing_extensions import TypeIs\ndef is_foo(a: object) -> TypeIs[Union[int, str]]: pass\ndef main(a: object) -> None:\n    if is_foo(a):\n        reveal_type(a)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsNonzeroFloat]\nfrom typing_extensions import TypeIs\ndef is_nonzero(a: object) -> TypeIs[float]: pass\ndef main(a: int):\n    if is_nonzero(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsHigherOrder]\nfrom typing import Callable, TypeVar, Iterable, List\nfrom typing_extensions import TypeIs\nT = TypeVar('T')\nR = TypeVar('R')\ndef filter(f: Callable[[T], TypeIs[R]], it: Iterable[T]) -> Iterable[R]: pass\ndef is_float(a: object) -> TypeIs[float]: pass\na: List[object] = [\"a\", 0, 0.0]\nb = filter(is_float, a)\nreveal_type(b)  # N: Revealed type is \"typing.Iterable[builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsMethod]\nfrom typing_extensions import TypeIs\nclass C:\n    def main(self, a: object) -> None:\n        if self.is_float(a):\n            reveal_type(self)  # N: Revealed type is \"__main__.C\"\n            reveal_type(a)  # N: Revealed type is \"builtins.float\"\n    def is_float(self, a: object) -> TypeIs[float]: pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsCrossModule]\nimport guard\nfrom points import Point\ndef main(a: object) -> None:\n    if guard.is_point(a):\n        reveal_type(a)  # N: Revealed type is \"points.Point\"\n[file guard.py]\nfrom typing_extensions import TypeIs\nimport points\ndef is_point(a: object) -> TypeIs[points.Point]: pass\n[file points.py]\nclass Point: pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsBodyRequiresBool]\nfrom typing_extensions import TypeIs\ndef is_float(a: object) -> TypeIs[float]:\n    return \"not a bool\"  # E: Incompatible return value type (got \"str\", expected \"bool\")\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsNarrowToTypedDict]\nfrom typing import Mapping, TypedDict\nfrom typing_extensions import TypeIs\nclass User(TypedDict):\n    name: str\n    id: int\ndef is_user(a: Mapping[str, object]) -> TypeIs[User]:\n    return isinstance(a.get(\"name\"), str) and isinstance(a.get(\"id\"), int)\ndef main(a: Mapping[str, object]) -> None:\n    if is_user(a):\n        reveal_type(a)  # N: Revealed type is \"TypedDict('__main__.User', {'name': builtins.str, 'id': builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTypeIsInAssert]\nfrom typing_extensions import TypeIs\ndef is_float(a: object) -> TypeIs[float]: pass\ndef main(a: object) -> None:\n    assert is_float(a)\n    reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsFromAny]\nfrom typing import Any\nfrom typing_extensions import TypeIs\ndef is_objfloat(a: object) -> TypeIs[float]: pass\ndef is_anyfloat(a: Any) -> TypeIs[float]: pass\ndef objmain(a: object) -> None:\n    if is_objfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n    if is_anyfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\ndef anymain(a: Any) -> None:\n    if is_objfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n    if is_anyfloat(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsNegatedAndElse]\nfrom typing import Union\nfrom typing_extensions import TypeIs\ndef is_int(a: object) -> TypeIs[int]: pass\ndef is_str(a: object) -> TypeIs[str]: pass\ndef intmain(a: Union[int, str]) -> None:\n    if not is_int(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\ndef strmain(a: Union[int, str]) -> None:\n    if is_str(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsClassMethod]\nfrom typing_extensions import TypeIs\nclass C:\n    @classmethod\n    def is_float(cls, a: object) -> TypeIs[float]: pass\n    def method(self, a: object) -> None:\n        if self.is_float(a):\n            reveal_type(a)  # N: Revealed type is \"builtins.float\"\ndef main(a: object) -> None:\n    if C.is_float(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeIsRequiresPositionalArgs]\nfrom typing_extensions import TypeIs\ndef is_float(a: object, b: object = 0) -> TypeIs[float]: pass\ndef main1(a: object) -> None:\n    if is_float(a=a, b=1):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n\n    if is_float(b=1, a=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsOverload]\nfrom typing import overload, Any, Callable, Iterable, Iterator, List, Optional, TypeVar\nfrom typing_extensions import TypeIs\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\n\n@overload\ndef filter(f: Callable[[T], TypeIs[R]], it: Iterable[T]) -> Iterator[R]: ...\n@overload\ndef filter(f: Callable[[T], bool], it: Iterable[T]) -> Iterator[T]: ...\ndef filter(*args): pass\n\ndef is_int_typeis(a: object) -> TypeIs[int]: pass\ndef is_int_bool(a: object) -> bool: pass\n\ndef main(a: List[Optional[int]]) -> None:\n    bb = filter(lambda x: x is not None, a)\n    reveal_type(bb)  # N: Revealed type is \"typing.Iterator[Union[builtins.int, None]]\"\n    # Also, if you replace 'bool' with 'Any' in the second overload, bb is Iterator[Any]\n    cc = filter(is_int_typeis, a)\n    reveal_type(cc)  # N: Revealed type is \"typing.Iterator[builtins.int]\"\n    dd = filter(is_int_bool, a)\n    reveal_type(dd)  # N: Revealed type is \"typing.Iterator[Union[builtins.int, None]]\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeIsDecorated]\nfrom typing import TypeVar\nfrom typing_extensions import TypeIs\nT = TypeVar(\"T\")\ndef decorator(f: T) -> T: pass\n@decorator\ndef is_float(a: object) -> TypeIs[float]:\n    pass\ndef main(a: object) -> None:\n    if is_float(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsMethodOverride]\nfrom typing_extensions import TypeIs\nclass C:\n    def is_float(self, a: object) -> TypeIs[float]: pass\nclass D(C):\n    def is_float(self, a: object) -> bool: pass  # Fail\n[builtins fixtures/tuple.pyi]\n[out]\nmain:5: error: Signature of \"is_float\" incompatible with supertype \"C\"\nmain:5: note:      Superclass:\nmain:5: note:          def is_float(self, a: object) -> TypeIs[float]\nmain:5: note:      Subclass:\nmain:5: note:          def is_float(self, a: object) -> bool\n\n[case testTypeIsInAnd]\nfrom typing import Any\nfrom typing_extensions import TypeIs\ndef isclass(a: object) -> bool:\n    pass\ndef isfloat(a: object) -> TypeIs[float]:\n    pass\ndef isstr(a: object) -> TypeIs[str]:\n    pass\n\ndef coverage1(obj: Any) -> bool:\n    if isfloat(obj) and obj.__self__ is not None and isclass(obj.__self__):  # E: \"float\" has no attribute \"__self__\" # E: \"float\" has no attribute \"__self__\"\n        reveal_type(obj)  # N: Revealed type is \"builtins.float\"\n        return True\n    reveal_type(obj)  # N: Revealed type is \"Any\"\n    return False\n\ndef coverage2(obj: Any) -> bool:\n    if not (isfloat(obj) or isstr(obj)):\n        reveal_type(obj)  # N: Revealed type is \"Any\"\n        return True\n    reveal_type(obj)  # N: Revealed type is \"Union[builtins.float, builtins.str]\"\n    return False\n[builtins fixtures/classmethod.pyi]\n\n[case testAssignToTypeIsedVariable1]\nfrom typing_extensions import TypeIs\n\nclass A: pass\nclass B(A): pass\n\ndef guard(a: A) -> TypeIs[B]:\n    pass\n\na = A()\nif not guard(a):\n    a = A()\n[builtins fixtures/tuple.pyi]\n\n[case testAssignToTypeIsedVariable2]\nfrom typing_extensions import TypeIs\n\nclass A: pass\nclass B: pass\n\ndef guard(a: object) -> TypeIs[B]:\n    pass\n\na = A()\nif not guard(a):\n    a = A()\n[builtins fixtures/tuple.pyi]\n\n[case testAssignToTypeIsedVariable3]\nfrom typing_extensions import TypeIs\n\nclass A: pass\nclass B: pass\n\ndef guard(a: object) -> TypeIs[B]:\n    pass\n\na = A()\nif guard(a):\n    reveal_type(a)  # N: Revealed type is \"__main__.A & __main__.B\"\n    a = B()  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    reveal_type(a)  # N: Revealed type is \"__main__.A & __main__.B\"\n    a = A()\n    reveal_type(a)  # N: Revealed type is \"__main__.A\"\nreveal_type(a)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsNestedRestrictionAny]\nfrom typing_extensions import TypeIs\nfrom typing import Any\n\nclass A: ...\ndef f(x: object) -> TypeIs[A]: ...\ndef g(x: object) -> None: ...\n\ndef test(x: Any) -> None:\n    if not(f(x) or x):\n        return\n    g(reveal_type(x))  # N: Revealed type is \"Union[__main__.A, Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsNestedRestrictionUnionOther]\nfrom typing_extensions import TypeIs\nfrom typing import Any\n\nclass A: ...\nclass B: ...\ndef f(x: object) -> TypeIs[A]: ...\ndef f2(x: object) -> TypeIs[B]: ...\ndef g(x: object) -> None: ...\n\ndef test(x: object) -> None:\n    if not(f(x) or f2(x)):\n        return\n    g(reveal_type(x))  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsComprehensionSubtype]\nfrom typing import List\nfrom typing_extensions import TypeIs\n\nclass Base: ...\nclass Foo(Base): ...\nclass Bar(Base): ...\n\ndef is_foo(item: object) -> TypeIs[Foo]:\n    return isinstance(item, Foo)\n\ndef is_bar(item: object) -> TypeIs[Bar]:\n    return isinstance(item, Bar)\n\ndef foobar(items: List[object]):\n    a: List[Base] = [x for x in items if is_foo(x) or is_bar(x)]\n    b: List[Base] = [x for x in items if is_foo(x)]\n    c: List[Foo] = [x for x in items if is_foo(x)]\n    d: List[Bar] = [x for x in items if is_foo(x)]  # E: list comprehension has incompatible type list[Foo]; expected list[Bar]\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsNestedRestrictionUnionIsInstance]\nfrom typing_extensions import TypeIs\nfrom typing import Any, List\n\nclass A: ...\ndef f(x: List[Any]) -> TypeIs[List[str]]: ...\ndef g(x: object) -> None: ...\n\ndef test(x: List[Any]) -> None:\n    if not(f(x) or isinstance(x, A)):\n        return\n    g(reveal_type(x))  # N: Revealed type is \"Union[builtins.list[builtins.str], builtins.list[Any] & __main__.A]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsMultipleCondition]\nfrom typing_extensions import TypeIs\nfrom typing import Any, List\n\nclass Foo: ...\nclass Bar: ...\n\ndef is_foo(item: object) -> TypeIs[Foo]:\n    return isinstance(item, Foo)\n\ndef is_bar(item: object) -> TypeIs[Bar]:\n    return isinstance(item, Bar)\n\ndef foobar(x: object):\n    if not isinstance(x, Foo) or not isinstance(x, Bar):\n        return\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo & __main__.Bar\"\n\ndef foobar_typeis(x: object):\n    if not is_foo(x) or not is_bar(x):\n        return\n    # Looks like a typo but this is what our unique name generation produces\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo & __main__.Bar\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsAsFunctionArgAsBoolSubtype]\nfrom typing import Callable\nfrom typing_extensions import TypeIs\n\ndef accepts_bool(f: Callable[[object], bool]): pass\n\ndef with_bool_typeis(o: object) -> TypeIs[bool]: pass\ndef with_str_typeis(o: object) -> TypeIs[str]: pass\ndef with_bool(o: object) -> bool: pass\n\naccepts_bool(with_bool_typeis)\naccepts_bool(with_str_typeis)\naccepts_bool(with_bool)\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsAsFunctionArg]\nfrom typing import Callable\nfrom typing_extensions import TypeIs\n\ndef accepts_typeis(f: Callable[[object], TypeIs[bool]]): pass\ndef different_typeis(f: Callable[[object], TypeIs[str]]): pass\n\ndef with_typeis(o: object) -> TypeIs[bool]: pass\ndef with_bool(o: object) -> bool: pass\n\naccepts_typeis(with_typeis)\naccepts_typeis(with_bool)  # E: Argument 1 to \"accepts_typeis\" has incompatible type \"Callable[[object], bool]\"; expected \"Callable[[object], TypeIs[bool]]\"\n\ndifferent_typeis(with_typeis)  # E: Argument 1 to \"different_typeis\" has incompatible type \"Callable[[object], TypeIs[bool]]\"; expected \"Callable[[object], TypeIs[str]]\"\ndifferent_typeis(with_bool)  # E: Argument 1 to \"different_typeis\" has incompatible type \"Callable[[object], bool]\"; expected \"Callable[[object], TypeIs[str]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsAsGenericFunctionArg]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import TypeIs\n\nT = TypeVar('T')\n\ndef accepts_typeis(f: Callable[[object], TypeIs[T]]): pass\n\ndef with_bool_typeis(o: object) -> TypeIs[bool]: pass\ndef with_str_typeis(o: object) -> TypeIs[str]: pass\ndef with_bool(o: object) -> bool: pass\n\naccepts_typeis(with_bool_typeis)\naccepts_typeis(with_str_typeis)\naccepts_typeis(with_bool)  # E: Argument 1 to \"accepts_typeis\" has incompatible type \"Callable[[object], bool]\"; expected \"Callable[[object], TypeIs[Never]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsAsOverloadedFunctionArg]\n# https://github.com/python/mypy/issues/11307\nfrom typing import Callable, TypeVar, Generic, Any, overload\nfrom typing_extensions import TypeIs\n\n_T = TypeVar('_T')\n\nclass filter(Generic[_T]):\n    @overload\n    def __init__(self, function: Callable[[object], TypeIs[_T]]) -> None: pass\n    @overload\n    def __init__(self, function: Callable[[_T], Any]) -> None: pass\n    def __init__(self, function): pass\n\ndef is_int_typeis(a: object) -> TypeIs[int]: pass\ndef returns_bool(a: object) -> bool: pass\n\nreveal_type(filter(is_int_typeis))  # N: Revealed type is \"__main__.filter[builtins.int]\"\nreveal_type(filter(returns_bool))  # N: Revealed type is \"__main__.filter[builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsSubtypingVariance]\nfrom typing import Callable\nfrom typing_extensions import TypeIs\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\ndef accepts_typeis(f: Callable[[object], TypeIs[B]]): pass\n\ndef with_typeis_a(o: object) -> TypeIs[A]: pass\ndef with_typeis_b(o: object) -> TypeIs[B]: pass\ndef with_typeis_c(o: object) -> TypeIs[C]: pass\n\naccepts_typeis(with_typeis_a)  # E: Argument 1 to \"accepts_typeis\" has incompatible type \"Callable[[object], TypeIs[A]]\"; expected \"Callable[[object], TypeIs[B]]\"\naccepts_typeis(with_typeis_b)\naccepts_typeis(with_typeis_c)  # E: Argument 1 to \"accepts_typeis\" has incompatible type \"Callable[[object], TypeIs[C]]\"; expected \"Callable[[object], TypeIs[B]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsWithIdentityGeneric]\nfrom typing import TypeVar\nfrom typing_extensions import TypeIs\n\n_T = TypeVar(\"_T\")\n\ndef identity(val: _T) -> TypeIs[_T]:\n    pass\n\ndef func1(name: _T):\n    reveal_type(name)  # N: Revealed type is \"_T`-1\"\n    if identity(name):\n        reveal_type(name)  # N: Revealed type is \"_T`-1\"\n\ndef func2(name: str):\n    reveal_type(name)  # N: Revealed type is \"builtins.str\"\n    if identity(name):\n        reveal_type(name)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsWithGenericOnSecondParam]\nfrom typing import TypeVar\nfrom typing_extensions import TypeIs\n\n_R = TypeVar(\"_R\")\n\ndef guard(val: object, param: _R) -> TypeIs[_R]:\n    pass\n\ndef func1(name: object):\n    reveal_type(name)  # N: Revealed type is \"builtins.object\"\n    if guard(name, name):\n        reveal_type(name)  # N: Revealed type is \"builtins.object\"\n    if guard(name, 1):\n        reveal_type(name)  # N: Revealed type is \"builtins.int\"\n\ndef func2(name: int):\n    reveal_type(name)  # N: Revealed type is \"builtins.int\"\n    if guard(name, True):\n        reveal_type(name)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsWithGenericInstance]\nfrom typing import TypeVar, List, Iterable\nfrom typing_extensions import TypeIs\n\n_T = TypeVar(\"_T\")\n\ndef is_list_of_str(val: Iterable[_T]) -> TypeIs[List[_T]]:\n    pass\n\ndef func(name: Iterable[str]):\n    reveal_type(name)  # N: Revealed type is \"typing.Iterable[builtins.str]\"\n    if is_list_of_str(name):\n        reveal_type(name)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsWithTupleGeneric]\nfrom typing import TypeVar, Tuple\nfrom typing_extensions import TypeIs\n\n_T = TypeVar(\"_T\")\n\ndef is_two_element_tuple(val: Tuple[_T, ...]) -> TypeIs[Tuple[_T, _T]]:\n    pass\n\ndef func(names: Tuple[str, ...]):\n    reveal_type(names)  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n    if is_two_element_tuple(names):\n        reveal_type(names)  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsErroneousDefinitionFails]\nfrom typing_extensions import TypeIs\n\nclass Z:\n    def typeis1(self, *, x: object) -> TypeIs[int]:  # E: \"TypeIs\" functions must have a positional argument\n        ...\n\n    @staticmethod\n    def typeis2(x: object) -> TypeIs[int]:\n        ...\n\n    @staticmethod\n    def typeis3(*, x: object) -> TypeIs[int]:  # E: \"TypeIs\" functions must have a positional argument\n        ...\n\ndef bad_typeis(*, x: object) -> TypeIs[int]:  # E: \"TypeIs\" functions must have a positional argument\n    ...\n\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeIsWithKeywordArg]\nfrom typing_extensions import TypeIs\n\nclass Z:\n    def typeis(self, x: object) -> TypeIs[int]:\n        ...\n\ndef typeis(x: object) -> TypeIs[int]:\n    ...\n\nn: object\nif typeis(x=n):\n    reveal_type(n)  # N: Revealed type is \"builtins.int\"\n\nif Z().typeis(x=n):\n    reveal_type(n)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testStaticMethodTypeIs]\nfrom typing_extensions import TypeIs\n\nclass Y:\n    @staticmethod\n    def typeis(h: object) -> TypeIs[int]:\n        ...\n\nx: object\nif Y().typeis(x):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nif Y.typeis(x):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeIsKwargFollowingThroughOverloaded]\nfrom typing import overload, Union\nfrom typing_extensions import TypeIs\n\n@overload\ndef typeis(x: object, y: str) -> TypeIs[str]:\n    ...\n\n@overload\ndef typeis(x: object, y: int) -> TypeIs[int]:\n    ...\n\ndef typeis(x: object, y: Union[int, str]) -> Union[TypeIs[int], TypeIs[str]]:\n    ...\n\nx: object\nif typeis(x=x, y=42):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif typeis(y=42, x=x):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif typeis(x=x, y=\"42\"):\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\nif typeis(y=\"42\", x=x):\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testGenericAliasWithTypeIs]\nfrom typing import Callable, List, TypeVar\nfrom typing_extensions import TypeIs\n\nT = TypeVar('T')\nA = Callable[[object], TypeIs[List[T]]]\ndef foo(x: object) -> TypeIs[List[str]]: ...\n\ndef test(f: A[T]) -> T: ...\nreveal_type(test(foo))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testNoCrashOnDunderCallTypeIs]\nfrom typing_extensions import TypeIs\n\nclass A:\n    def __call__(self, x) -> TypeIs[int]:\n        return True\n\na: A\nassert a(x=1)\n\nx: object\nassert a(x=x)\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsMustBeSubtypeFunctions]\nfrom typing_extensions import TypeIs\nfrom typing import List, Sequence, TypeVar\n\ndef f(x: str) -> TypeIs[int]:  # E: Narrowed type \"int\" is not a subtype of input type \"str\"\n    pass\n\nT = TypeVar('T')\n\ndef g(x: List[T]) -> TypeIs[Sequence[T]]:  # E: Narrowed type \"Sequence[T]\" is not a subtype of input type \"List[T]\"\n    pass\n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIsMustBeSubtypeMethods]\nfrom typing_extensions import TypeIs\n\nclass NarrowHolder:\n    @classmethod\n    def cls_narrower_good(cls, x: object) -> TypeIs[int]:\n        pass\n\n    @classmethod\n    def cls_narrower_bad(cls, x: str) -> TypeIs[int]:  # E: Narrowed type \"int\" is not a subtype of input type \"str\"\n        pass\n\n    @staticmethod\n    def static_narrower_good(x: object) -> TypeIs[int]:\n        pass\n\n    @staticmethod\n    def static_narrower_bad(x: str) -> TypeIs[int]:  # E: Narrowed type \"int\" is not a subtype of input type \"str\"\n        pass\n\n    def inst_narrower_good(self, x: object) -> TypeIs[int]:\n        pass\n\n    def inst_narrower_bad(self, x: str) -> TypeIs[int]:  # E: Narrowed type \"int\" is not a subtype of input type \"str\"\n        pass\n\n\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeIsTypeGuardNoSubtyping]\nfrom typing_extensions import TypeGuard, TypeIs\nfrom typing import Callable\n\ndef accept_typeis(x: Callable[[object], TypeIs[str]]):\n    pass\n\ndef accept_typeguard(x: Callable[[object], TypeGuard[str]]):\n    pass\n\ndef typeis(x: object) -> TypeIs[str]:\n    pass\n\ndef typeguard(x: object) -> TypeGuard[str]:\n    pass\n\naccept_typeis(typeis)\naccept_typeis(typeguard)  # E: Argument 1 to \"accept_typeis\" has incompatible type \"Callable[[object], TypeGuard[str]]\"; expected \"Callable[[object], TypeIs[str]]\"\naccept_typeguard(typeis)  # E: Argument 1 to \"accept_typeguard\" has incompatible type \"Callable[[object], TypeIs[str]]\"; expected \"Callable[[object], TypeGuard[str]]\"\naccept_typeguard(typeguard)\n\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typevar-defaults.test",
    "content": "[case testTypeVarDefaultsBasic]\nfrom typing import Generic, TypeVar, ParamSpec, Callable, Tuple, List\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT1 = TypeVar(\"T1\", default=int)\nP1 = ParamSpec(\"P1\", default=[int, str])\nTs1 = TypeVarTuple(\"Ts1\", default=Unpack[Tuple[int, str]])\n\ndef f1(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(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(a: Tuple[Unpack[Ts1]]) -> Tuple[Unpack[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(Generic[T1]): ...\nclass ClassA2(Generic[P1]): ...\nclass ClassA3(Generic[Unpack[Ts1]]): ...\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 testTypeVarDefaultsValid]\nfrom typing import TypeVar, ParamSpec, Any, List, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nS0 = TypeVar(\"S0\")\nS1 = TypeVar(\"S1\", bound=int)\n\nP0 = ParamSpec(\"P0\")\nTs0 = TypeVarTuple(\"Ts0\")\n\nT1 = TypeVar(\"T1\", default=int)\nT2 = TypeVar(\"T2\", bound=float, default=int)\nT3 = TypeVar(\"T3\", bound=List[Any], default=List[int])\nT4 = TypeVar(\"T4\", int, str, default=int)\nT5 = TypeVar(\"T5\", default=S0)\nT6 = TypeVar(\"T6\", bound=float, default=S1)\n# T7 = TypeVar(\"T7\", bound=List[Any], default=List[S0])  # TODO\n\nP1 = ParamSpec(\"P1\", default=[])\nP2 = ParamSpec(\"P2\", default=...)\nP3 = ParamSpec(\"P3\", default=[int, str])\nP4 = ParamSpec(\"P4\", default=P0)\n\nTs1 = TypeVarTuple(\"Ts1\", default=Unpack[Tuple[int]])\nTs2 = TypeVarTuple(\"Ts2\", default=Unpack[Tuple[int, ...]])\n# Ts3 = TypeVarTuple(\"Ts3\", default=Unpack[Ts0])  # TODO\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultsInvalid]\nfrom typing import TypeVar, ParamSpec, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT1 = TypeVar(\"T1\", default=2)  # E: \"2\" is a bare literal and cannot be used here, try Literal[2] instead?\nT2 = TypeVar(\"T2\", default=[int])  # E: Bracketed expression \"[...]\" is not valid as a type \\\n                                   # N: Did you mean \"list[...]\"? \\\n                                   # E: TypeVar \"default\" must be a type\n\nP1 = ParamSpec(\"P1\", default=int)  # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\nP2 = ParamSpec(\"P2\", default=2)  # E: \"2\" is a bare literal and cannot be used here, try Literal[2] instead? \\\n                                 # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\nP3 = ParamSpec(\"P3\", default=(2, int))  # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\nP4 = ParamSpec(\"P4\", default=[2, int])  # E: \"2\" is a bare literal and cannot be used here, try Literal[2] instead?\n\nTs1 = TypeVarTuple(\"Ts1\", default=2)  # E: \"2\" is a bare literal and cannot be used here, try Literal[2] instead? \\\n                                      # E: The default argument to TypeVarTuple must be an Unpacked tuple\nTs2 = TypeVarTuple(\"Ts2\", default=int)  # E: The default argument to TypeVarTuple must be an Unpacked tuple\nTs3 = TypeVarTuple(\"Ts3\", default=Tuple[int])  # E: The default argument to TypeVarTuple must be an Unpacked tuple\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultsInvalid2]\nfrom typing import TypeVar, List, Union\n\nT1 = TypeVar(\"T1\", bound=str, default=int)  # E: TypeVar default must be a subtype of the bound type\nT2 = TypeVar(\"T2\", bound=List[str], default=List[int])  # E: TypeVar default must be a subtype of the bound type\nT3 = TypeVar(\"T3\", int, str, default=bytes)  # E: TypeVar default must be one of the constraint types\nT4 = TypeVar(\"T4\", int, str, default=Union[int, str])  # E: TypeVar default must be one of the constraint types\nT5 = TypeVar(\"T5\", float, str, default=int)  # E: TypeVar default must be one of the constraint types\n\n[case testTypeVarDefaultsInvalid3]\nfrom typing import Dict, Generic, TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", default=T3)  # E: Name \"T3\" is used before definition\nT3 = TypeVar(\"T3\", default=str)\nT4 = TypeVar(\"T4\", default=T3)\n\nclass ClassError1(Generic[T3, T1]): ...  # E: \"T1\" cannot appear after \"T3\" in type parameter list because it has no default type\n\ndef func_error1(\n    a: ClassError1,\n    b: ClassError1[int],\n    c: ClassError1[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassError1[builtins.str, Any]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassError1[builtins.int, Any]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassError1[builtins.int, builtins.float]\"\n\n    k = ClassError1()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassError1[builtins.str, Any]\"\n    l = ClassError1[int]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassError1[builtins.int, Any]\"\n    m = ClassError1[int, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassError1[builtins.int, builtins.float]\"\n\nclass ClassError2(Generic[T4, T3]): ...  # E: Type parameter \"T4\" has a default type that refers to one or more type variables that are out of scope\n\ndef func_error2(\n    a: ClassError2,\n    b: ClassError2[int],\n    c: ClassError2[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassError2[Any, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassError2[builtins.int, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassError2[builtins.int, builtins.float]\"\n\n    k = ClassError2()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassError2[Any, builtins.str]\"\n    l = ClassError2[int]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassError2[builtins.int, builtins.str]\"\n    m = ClassError2[int, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassError2[builtins.int, builtins.float]\"\n\nTERR1 = Dict[T3, T1]  # E: \"T1\" cannot appear after \"T3\" in type parameter list because it has no default type\n\ndef func_error_alias1(\n    a: TERR1,\n    b: TERR1[int],\n    c: TERR1[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n    reveal_type(b)  # N: Revealed type is \"builtins.dict[builtins.int, Any]\"\n    reveal_type(c)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.float]\"\n\nTERR2 = Dict[T4, T3]  # TODO should be an error  \\\n                      # Type parameter \"T4\" has a default type that refers to one or more type variables that are out of scope\n\ndef func_error_alias2(\n    a: TERR2,\n    b: TERR2[int],\n    c: TERR2[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"builtins.dict[Any, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.float]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypeVarDefaultsFunctions]\nfrom typing import TypeVar, ParamSpec, List, Union, Callable, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT1 = TypeVar(\"T1\", default=str)\nT2 = TypeVar(\"T2\", bound=str, default=str)\nT3 = TypeVar(\"T3\", bytes, str, default=str)\nP1 = ParamSpec(\"P1\", default=[int, str])\nTs1 = TypeVarTuple(\"Ts1\", default=Unpack[Tuple[int, str]])\n\ndef callback1(x: str) -> None: ...\n\ndef func_a1(x: Union[int, T1]) -> T1: ...\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(x: Union[int, T1]) -> List[T1]: ...\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\ndef func_a3(x: Union[int, T2]) -> T2: ...\nreveal_type(func_a3(2))  # N: Revealed type is \"builtins.str\"\n\ndef func_a4(x: Union[int, T3]) -> T3: ...\nreveal_type(func_a4(2))  # N: Revealed type is \"builtins.str\"\n\ndef func_b1(x: Union[int, Callable[P1, None]]) -> Callable[P1, 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(x: Union[int, Callable[[Unpack[Ts1]], None]]) -> Tuple[Unpack[Ts1]]: ...\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 testTypeVarDefaultsClass1]\n# flags: --disallow-any-generics\nfrom typing import Generic, TypeVar, Union, overload\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", default=int)\nT3 = TypeVar(\"T3\", default=str)\nT4 = TypeVar(\"T4\", default=Union[int, None])\n\nclass ClassA1(Generic[T2, T3]): ...\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\n    k = ClassA1()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassA1[builtins.int, builtins.str]\"\n    l = ClassA1[float]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassA1[builtins.float, builtins.str]\"\n    m = ClassA1[float, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassA1[builtins.float, builtins.float]\"\n    n = ClassA1[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\nclass ClassA2(Generic[T1, T2, T3]): ...\n\ndef func_a2(\n    a: ClassA2,  # E: Missing type parameters for generic type \"ClassA2\"\n    b: ClassA2[float],\n    c: ClassA2[float, float],\n    d: ClassA2[float, float, float],\n    e: ClassA2[float, float, float, float],  # E: \"ClassA2\" expects between 1 and 3 type arguments, but 4 given\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassA2[Any, builtins.int, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassA2[builtins.float, builtins.int, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassA2[builtins.float, builtins.float, builtins.str]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassA2[builtins.float, builtins.float, builtins.float]\"\n    reveal_type(e)  # N: Revealed type is \"__main__.ClassA2[Any, builtins.int, builtins.str]\"\n\n    k = ClassA2()  # E: Need type annotation for \"k\"\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassA2[Any, builtins.int, builtins.str]\"\n    l = ClassA2[float]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassA2[builtins.float, builtins.int, builtins.str]\"\n    m = ClassA2[float, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassA2[builtins.float, builtins.float, builtins.str]\"\n    n = ClassA2[float, float, float]()\n    reveal_type(n)  # N: Revealed type is \"__main__.ClassA2[builtins.float, builtins.float, builtins.float]\"\n    o = ClassA2[float, float, float, float]()  # E: Type application has too many types (expected between 1 and 3)\n    reveal_type(o)  # N: Revealed type is \"Any\"\n\nclass ClassA3(Generic[T1, T2]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, var: int) -> None: ...\n    def __init__(self, var: Union[int, None] = None) -> None: ...\n\ndef func_a3(\n    a: ClassA3,  # E: Missing type parameters for generic type \"ClassA3\"\n    b: ClassA3[float],\n    c: ClassA3[float, float],\n    d: ClassA3[float, float, float],  # E: \"ClassA3\" expects between 1 and 2 type arguments, but 3 given\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassA3[Any, builtins.int]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassA3[builtins.float, builtins.int]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassA3[builtins.float, builtins.float]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassA3[Any, builtins.int]\"\n\n    k = ClassA3()  # E: Need type annotation for \"k\"\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassA3[Any, builtins.int]\"\n    l = ClassA3[float]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassA3[builtins.float, builtins.int]\"\n    m = ClassA3[float, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassA3[builtins.float, builtins.float]\"\n    n = ClassA3[float, float, float]()  # E: Type application has too many types (expected between 1 and 2)\n    reveal_type(n)  # N: Revealed type is \"Any\"\n\nclass ClassA4(Generic[T4]): ...\n\ndef func_a4(\n    a: ClassA4,\n    b: ClassA4[float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassA4[Union[builtins.int, None]]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassA4[builtins.float]\"\n\n    k = ClassA4()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassA4[Union[builtins.int, None]]\"\n    l = ClassA4[float]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassA4[builtins.float]\"\n\n[case testTypeVarDefaultsClass2]\n# flags: --disallow-any-generics\nfrom typing import Generic, ParamSpec\n\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\", default=[int, str])\nP3 = ParamSpec(\"P3\", default=...)\n\nclass ClassB1(Generic[P2, 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\nclass ClassB2(Generic[P1, P2]): ...\n\ndef func_b2(\n    a: ClassB2,  # E: Missing type parameters for generic type \"ClassB2\"\n    b: ClassB2[[float]],\n    c: ClassB2[[float], [float]],\n    d: ClassB2[[float], [float], [float]],  # E: \"ClassB2\" expects between 1 and 2 type arguments, but 3 given\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassB2[Any, [builtins.int, builtins.str]]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassB2[[builtins.float], [builtins.int, builtins.str]]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassB2[[builtins.float], [builtins.float]]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassB2[Any, [builtins.int, builtins.str]]\"\n\n    k = ClassB2()  # E: Need type annotation for \"k\"\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassB2[Any, [builtins.int, builtins.str]]\"\n    l = ClassB2[[float]]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassB2[[builtins.float], [builtins.int, builtins.str]]\"\n    m = ClassB2[[float], [float]]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassB2[[builtins.float], [builtins.float]]\"\n    n = ClassB2[[float], [float], [float]]()  # E: Type application has too many types (expected between 1 and 2)\n    reveal_type(n)  # N: Revealed type is \"Any\"\n\n[case testTypeVarDefaultsClass3]\n# flags: --disallow-any-generics\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT1 = TypeVar(\"T1\")\nT3 = TypeVar(\"T3\", default=str)\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\", default=Unpack[Tuple[int, str]])\nTs3 = TypeVarTuple(\"Ts3\", default=Unpack[Tuple[float, ...]])\nTs4 = TypeVarTuple(\"Ts4\", default=Unpack[Tuple[()]])\n\nclass ClassC1(Generic[Unpack[Ts2]]): ...\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\nclass ClassC2(Generic[T3, Unpack[Ts3]]): ...\n\ndef func_c2(\n    a: ClassC2,\n    b: ClassC2[int],\n    c: ClassC2[int, Unpack[Tuple[()]]],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassC2[builtins.str, Unpack[builtins.tuple[builtins.float, ...]]]\"\n    # reveal_type(b)  # Revealed type is \"__main__.ClassC2[builtins.int, Unpack[builtins.tuple[builtins.float, ...]]]\"  # TODO\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassC2[builtins.int]\"\n\n    k = ClassC2()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassC2[builtins.str, Unpack[builtins.tuple[builtins.float, ...]]]\"\n    l = ClassC2[int]()\n    # reveal_type(l)  # Revealed type is \"__main__.ClassC2[builtins.int, Unpack[builtins.tuple[builtins.float, ...]]]\"  # TODO\n    m = ClassC2[int, Unpack[Tuple[()]]]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassC2[builtins.int]\"\n\nclass ClassC3(Generic[T3, Unpack[Ts4]]): ...\n\ndef func_c3(\n    a: ClassC3,\n    b: ClassC3[int],\n    c: ClassC3[int, Unpack[Tuple[float]]]\n) -> None:\n    # reveal_type(a)  # Revealed type is \"__main__.ClassC3[builtins.str]\"  # TODO\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassC3[builtins.int]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassC3[builtins.int, builtins.float]\"\n\n    k = ClassC3()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassC3[builtins.str]\"\n    l = ClassC3[int]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassC3[builtins.int]\"\n    m = ClassC3[int, Unpack[Tuple[float]]]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassC3[builtins.int, builtins.float]\"\n\nclass ClassC4(Generic[T1, Unpack[Ts1], T3]): ...\n\ndef func_c4(\n    a: ClassC4,  # E: Missing type parameters for generic type \"ClassC4\"\n    b: ClassC4[int],\n    c: ClassC4[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassC4[Any, Unpack[builtins.tuple[Any, ...]], builtins.str]\"\n    # reveal_type(b)  # Revealed type is \"__main__.ClassC4[builtins.int, builtins.str]\"  # TODO\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassC4[builtins.int, builtins.float]\"\n\n    k = ClassC4()  # E: Need type annotation for \"k\"\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassC4[Any, Unpack[builtins.tuple[Any, ...]], builtins.str]\"\n    l = ClassC4[int]()\n    # reveal_type(l)  # Revealed type is \"__main__.ClassC4[builtins.int, builtins.str]\"  # TODO\n    m = ClassC4[int, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassC4[builtins.int, builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultsClassRecursive1]\n# flags: --disallow-any-generics\nfrom typing import Generic, TypeVar, List\n\nT1 = TypeVar(\"T1\", default=str)\nT2 = TypeVar(\"T2\", default=T1)\nT3 = TypeVar(\"T3\", default=T2)\nT4 = TypeVar(\"T4\", default=List[T1])\n\nclass ClassD1(Generic[T1, T2]): ...\n\ndef func_d1(\n    a: ClassD1,\n    b: ClassD1[int],\n    c: ClassD1[int, float]\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassD1[builtins.str, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassD1[builtins.int, builtins.int]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassD1[builtins.int, builtins.float]\"\n\n    k = ClassD1()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassD1[builtins.str, builtins.str]\"\n    l = ClassD1[int]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassD1[builtins.int, builtins.int]\"\n    m = ClassD1[int, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassD1[builtins.int, builtins.float]\"\n\nclass ClassD2(Generic[T1, T2, T3]): ...\n\ndef func_d2(\n    a: ClassD2,\n    b: ClassD2[int],\n    c: ClassD2[int, float],\n    d: ClassD2[int, float, str],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassD2[builtins.str, builtins.str, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassD2[builtins.int, builtins.int, builtins.int]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassD2[builtins.int, builtins.float, builtins.float]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassD2[builtins.int, builtins.float, builtins.str]\"\n\n    k = ClassD2()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassD2[builtins.str, builtins.str, builtins.str]\"\n    l = ClassD2[int]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassD2[builtins.int, builtins.int, builtins.int]\"\n    m = ClassD2[int, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassD2[builtins.int, builtins.float, builtins.float]\"\n    n = ClassD2[int, float, str]()\n    reveal_type(n)  # N: Revealed type is \"__main__.ClassD2[builtins.int, builtins.float, builtins.str]\"\n\nclass ClassD3(Generic[T1, T4]): ...\n\ndef func_d3(\n    a: ClassD3,\n    b: ClassD3[int],\n    c: ClassD3[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassD3[builtins.str, builtins.list[builtins.str]]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassD3[builtins.int, builtins.list[builtins.int]]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassD3[builtins.int, builtins.float]\"\n\n    # k = ClassD3()\n    # reveal_type(k)  # Revealed type is \"__main__.ClassD3[builtins.str, builtins.list[builtins.str]]\"  # TODO\n    l = ClassD3[int]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassD3[builtins.int, builtins.list[builtins.int]]\"\n    m = ClassD3[int, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassD3[builtins.int, builtins.float]\"\n\n[case testTypeVarDefaultsClassRecursiveMultipleFiles]\n# flags: --disallow-any-generics\nfrom typing import Generic, TypeVar\nfrom file2 import T as T2\n\nT = TypeVar(\"T\", default=T2)\n\nclass ClassG1(Generic[T2, T]):\n    pass\n\ndef func(\n    a: ClassG1,\n    b: ClassG1[str],\n    c: ClassG1[str, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassG1[builtins.int, builtins.int]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassG1[builtins.str, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassG1[builtins.str, builtins.float]\"\n\n    k = ClassG1()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassG1[builtins.int, builtins.int]\"\n    l = ClassG1[str]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassG1[builtins.str, builtins.str]\"\n    m = ClassG1[str, float]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassG1[builtins.str, builtins.float]\"\n\n[file file2.py]\nfrom typing import TypeVar\nT = TypeVar('T', default=int)\n\n[case testTypeVarDefaultsTypeAlias1]\n# flags: --disallow-any-generics\nfrom typing import Any, Dict, List, Tuple, TypeVar, Union\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", default=int)\nT3 = TypeVar(\"T3\", default=str)\nT4 = TypeVar(\"T4\")\n\nTA1 = 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\nTA2 = Tuple[T1, T2, T3]\n\ndef func_a2(\n    a: TA2,  # E: Missing type parameters for generic type \"TA2\"\n    b: TA2[float],\n    c: TA2[float, float],\n    d: TA2[float, float, float],\n    e: TA2[float, float, float, float],  # E: Bad number of arguments for type alias, expected between 1 and 3, given 4\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"Tuple[Any, builtins.int, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"Tuple[builtins.float, builtins.int, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"Tuple[builtins.float, builtins.float, builtins.str]\"\n    reveal_type(d)  # N: Revealed type is \"Tuple[builtins.float, builtins.float, builtins.float]\"\n    reveal_type(e)  # N: Revealed type is \"Tuple[Any, builtins.int, builtins.str]\"\n\nTA3 = Union[Dict[T1, T2], List[T3]]\n\ndef func_a3(\n    a: TA3,  # E: Missing type parameters for generic type \"TA3\"\n    b: TA3[float],\n    c: TA3[float, float],\n    d: TA3[float, float, float],\n    e: TA3[float, float, float, float],  # E: Bad number of arguments for type alias, expected between 1 and 3, given 4\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"Union[builtins.dict[Any, builtins.int], builtins.list[builtins.str]]\"\n    reveal_type(b)  # N: Revealed type is \"Union[builtins.dict[builtins.float, builtins.int], builtins.list[builtins.str]]\"\n    reveal_type(c)  # N: Revealed type is \"Union[builtins.dict[builtins.float, builtins.float], builtins.list[builtins.str]]\"\n    reveal_type(d)  # N: Revealed type is \"Union[builtins.dict[builtins.float, builtins.float], builtins.list[builtins.float]]\"\n    reveal_type(e)  # N: Revealed type is \"Union[builtins.dict[Any, builtins.int], builtins.list[builtins.str]]\"\n\nTA4 = Tuple[T1, T4, T2]\n\ndef func_a4(\n    a: TA4,  # E: Missing type parameters for generic type \"TA4\"\n    b: TA4[float],  # E: Bad number of arguments for type alias, expected between 2 and 3, given 1\n    c: TA4[float, float],\n    d: TA4[float, float, float],\n    e: TA4[float, float, float, float],  # E: Bad number of arguments for type alias, expected between 2 and 3, given 4\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"Tuple[Any, Any, builtins.int]\"\n    reveal_type(b)  # N: Revealed type is \"Tuple[Any, Any, builtins.int]\"\n    reveal_type(c)  # N: Revealed type is \"Tuple[builtins.float, builtins.float, builtins.int]\"\n    reveal_type(d)  # N: Revealed type is \"Tuple[builtins.float, builtins.float, builtins.float]\"\n    reveal_type(e)  # N: Revealed type is \"Tuple[Any, Any, builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypeVarDefaultsTypeAlias2]\n# flags: --disallow-any-generics\nfrom typing import Any, Generic, ParamSpec\n\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\", default=[int, str])\nP3 = ParamSpec(\"P3\", default=...)\n\nclass ClassB1(Generic[P2, P3]): ...\nTB1 = 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\nclass ClassB2(Generic[P1, P2]): ...\nTB2 = ClassB2[P1, P2]\n\ndef func_b2(\n    a: TB2,  # E: Missing type parameters for generic type \"TB2\"\n    b: TB2[[float]],\n    c: TB2[[float], [float]],\n    d: TB2[[float], [float], [float]],  # E: Bad number of arguments for type alias, expected between 1 and 2, given 3\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassB2[Any, [builtins.int, builtins.str]]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassB2[[builtins.float], [builtins.int, builtins.str]]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassB2[[builtins.float], [builtins.float]]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassB2[Any, [builtins.int, builtins.str]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultsTypeAlias3]\n# flags: --disallow-any-generics\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT1 = TypeVar(\"T1\")\nT3 = TypeVar(\"T3\", default=str)\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\", default=Unpack[Tuple[int, str]])\nTs3 = TypeVarTuple(\"Ts3\", default=Unpack[Tuple[float, ...]])\nTs4 = TypeVarTuple(\"Ts4\", default=Unpack[Tuple[()]])\n\nTC1 = Tuple[Unpack[Ts2]]\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\nTC2 = Tuple[T3, Unpack[Ts3]]\n\ndef func_c2(\n    a: TC2,\n    b: TC2[int],\n    c: TC2[int, Unpack[Tuple[()]]],\n) -> None:\n    # reveal_type(a)  # Revealed type is \"Tuple[builtins.str, Unpack[builtins.tuple[builtins.float, ...]]]\"  # TODO\n    # reveal_type(b)  # Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]]]\"  # TODO\n    reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int]\"\n\nTC3 = Tuple[T3, Unpack[Ts4]]\n\ndef func_c3(\n    a: TC3,\n    b: TC3[int],\n    c: TC3[int, Unpack[Tuple[float]]],\n) -> None:\n    # reveal_type(a)  # Revealed type is \"Tuple[builtins.str]\"  # TODO\n    reveal_type(b)  # N: Revealed type is \"Tuple[builtins.int]\"\n    reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, builtins.float]\"\n\nTC4 = Tuple[T1, Unpack[Ts1], T3]\n\ndef func_c4(\n    a: TC4,  # E: Missing type parameters for generic type \"TC4\"\n    b: TC4[int],\n    c: TC4[int, float],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"Tuple[Any, Unpack[builtins.tuple[Any, ...]], builtins.str]\"\n    # reveal_type(b)  # Revealed type is \"Tuple[builtins.int, builtins.str]\"  # TODO\n    reveal_type(c)  # N: Revealed type is \"Tuple[builtins.int, builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultsTypeAliasRecursive1]\n# flags: --disallow-any-generics\nfrom typing import Dict, List, TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", default=T1)\n\nTD1 = Dict[T1, T2]\n\ndef func_d1(\n    a: TD1,  # E: Missing type parameters for generic type \"TD1\"\n    b: TD1[int],\n    c: TD1[int, float],\n) -> None:\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.int]\"\n    reveal_type(c)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.float]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypeVarDefaultsTypeAliasRecursive2]\nfrom typing import Any, Dict, Generic, TypeVar\n\nT1 = TypeVar(\"T1\", default=str)\nT2 = TypeVar(\"T2\", default=T1)\nAlias1 = Dict[T1, T2]\nT3 = TypeVar(\"T3\")\nclass A(Generic[T3]): ...\n\nT4 = TypeVar(\"T4\", default=A[Alias1])\nclass B(Generic[T4]): ...\n\ndef func_d3(\n    a: B,\n    b: B[A[Alias1[int]]],\n    c: B[A[Alias1[int, float]]],\n    d: B[int],\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.B[__main__.A[builtins.dict[builtins.str, builtins.str]]]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.B[__main__.A[builtins.dict[builtins.int, builtins.int]]]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.B[__main__.A[builtins.dict[builtins.int, builtins.float]]]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.B[builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypeVarDefaultsAndTypeObjectTypeInUnion]\nfrom __future__ import annotations\nfrom typing import Generic\nfrom typing_extensions import TypeVar\n\n_I = TypeVar(\"_I\", default=int)\n\nclass C(Generic[_I]): pass\n\nt: type[C] | int = C\n[builtins fixtures/tuple.pyi]\n\n\n\n[case testGenericTypeAliasWithDefaultTypeVarPreservesNoneInDefault]\nfrom typing_extensions import TypeVar\nfrom typing import Generic, Union\n\nT1 = TypeVar(\"T1\", default=Union[int, None])\nT2 = TypeVar(\"T2\", default=Union[int, None])\n\n\nclass A(Generic[T1, T2]):\n    def __init__(self, a: T1, b: T2) -> None:\n        self.a = a\n        self.b = b\n\n\nMyA = A[T1, int]\na: MyA = A(None, 10)\nreveal_type(a.a)  # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typevar-tuple.test",
    "content": "[case testTypeVarTupleBasic]\nfrom typing import Any, Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef f(a: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]:\n    return a\n\nany: Any\nargs: Tuple[int, str] = (1, 'x')\nargs2: Tuple[bool, str] = (False, 'y')\nargs3: Tuple[int, str, bool] = (2, 'z', True)\nvarargs: Tuple[int, ...]\n\nreveal_type(f(args))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\nreveal_type(f(varargs))  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nf(0)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"Tuple[Never, ...]\"\n\ndef g(a: Tuple[Unpack[Ts]], b: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]:\n    return a\n\nreveal_type(g(args, args))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\nreveal_type(g(args, args2))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\nreveal_type(g(args, args3))  # N: Revealed type is \"builtins.tuple[Union[builtins.int, builtins.str], ...]\"\nreveal_type(g(any, any))  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleMixed]\nfrom typing import Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef to_str(i: int) -> str:\n    ...\n\ndef f(a: Tuple[int, Unpack[Ts]]) -> Tuple[str, Unpack[Ts]]:\n    return (to_str(a[0]),) + a[1:]\n\ndef g(a: Tuple[Unpack[Ts], int]) -> Tuple[Unpack[Ts], str]:\n    return a[:-1] + (to_str(a[-1]),)\n\ndef h(a: Tuple[bool, int, Unpack[Ts], str, object]) -> Tuple[Unpack[Ts]]:\n    return a[2:-2]\n\nempty = ()\nbad_args: Tuple[str, str]\nvar_len_tuple: Tuple[int, ...]\n\nf_args: Tuple[int, str]\nf_args2: Tuple[int]\nf_args3: Tuple[int, str, bool]\n\nreveal_type(f(f_args))  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\nreveal_type(f(f_args2))  # N: Revealed type is \"Tuple[builtins.str]\"\nreveal_type(f(f_args3))  # N: Revealed type is \"Tuple[builtins.str, builtins.str, builtins.bool]\"\nf(empty)  # E: Argument 1 to \"f\" has incompatible type \"Tuple[()]\"; expected \"Tuple[int]\"\nf(bad_args)  # E: Argument 1 to \"f\" has incompatible type \"Tuple[str, str]\"; expected \"Tuple[int, str]\"\n\n# The reason for error in subtle: actual can be empty, formal cannot.\nreveal_type(f(var_len_tuple))  # N: Revealed type is \"Tuple[builtins.str, Unpack[builtins.tuple[builtins.int, ...]]]\" \\\n                               # E: Argument 1 to \"f\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[int, Unpack[Tuple[int, ...]]]\"\n\ng_args: Tuple[str, int]\nreveal_type(g(g_args))  # N: Revealed type is \"Tuple[builtins.str, builtins.str]\"\n\nh_args: Tuple[bool, int, str, int, str, object]\nreveal_type(h(h_args))  # N: Revealed type is \"Tuple[builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleChaining]\nfrom typing import Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef to_str(i: int) -> str:\n    ...\n\ndef f(a: Tuple[int, Unpack[Ts]]) -> Tuple[str, Unpack[Ts]]:\n    return (to_str(a[0]),) + a[1:]\n\ndef g(a: Tuple[bool, int, Unpack[Ts], str, object]) -> Tuple[str, Unpack[Ts]]:\n    return f(a[1:-2])\n\ndef h(a: Tuple[bool, int, Unpack[Ts], str, object]) -> Tuple[str, Unpack[Ts]]:\n    x = f(a[1:-2])\n    return x\n\nargs: Tuple[bool, int, str, int, str, object]\nreveal_type(g(args))  # N: Revealed type is \"Tuple[builtins.str, builtins.str, builtins.int]\"\nreveal_type(h(args))  # N: Revealed type is \"Tuple[builtins.str, builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleGenericClassDefn]\nfrom typing import Generic, TypeVar, Tuple, Union\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\nclass Variadic(Generic[Unpack[Ts]]):\n    pass\n\nclass Mixed1(Generic[T, Unpack[Ts]]):\n    pass\n\nclass Mixed2(Generic[Unpack[Ts], T]):\n    pass\n\nvariadic: Variadic[int, str]\nreveal_type(variadic)  # N: Revealed type is \"__main__.Variadic[builtins.int, builtins.str]\"\n\nvariadic_single: Variadic[int]\nreveal_type(variadic_single)  # N: Revealed type is \"__main__.Variadic[builtins.int]\"\n\nempty: Variadic[()]\nreveal_type(empty)  # N: Revealed type is \"__main__.Variadic[()]\"\n\nomitted: Variadic\nreveal_type(omitted)  # N: Revealed type is \"__main__.Variadic[Unpack[builtins.tuple[Any, ...]]]\"\n\nbad: Variadic[Unpack[Tuple[int, ...]], str, Unpack[Tuple[bool, ...]]]  # E: More than one Unpack in a type is not allowed\nreveal_type(bad)  # N: Revealed type is \"__main__.Variadic[Unpack[builtins.tuple[builtins.int, ...]], builtins.str]\"\n\nbad2: Unpack[Tuple[int, ...]]  # E: Unpack is only valid in a variadic position\n\nm1: Mixed1[int, str, bool]\nreveal_type(m1)  # N: Revealed type is \"__main__.Mixed1[builtins.int, builtins.str, builtins.bool]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleGenericClassWithFunctions]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass Variadic(Generic[T, Unpack[Ts], S]):\n    pass\n\ndef foo(t: Variadic[int, Unpack[Ts], object]) -> Tuple[int, Unpack[Ts]]:\n    ...\n\nv: Variadic[int, str, bool, object]\nreveal_type(foo(v))  # N: Revealed type is \"Tuple[builtins.int, builtins.str, builtins.bool]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleGenericClassWithMethods]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass Variadic(Generic[T, Unpack[Ts], S]):\n    def __init__(self, t: Tuple[Unpack[Ts]]) -> None:\n        ...\n\n    def foo(self, t: int) -> Tuple[int, Unpack[Ts]]:\n        ...\n\nv: Variadic[float, str, bool, object]\nreveal_type(v.foo(0))  # N: Revealed type is \"Tuple[builtins.int, builtins.str, builtins.bool]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleIsNotValidAliasTarget]\nfrom typing_extensions import TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\nB = Ts  # E: Type variable \"__main__.Ts\" is invalid as target for type alias\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646ArrayExample]\nfrom typing import Generic, Tuple, TypeVar, Protocol, NewType\nfrom typing_extensions import TypeVarTuple, Unpack\n\nShape = TypeVarTuple('Shape')\n\nHeight = NewType('Height', int)\nWidth = NewType('Width', int)\n\nT_co = TypeVar(\"T_co\", covariant=True)\nT = TypeVar(\"T\")\n\nclass SupportsAbs(Protocol[T_co]):\n    def __abs__(self) -> T_co: pass\n\ndef abs(a: SupportsAbs[T]) -> T:\n    ...\n\nclass Array(Generic[Unpack[Shape]]):\n    def __init__(self, shape: Tuple[Unpack[Shape]]):\n        self._shape: Tuple[Unpack[Shape]] = shape\n\n    def get_shape(self) -> Tuple[Unpack[Shape]]:\n        return self._shape\n\n    def __abs__(self) -> Array[Unpack[Shape]]: ...\n\n    def __add__(self, other: Array[Unpack[Shape]]) -> Array[Unpack[Shape]]: ...\n\nshape = (Height(480), Width(640))\nx: Array[Height, Width] = Array(shape)\nreveal_type(abs(x))  # N: Revealed type is \"__main__.Array[__main__.Height, __main__.Width]\"\nreveal_type(x + x)  # N: Revealed type is \"__main__.Array[__main__.Height, __main__.Width]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646ArrayExampleWithDType]\nfrom typing import Generic, Tuple, TypeVar, Protocol, NewType\nfrom typing_extensions import TypeVarTuple, Unpack\n\nDType = TypeVar(\"DType\")\nShape = TypeVarTuple('Shape')\n\nHeight = NewType('Height', int)\nWidth = NewType('Width', int)\n\nT_co = TypeVar(\"T_co\", covariant=True)\nT = TypeVar(\"T\")\n\nclass SupportsAbs(Protocol[T_co]):\n    def __abs__(self) -> T_co: pass\n\ndef abs(a: SupportsAbs[T]) -> T:\n    ...\n\nclass Array(Generic[DType, Unpack[Shape]]):\n    def __init__(self, shape: Tuple[Unpack[Shape]]):\n        self._shape: Tuple[Unpack[Shape]] = shape\n\n    def get_shape(self) -> Tuple[Unpack[Shape]]:\n        return self._shape\n\n    def __abs__(self) -> Array[DType, Unpack[Shape]]: ...\n\n    def __add__(self, other: Array[DType, Unpack[Shape]]) -> Array[DType, Unpack[Shape]]: ...\n\nshape = (Height(480), Width(640))\nx: Array[float, Height, Width] = Array(shape)\nreveal_type(abs(x))  # N: Revealed type is \"__main__.Array[builtins.float, __main__.Height, __main__.Width]\"\nreveal_type(x + x)  # N: Revealed type is \"__main__.Array[builtins.float, __main__.Height, __main__.Width]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646ArrayExampleInfer]\nfrom typing import Generic, Tuple, TypeVar, NewType\nfrom typing_extensions import TypeVarTuple, Unpack\n\nShape = TypeVarTuple('Shape')\n\nHeight = NewType('Height', int)\nWidth = NewType('Width', int)\n\nclass Array(Generic[Unpack[Shape]]):\n    pass\n\nx: Array[float, Height, Width] = Array()\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeConcatenation]\nfrom typing import Generic, TypeVar, NewType\nfrom typing_extensions import TypeVarTuple, Unpack\n\nShape = TypeVarTuple('Shape')\n\nChannels = NewType(\"Channels\", int)\nBatch = NewType(\"Batch\", int)\nHeight = NewType('Height', int)\nWidth = NewType('Width', int)\n\nclass Array(Generic[Unpack[Shape]]):\n    pass\n\n\ndef add_batch_axis(x: Array[Unpack[Shape]]) -> Array[Batch, Unpack[Shape]]: ...\ndef del_batch_axis(x: Array[Batch, Unpack[Shape]]) -> Array[Unpack[Shape]]: ...\ndef add_batch_channels(\n  x: Array[Unpack[Shape]]\n) -> Array[Batch, Unpack[Shape], Channels]: ...\n\na: Array[Height, Width]\nb = add_batch_axis(a)\nreveal_type(b)  # N: Revealed type is \"__main__.Array[__main__.Batch, __main__.Height, __main__.Width]\"\nc = del_batch_axis(b)\nreveal_type(c)  # N: Revealed type is \"__main__.Array[__main__.Height, __main__.Width]\"\nd = add_batch_channels(a)\nreveal_type(d)  # N: Revealed type is \"__main__.Array[__main__.Batch, __main__.Height, __main__.Width, __main__.Channels]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeVarConcatenation]\nfrom typing import Generic, TypeVar, NewType, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar('T')\nTs = TypeVarTuple('Ts')\n\ndef prefix_tuple(\n    x: T,\n    y: Tuple[Unpack[Ts]],\n) -> Tuple[T, Unpack[Ts]]:\n    ...\n\nz = prefix_tuple(x=0, y=(True, 'a'))\nreveal_type(z)  # N: Revealed type is \"Tuple[builtins.int, builtins.bool, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeVarTupleUnpacking]\nfrom typing import Generic, TypeVar, NewType, Any, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nShape = TypeVarTuple('Shape')\n\nChannels = NewType(\"Channels\", int)\nBatch = NewType(\"Batch\", int)\nHeight = NewType('Height', int)\nWidth = NewType('Width', int)\n\nclass Array(Generic[Unpack[Shape]]):\n    pass\n\ndef process_batch_channels(\n    x: Array[Batch, Unpack[Tuple[Any, ...]], Channels]\n) -> None:\n    ...\n\nx: Array[Batch, Height, Width, Channels]\nprocess_batch_channels(x)\ny: Array[Batch, Channels]\nprocess_batch_channels(y)\nz: Array[Batch]\nprocess_batch_channels(z)  # E: Argument 1 to \"process_batch_channels\" has incompatible type \"Array[Batch]\"; expected \"Array[Batch, Unpack[Tuple[Any, ...]], Channels]\"\n\nu: Array[Unpack[Tuple[Any, ...]]]\n\ndef expect_variadic_array(\n    x: Array[Batch, Unpack[Shape]]\n) -> None:\n    ...\n\ndef expect_variadic_array_2(\n    x: Array[Batch, Height, Width, Channels]\n) -> None:\n    ...\n\nexpect_variadic_array(u)\nexpect_variadic_array_2(u)\n\nTs = TypeVarTuple(\"Ts\")\nTs2 = TypeVarTuple(\"Ts2\")\n\ndef bad(x: Tuple[int, Unpack[Ts], str, Unpack[Ts2]]) -> None: # E: More than one Unpack in a type is not allowed\n\n    ...\nreveal_type(bad)  # N: Revealed type is \"def [Ts, Ts2] (x: Tuple[builtins.int, Unpack[Ts`-1], builtins.str])\"\n\ndef bad2(x: Tuple[int, Unpack[Tuple[int, ...]], str, Unpack[Tuple[str, ...]]]) -> None:  # E: More than one Unpack in a type is not allowed\n    ...\nreveal_type(bad2)  # N: Revealed type is \"def (x: Tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]], builtins.str])\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeVarStarArgsBasic]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\n\ndef args_to_tuple(*args: Unpack[Ts]) -> Tuple[Unpack[Ts]]:\n    reveal_type(args)  # N: Revealed type is \"Tuple[Unpack[Ts`-1]]\"\n    reveal_type(args_to_tuple(1, *args))  # N: Revealed type is \"Tuple[Literal[1]?, Unpack[Ts`-1]]\"\n    reveal_type(args_to_tuple(*args, 'a'))  # N: Revealed type is \"Tuple[Unpack[Ts`-1], Literal['a']?]\"\n    reveal_type(args_to_tuple(1, *args, 'a'))  # N: Revealed type is \"Tuple[Literal[1]?, Unpack[Ts`-1], Literal['a']?]\"\n    args_to_tuple(*args, *args)  # E: Passing multiple variadic unpacks in a call is not supported\n    ok = (1, 'a')\n    reveal_type(args_to_tuple(*ok, *ok))  # N: Revealed type is \"Tuple[builtins.int, builtins.str, builtins.int, builtins.str]\"\n    if int():\n        return args\n    else:\n        return args_to_tuple(*args)\n\nreveal_type(args_to_tuple(1, 'a'))  # N: Revealed type is \"Tuple[Literal[1]?, Literal['a']?]\"\nvt: Tuple[int, ...]\nreveal_type(args_to_tuple(1, *vt))  # N: Revealed type is \"Tuple[Literal[1]?, Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(args_to_tuple(*vt, 'a'))  # N: Revealed type is \"Tuple[Unpack[builtins.tuple[builtins.int, ...]], Literal['a']?]\"\nreveal_type(args_to_tuple(1, *vt, 'a'))  # N: Revealed type is \"Tuple[Literal[1]?, Unpack[builtins.tuple[builtins.int, ...]], Literal['a']?]\"\nargs_to_tuple(*vt, *vt)  # E: Passing multiple variadic unpacks in a call is not supported\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeVarStarArgs]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\n\ndef args_to_tuple(*args: Unpack[Ts]) -> Tuple[Unpack[Ts]]:\n    with_prefix_suffix(*args)  # E: Too few arguments for \"with_prefix_suffix\" \\\n                               # E: Argument 1 to \"with_prefix_suffix\" has incompatible type \"*Tuple[Unpack[Ts]]\"; expected \"bool\"\n    new_args = (True, \"foo\", *args, 5)\n    with_prefix_suffix(*new_args)\n    return args\n\ndef with_prefix_suffix(*args: Unpack[Tuple[bool, str, Unpack[Ts], int]]) -> Tuple[bool, str, Unpack[Ts], int]:\n    reveal_type(args)  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, Unpack[Ts`-1], builtins.int]\"\n    reveal_type(args_to_tuple(*args))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, Unpack[Ts`-1], builtins.int]\"\n    reveal_type(args_to_tuple(1, *args, 'a'))  # N: Revealed type is \"Tuple[Literal[1]?, builtins.bool, builtins.str, Unpack[Ts`-1], builtins.int, Literal['a']?]\"\n    return args\n\nreveal_type(with_prefix_suffix(True, \"bar\", \"foo\", 5))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, Literal['foo']?, builtins.int]\"\nreveal_type(with_prefix_suffix(True, \"bar\", 5))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, builtins.int]\"\n\nwith_prefix_suffix(True, \"bar\", \"foo\", 1.0)  # E: Argument 4 to \"with_prefix_suffix\" has incompatible type \"float\"; expected \"int\"\nwith_prefix_suffix(True, \"bar\")  # E: Too few arguments for \"with_prefix_suffix\"\n\nt = (True, \"bar\", \"foo\", 5)\nreveal_type(with_prefix_suffix(*t))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, builtins.str, builtins.int]\"\nreveal_type(with_prefix_suffix(True, *(\"bar\", \"foo\"), 5))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, Literal['foo']?, builtins.int]\"\n\nreveal_type(with_prefix_suffix(True, \"bar\", *[\"foo1\", \"foo2\"], 5))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, Unpack[builtins.tuple[builtins.str, ...]], builtins.int]\"\n\nbad_t = (True, \"bar\")\nwith_prefix_suffix(*bad_t)  # E: Too few arguments for \"with_prefix_suffix\"\n\ndef foo(*args: Unpack[Ts]) -> None:\n    reveal_type(with_prefix_suffix(True, \"bar\", *args, 5))  # N: Revealed type is \"Tuple[builtins.bool, builtins.str, Unpack[Ts`-1], builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeVarStarArgsFixedLengthTuple]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef foo(*args: Unpack[Tuple[int, str]]) -> None:\n    reveal_type(args)  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\nfoo(0, \"foo\")\nfoo(0, 1)  # E: Argument 2 to \"foo\" has incompatible type \"int\"; expected \"str\"\nfoo(\"foo\", \"bar\")  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\nfoo(0, \"foo\", 1)  # E: Too many arguments for \"foo\"\nfoo(0)  # E: Too few arguments for \"foo\"\nfoo()  # E: Too few arguments for \"foo\"\nfoo(*(0, \"foo\"))\n\ndef foo2(*args: Unpack[Tuple[bool, Unpack[Tuple[int, str]], bool]]) -> None:\n    reveal_type(args)  # N: Revealed type is \"Tuple[builtins.bool, builtins.int, builtins.str, builtins.bool]\"\n\n# It is hard to normalize callable types in definition, because there is deep relation between `FuncDef.type`\n# and `FuncDef.arguments`, therefore various typeops need to be sure to normalize Callable types before using them.\nreveal_type(foo2)  # N: Revealed type is \"def (*args: Unpack[Tuple[builtins.bool, builtins.int, builtins.str, builtins.bool]])\"\n\nclass C:\n    def foo2(self, *args: Unpack[Tuple[bool, Unpack[Tuple[int, str]], bool]]) -> None: ...\nreveal_type(C().foo2)  # N: Revealed type is \"def (*args: Unpack[Tuple[builtins.bool, builtins.int, builtins.str, builtins.bool]])\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646TypeVarStarArgsVariableLengthTuple]\nfrom typing import Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\ndef foo(*args: Unpack[Tuple[int, ...]]) -> None:\n    reveal_type(args)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nfoo(0, 1, 2)\nfoo(0, 1, \"bar\")  # E: Argument 3 to \"foo\" has incompatible type \"str\"; expected \"int\"\n\ndef foo2(*args: Unpack[Tuple[str, Unpack[Tuple[int, ...]], bool, bool]]) -> None:\n    reveal_type(args)  # N: Revealed type is \"Tuple[builtins.str, Unpack[builtins.tuple[builtins.int, ...]], builtins.bool, builtins.bool]\"\n    reveal_type(args[1])  # N: Revealed type is \"builtins.int\"\n\ndef foo3(*args: Unpack[Tuple[str, Unpack[Tuple[int, ...]], str, float]]) -> None:\n    reveal_type(args[0])  # N: Revealed type is \"builtins.str\"\n    reveal_type(args[1])  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    reveal_type(args[2])  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.float]\"\n    args[3]  # E: Tuple index out of range \\\n             # N: Variadic tuple can have length 3\n    reveal_type(args[-1])  # N: Revealed type is \"builtins.float\"\n    reveal_type(args[-2])  # N: Revealed type is \"builtins.str\"\n    reveal_type(args[-3])  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\n    args[-4]  # E: Tuple index out of range \\\n              # N: Variadic tuple can have length 3\n    reveal_type(args[::-1])  # N: Revealed type is \"Tuple[builtins.float, builtins.str, Unpack[builtins.tuple[builtins.int, ...]], builtins.str]\"\n    args[::2]  # E: Ambiguous slice of a variadic tuple\n    args[:2]  # E: Ambiguous slice of a variadic tuple\n\nTs = TypeVarTuple(\"Ts\")\ndef foo4(*args: Unpack[Tuple[str, Unpack[Ts], bool, bool]]) -> None:\n    reveal_type(args[1])  # N: Revealed type is \"builtins.object\"\n\nfoo2(\"bar\", 1, 2, 3, False, True)\nfoo2(0, 1, 2, 3, False, True)  # E: Argument 1 to \"foo2\" has incompatible type \"int\"; expected \"str\"\nfoo2(\"bar\", \"bar\", 2, 3, False, True)  # E: Argument 2 to \"foo2\" has incompatible type \"str\"; expected \"Unpack[Tuple[Unpack[Tuple[int, ...]], bool, bool]]\"\nfoo2(\"bar\", 1, 2, 3, 4, True)  # E: Argument 5 to \"foo2\" has incompatible type \"int\"; expected \"Unpack[Tuple[Unpack[Tuple[int, ...]], bool, bool]]\"\nfoo2(*(\"bar\", 1, 2, 3, False, True))\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646Callable]\nfrom typing import Tuple, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef call(\n    target: Callable[[Unpack[Ts]], None],\n    args: Tuple[Unpack[Ts]],\n) -> None:\n    pass\n\ndef func(arg1: int, arg2: str) -> None: ...\ndef func2(arg1: int, arg2: int) -> None: ...\ndef func3(*args: int) -> None: ...\n\nvargs: Tuple[int, ...]\nvargs_str: Tuple[str, ...]\n\ncall(target=func, args=(0, 'foo'))\ncall(target=func, args=('bar', 'foo'))  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[str, str], None]\"\ncall(target=func, args=(True, 'foo', 0))  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[bool, str, int], None]\"\ncall(target=func, args=(0, 0, 'foo'))  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[int, int, str], None]\"\ncall(target=func, args=vargs)  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[VarArg(int)], None]\"\n\n# NOTE: This behavior may be a bit contentious, it is maybe inconsistent with our handling of\n# PEP646 but consistent with our handling of callable constraints.\ncall(target=func2, args=vargs)  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[int, int], None]\"; expected \"Callable[[VarArg(int)], None]\"\ncall(target=func3, args=vargs)\ncall(target=func3, args=(0,1))\ncall(target=func3, args=(0,'foo'))  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[VarArg(int)], None]\"; expected \"Callable[[int, str], None]\"\ncall(target=func3, args=vargs_str)  # E: Argument \"target\" to \"call\" has incompatible type \"Callable[[VarArg(int)], None]\"; expected \"Callable[[VarArg(str)], None]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646CallableWithPrefixSuffix]\nfrom typing import Tuple, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef call_prefix(\n    target: Callable[[bytes, Unpack[Ts]], None],\n    args: Tuple[Unpack[Ts]],\n) -> None:\n    pass\n\ndef func_prefix(arg0: bytes, arg1: int, arg2: str) -> None: ...\ndef func2_prefix(arg0: str, arg1: int, arg2: str) -> None: ...\n\ncall_prefix(target=func_prefix, args=(0, 'foo'))\ncall_prefix(target=func2_prefix, args=(0, 'foo'))  # E: Argument \"target\" to \"call_prefix\" has incompatible type \"Callable[[str, int, str], None]\"; expected \"Callable[[bytes, int, str], None]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646CallableSuffixSyntax]\nfrom typing import Callable, Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nx: Callable[[str, Unpack[Tuple[int, ...]], bool], None]\nreveal_type(x)  # N: Revealed type is \"def (builtins.str, *Unpack[Tuple[Unpack[builtins.tuple[builtins.int, ...]], builtins.bool]])\"\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nA = Callable[[T, Unpack[Ts], S], int]\ny: A[int, str, bool]\nreveal_type(y)  # N: Revealed type is \"def (builtins.int, builtins.str, builtins.bool) -> builtins.int\"\nz: A[Unpack[Tuple[int, ...]]]\nreveal_type(z)  # N: Revealed type is \"def (builtins.int, *Unpack[Tuple[Unpack[builtins.tuple[builtins.int, ...]], builtins.int]]) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646CallableInvalidSyntax]\nfrom typing import Callable, Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\nUs = TypeVarTuple(\"Us\")\na: Callable[[Unpack[Ts], Unpack[Us]], int]  # E: More than one Unpack in a type is not allowed\nreveal_type(a)  # N: Revealed type is \"def [Ts, Us] (*Unpack[Ts`-1]) -> builtins.int\"\nb: Callable[[Unpack], int]  # E: Unpack[...] requires exactly one type argument\nreveal_type(b)  # N: Revealed type is \"def (*Any) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646CallableNewSyntax]\nfrom typing import Callable, Generic, Tuple\nfrom typing_extensions import ParamSpec\n\nx: Callable[[str, *Tuple[int, ...]], None]\nreveal_type(x)  # N: Revealed type is \"def (builtins.str, *builtins.int)\"\ny: Callable[[str, *Tuple[int, ...], bool], None]\nreveal_type(y)  # N: Revealed type is \"def (builtins.str, *Unpack[Tuple[Unpack[builtins.tuple[builtins.int, ...]], builtins.bool]])\"\n\nP = ParamSpec(\"P\")\nclass C(Generic[P]): ...\nbad: C[[int, *Tuple[int, ...], int]]\nreveal_type(bad)  # N: Revealed type is \"__main__.C[[builtins.int, *Unpack[Tuple[Unpack[builtins.tuple[builtins.int, ...]], builtins.int]]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646UnspecifiedParameters]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\nclass Array(Generic[Unpack[Ts]]):\n    ...\n\ndef takes_any_array(arr: Array) -> None:\n    ...\n\nx: Array[int, bool]\ntakes_any_array(x)\n\nT = TypeVar(\"T\")\n\nclass Array2(Generic[T, Unpack[Ts]]):\n    ...\n\ndef takes_empty_array2(arr: Array2[int]) -> None:\n    ...\n\ny: Array2[int]\ntakes_empty_array2(y)\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTuplePep646CallableStarArgs]\nfrom typing import Tuple, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef call(\n    target: Callable[[Unpack[Ts]], None],\n    *args: Unpack[Ts],\n) -> None:\n    ...\n    target(*args)\n\nclass A:\n    def func(self, arg1: int, arg2: str) -> None: ...\n    def func2(self, arg1: int, arg2: int) -> None: ...\n    def func3(self, *args: int) -> None: ...\n\nvargs: Tuple[int, ...]\nvargs_str: Tuple[str, ...]\n\ncall(A().func)  # E: Argument 1 to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[], None]\"\ncall(A().func, 0, 'foo')\ncall(A().func, 0, 'foo', 0)  # E: Argument 1 to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[int, str, int], None]\"\ncall(A().func, 0)  # E: Argument 1 to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[int], None]\"\ncall(A().func, 0, 1)  # E: Argument 1 to \"call\" has incompatible type \"Callable[[int, str], None]\"; expected \"Callable[[int, int], None]\"\ncall(A().func2, 0, 0)\ncall(A().func3, 0, 1, 2)\ncall(A().func3)\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasBasicTuple]\nfrom typing import Tuple, List, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\nA = List[Tuple[T, Unpack[Ts], T]]\nx: A[int, str, str]\nreveal_type(x)  # N: Revealed type is \"builtins.list[Tuple[builtins.int, builtins.str, builtins.str, builtins.int]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasBasicCallable]\nfrom typing import TypeVar, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\n\nA = Callable[[T, Unpack[Ts]], S]\nx: A[int, str, int, str]\nreveal_type(x)  # N: Revealed type is \"def (builtins.int, builtins.str, builtins.int) -> builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasBasicInstance]\nfrom typing import TypeVar, Generic\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\nclass G(Generic[Unpack[Ts], T]): ...\n\nA = G[T, Unpack[Ts], T]\nx: A[int, str, str]\nreveal_type(x)  # N: Revealed type is \"__main__.G[builtins.int, builtins.str, builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasUnpackFixedTupleArgs]\nfrom typing import Tuple, List, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\n\nStart = Tuple[int, str]\nA = List[Tuple[T, Unpack[Ts], S]]\nx: A[Unpack[Start], int]\nreveal_type(x)  # N: Revealed type is \"builtins.list[Tuple[builtins.int, builtins.str, builtins.int]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasUnpackFixedTupleTarget]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\n\nPrefix = Tuple[int, int]\nA = Tuple[Unpack[Prefix], Unpack[Ts]]\nx: A[str, str]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasMultipleUnpacks]\nfrom typing import Tuple, Generic, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\nUs = TypeVarTuple(\"Us\")\nclass G(Generic[Unpack[Ts]]): ...\n\nA = Tuple[Unpack[Ts], Unpack[Us]]  # E: More than one Unpack in a type is not allowed\nx: A[int, str]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\nB = Callable[[Unpack[Ts], Unpack[Us]], int]  # E: More than one Unpack in a type is not allowed\ny: B[int, str]\nreveal_type(y)  # N: Revealed type is \"def (builtins.int, builtins.str) -> builtins.int\"\n\nC = G[Unpack[Ts], Unpack[Us]]  # E: More than one Unpack in a type is not allowed\nz: C[int, str]\nreveal_type(z)  # N: Revealed type is \"__main__.G[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasNoArgs]\nfrom typing import Tuple, TypeVar, Generic, Callable, List\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\nclass G(Generic[Unpack[Ts]]): ...\n\nA = List[Tuple[T, Unpack[Ts], T]]\nx: A\nreveal_type(x)  # N: Revealed type is \"builtins.list[Tuple[Any, Unpack[builtins.tuple[Any, ...]], Any]]\"\n\nB = Callable[[T, Unpack[Ts]], int]\ny: B\nreveal_type(y)  # N: Revealed type is \"def (Any, *Any) -> builtins.int\"\n\nC = G[T, Unpack[Ts], T]\nz: C\nreveal_type(z)  # N: Revealed type is \"__main__.G[Any, Unpack[builtins.tuple[Any, ...]], Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasFewArgs]\nfrom typing import Tuple, List, TypeVar, Generic, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nclass G(Generic[Unpack[Ts]]): ...\n\nA = List[Tuple[T, Unpack[Ts], S]]\nx: A[int]  # E: Bad number of arguments for type alias, expected at least 2, given 1\nreveal_type(x)  # N: Revealed type is \"builtins.list[Tuple[Any, Unpack[builtins.tuple[Any, ...]], Any]]\"\n\nB = Callable[[T, S, Unpack[Ts]], int]\ny: B[int]  # E: Bad number of arguments for type alias, expected at least 2, given 1\nreveal_type(y)  # N: Revealed type is \"def (Any, Any, *Any) -> builtins.int\"\n\nC = G[T, Unpack[Ts], S]\nz: C[int]  # E: Bad number of arguments for type alias, expected at least 2, given 1\nreveal_type(z)  # N: Revealed type is \"__main__.G[Any, Unpack[builtins.tuple[Any, ...]], Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasRecursiveUnpack]\nfrom typing import Tuple, Optional\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\nA = Tuple[Unpack[Ts], Optional[A[Unpack[Ts]]]]\nx: A[int, str]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, Union[..., None]]\"\n\n*_, last = x\nif last is not None:\n    reveal_type(last)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, Union[Tuple[builtins.int, builtins.str, Union[..., None]], None]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasUpperBoundCheck]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\nT = TypeVar(\"T\", bound=int)\nS = TypeVar(\"S\", bound=str)\nTs = TypeVarTuple(\"Ts\")\n\nAlias = Tuple[T, Unpack[Ts], S]\nFirst = Tuple[A, B]\nSecond = Tuple[C, D]\nx: Alias[Unpack[First], Unpack[Second]]  # E: Type argument \"A\" of \"Alias\" must be a subtype of \"int\" \\\n                                         # E: Type argument \"D\" of \"Alias\" must be a subtype of \"str\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasEmptyArg]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nA = Tuple[int, Unpack[Ts], str]\nx: A[()]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasVariadicTupleArg]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\nA = Tuple[int, Unpack[Ts]]\nB = A[str, Unpack[Ts]]\nC = B[Unpack[Tuple[bool, ...]]]\nx: C\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, Unpack[builtins.tuple[builtins.bool, ...]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasVariadicTupleArgGeneric]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\nA = Tuple[int, Unpack[Ts]]\nB = A[Unpack[Tuple[T, ...]]]\nx: B[str]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasVariadicTupleArgSplit]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\n\nA = Tuple[T, Unpack[Ts], S, T]\n\nx: A[int, Unpack[Tuple[bool, ...]], str]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.bool, ...]], builtins.str, builtins.int]\"\n\ny: A[Unpack[Tuple[bool, ...]]]\nreveal_type(y)  # N: Revealed type is \"Tuple[builtins.bool, Unpack[builtins.tuple[builtins.bool, ...]], builtins.bool, builtins.bool]\"\n[builtins fixtures/tuple.pyi]\n\n[case testBanPathologicalRecursiveTuples]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\nA = Tuple[int, Unpack[A]]  # E: Invalid recursive alias: a tuple item of itself\nB = Tuple[int, Unpack[C]]  # E: Invalid recursive alias: a tuple item of itself \\\n                           # E: Name \"C\" is used before definition\nC = Tuple[int, Unpack[B]]\nx: A\ny: B\nz: C\nreveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(y)  # N: Revealed type is \"Any\"\nreveal_type(z)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[Any, ...]]]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericVariadicWithBadType]\n# flags: --new-type-inference\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]], T]) -> Callable[[Unpack[Ts]], T]: ...\ndef f(*args: Unpack[Us]) -> Foo[Us]: ...  # E: TypeVarTuple \"Us\" is only valid with an unpack\ndec(f)  # No crash\n[builtins fixtures/tuple.pyi]\n\n[case testHomogeneousGenericTupleUnpackInferenceNoCrash1]\nfrom typing import Any, TypeVar, Tuple, Type, Optional\nfrom typing_extensions import Unpack\n\nT = TypeVar(\"T\")\ndef convert(obj: Any, *to_classes: Unpack[Tuple[Type[T], ...]]) -> Optional[T]:\n    ...\n\nx = convert(1, int, float)\nreveal_type(x)  # N: Revealed type is \"Union[builtins.float, None]\"\n[builtins fixtures/tuple.pyi]\n\n[case testHomogeneousGenericTupleUnpackInferenceNoCrash2]\nfrom typing import TypeVar, Tuple, Callable, Iterable\nfrom typing_extensions import Unpack\n\nT = TypeVar(\"T\")\ndef combine(x: T, y: T) -> T: ...\ndef reduce(fn: Callable[[T, T], T], xs: Iterable[T]) -> T: ...\n\ndef pipeline(*xs: Unpack[Tuple[int, Unpack[Tuple[str, ...]], bool]]) -> None:\n    reduce(combine, xs)\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicStarArgsCallNoCrash]\nfrom typing import TypeVar, Callable, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nX = TypeVar(\"X\")\nY = TypeVar(\"Y\")\nXs = TypeVarTuple(\"Xs\")\nYs = TypeVarTuple(\"Ys\")\n\ndef nil() -> Tuple[()]:\n    return ()\n\ndef cons(\n    f: Callable[[X], Y],\n    g: Callable[[Unpack[Xs]], Tuple[Unpack[Ys]]],\n) -> Callable[[X, Unpack[Xs]], Tuple[Y, Unpack[Ys]]]:\n    def wrapped(x: X, *xs: Unpack[Xs]) -> Tuple[Y, Unpack[Ys]]:\n        y, ys = f(x), g(*xs)\n        return y, *ys\n    return wrapped\n\ndef star(f: Callable[[X], Y]) -> Callable[[Unpack[Tuple[X, ...]]], Tuple[Y, ...]]:\n    def wrapped(*xs: X) -> Tuple[Y, ...]:\n        if not xs:\n            return nil()\n        return cons(f, star(f))(*xs)\n    return wrapped\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidTypeVarTupleUseNoCrash]\nfrom typing_extensions import TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef f(x: Ts) -> Ts:  # E: TypeVarTuple \"Ts\" is only valid with an unpack \\\n                     # E: TypeVarTuple \"Ts\" is only valid with an unpack\n    return x\n\nv = f(1, 2, \"A\")  # E: Too many arguments for \"f\"\nreveal_type(v)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleSimpleDecoratorWorks]\nfrom typing import TypeVar, Callable\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\ndef decorator(f: Callable[[Unpack[Ts]], T]) -> Callable[[Unpack[Ts]], T]:\n    def wrapper(*args: Unpack[Ts]) -> T:\n        return f(*args)\n    return wrapper\n\n@decorator\ndef f(a: int, b: int) -> int: ...\nreveal_type(f)  # N: Revealed type is \"def (builtins.int, builtins.int) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTupleWithUnpackIterator]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef pipeline(*xs: Unpack[Tuple[int, Unpack[Tuple[float, ...]], bool]]) -> None:\n    for x in xs:\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testFixedUnpackItemInInstanceArguments]\nfrom typing import TypeVar, Callable, Tuple, Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\n\nclass C(Generic[T, Unpack[Ts], S]):\n    prefix: T\n    suffix: S\n    middle: Tuple[Unpack[Ts]]\n\nInts = Tuple[int, int]\nc: C[Unpack[Ints]]\nreveal_type(c.prefix)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.suffix)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.middle)  # N: Revealed type is \"Tuple[()]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicUnpackItemInInstanceArguments]\nfrom typing import TypeVar, Callable, Tuple, Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\n\nclass Other(Generic[Unpack[Ts]]): ...\nclass C(Generic[T, Unpack[Ts], S]):\n    prefix: T\n    suffix: S\n    x: Tuple[Unpack[Ts]]\n    y: Callable[[Unpack[Ts]], None]\n    z: Other[Unpack[Ts]]\n\nInts = Tuple[int, ...]\nc: C[Unpack[Ints]]\nreveal_type(c.prefix)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.suffix)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(c.y)  # N: Revealed type is \"def (*builtins.int)\"\nreveal_type(c.z)  # N: Revealed type is \"__main__.Other[Unpack[builtins.tuple[builtins.int, ...]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTooFewItemsInInstanceArguments]\nfrom typing import Generic, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[T, Unpack[Ts], S]): ...\n\nc: C[int]  # E: Bad number of arguments, expected: at least 2, given: 1\nreveal_type(c)  # N: Revealed type is \"__main__.C[Any, Unpack[builtins.tuple[Any, ...]], Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicClassUpperBoundCheck]\nfrom typing import Tuple, TypeVar, Generic\nfrom typing_extensions import Unpack, TypeVarTuple\n\nclass A: ...\nclass B: ...\nclass C: ...\nclass D: ...\n\nT = TypeVar(\"T\", bound=int)\nS = TypeVar(\"S\", bound=str)\nTs = TypeVarTuple(\"Ts\")\n\nclass G(Generic[T, Unpack[Ts], S]): ...\nFirst = Tuple[A, B]\nSecond = Tuple[C, D]\nx: G[Unpack[First], Unpack[Second]]  # E: Type argument \"A\" of \"G\" must be a subtype of \"int\" \\\n                                     # E: Type argument \"D\" of \"G\" must be a subtype of \"str\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleType]\nfrom typing import Tuple, Callable\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass A(Tuple[Unpack[Ts]]):\n    fn: Callable[[Unpack[Ts]], None]\n\nx: A[int]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, fallback=__main__.A[builtins.int]]\"\nreveal_type(x[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(x.fn)  # N: Revealed type is \"def (builtins.int)\"\n\ny: A[int, str]\nreveal_type(y)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.A[builtins.int, builtins.str]]\"\nreveal_type(y[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(y.fn)  # N: Revealed type is \"def (builtins.int, builtins.str)\"\n\nz: A[Unpack[Tuple[int, ...]]]\nreveal_type(z)  # N: Revealed type is \"__main__.A[Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(z[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(z.fn)  # N: Revealed type is \"def (*builtins.int)\"\n\nt: A[int, Unpack[Tuple[int, str]], str]\nreveal_type(t)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, builtins.str, builtins.str, fallback=__main__.A[builtins.int, builtins.int, builtins.str, builtins.str]]\"\nreveal_type(t[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(t.fn)  # N: Revealed type is \"def (builtins.int, builtins.int, builtins.str, builtins.str)\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicNamedTuple]\nfrom typing import Tuple, Callable, NamedTuple, Generic, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\nclass A(NamedTuple, Generic[Unpack[Ts], T]):\n    fn: Callable[[Unpack[Ts]], None]\n    val: T\n\ny: A[int, str]\nreveal_type(y)  # N: Revealed type is \"Tuple[def (builtins.int), builtins.str, fallback=__main__.A[builtins.int, builtins.str]]\"\nreveal_type(y[0])  # N: Revealed type is \"def (builtins.int)\"\nreveal_type(y.fn)  # N: Revealed type is \"def (builtins.int)\"\n\nz: A[Unpack[Tuple[int, ...]]]\nreveal_type(z)  # N: Revealed type is \"Tuple[def (*builtins.int), builtins.int, fallback=__main__.A[Unpack[builtins.tuple[builtins.int, ...]], builtins.int]]\"\nreveal_type(z.fn)  # N: Revealed type is \"def (*builtins.int)\"\n\nt: A[int, Unpack[Tuple[int, str]], str]\nreveal_type(t)  # N: Revealed type is \"Tuple[def (builtins.int, builtins.int, builtins.str), builtins.str, fallback=__main__.A[builtins.int, builtins.int, builtins.str, builtins.str]]\"\n\ndef test(x: int, y: str) -> None: ...\nnt = A(fn=test, val=42)\nreveal_type(nt)  # N: Revealed type is \"Tuple[def (builtins.int, builtins.str), builtins.int, fallback=__main__.A[builtins.int, builtins.str, builtins.int]]\"\n\ndef bad() -> int: ...\nnt2 = A(fn=bad, val=42)  # E: Argument \"fn\" to \"A\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[], None]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTypedDict]\nfrom typing import Tuple, Callable, Generic, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack, TypedDict\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\nclass A(TypedDict, Generic[Unpack[Ts], T]):\n    fn: Callable[[Unpack[Ts]], None]\n    val: T\n\ny: A[int, str]\nreveal_type(y)  # N: Revealed type is \"TypedDict('__main__.A', {'fn': def (builtins.int), 'val': builtins.str})\"\nreveal_type(y[\"fn\"])  # N: Revealed type is \"def (builtins.int)\"\n\nz: A[Unpack[Tuple[int, ...]]]\nreveal_type(z)  # N: Revealed type is \"TypedDict('__main__.A', {'fn': def (*builtins.int), 'val': builtins.int})\"\nreveal_type(z[\"fn\"])  # N: Revealed type is \"def (*builtins.int)\"\n\nt: A[int, Unpack[Tuple[int, str]], str]\nreveal_type(t)  # N: Revealed type is \"TypedDict('__main__.A', {'fn': def (builtins.int, builtins.int, builtins.str), 'val': builtins.str})\"\n\ndef test(x: int, y: str) -> None: ...\ntd = A({\"fn\": test, \"val\": 42})\nreveal_type(td)  # N: Revealed type is \"TypedDict('__main__.A', {'fn': def (builtins.int, builtins.str), 'val': builtins.int})\"\n\ndef bad() -> int: ...\ntd2 = A({\"fn\": bad, \"val\": 42})  # E: Incompatible types (expression has type \"Callable[[], int]\", TypedDict item \"fn\" has type \"Callable[[], None]\")\n[builtins fixtures/tuple.pyi]\n\n[case testFixedUnpackWithRegularInstance]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import Unpack\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\nT4 = TypeVar(\"T4\")\n\nclass C(Generic[T1, T2, T3, T4]): ...\nx: C[int, Unpack[Alias], str]\nAlias = Tuple[int, str]\nreveal_type(x)  # N: Revealed type is \"__main__.C[builtins.int, builtins.int, builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicUnpackWithRegularInstance]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import Unpack\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\nT4 = TypeVar(\"T4\")\n\nclass C(Generic[T1, T2, T3, T4]): ...\nx: C[int, Unpack[Alias], str, str]  # E: Unpack is only valid in a variadic position\nAlias = Tuple[int, ...]\nreveal_type(x)  # N: Revealed type is \"__main__.C[Any, Any, Any, Any]\"\ny: C[int, Unpack[Undefined]]  # E: Name \"Undefined\" is not defined\nreveal_type(y)  # N: Revealed type is \"__main__.C[Any, Any, Any, Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasInvalidUnpackNoCrash]\nfrom typing import Tuple, Generic, Union, List\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\nAlias = Tuple[int, Unpack[Ts], str]\n\nA = Union[int, str]\nx: List[Alias[int, Unpack[A], str]]  # E: \"Union[int, str]\" cannot be unpacked (must be tuple or TypeVarTuple)\nreveal_type(x)  # N: Revealed type is \"builtins.list[Tuple[builtins.int, builtins.int, Unpack[builtins.tuple[Any, ...]], builtins.str, builtins.str]]\"\ny: List[Alias[int, Unpack[Undefined], str]]  # E: Name \"Undefined\" is not defined\nreveal_type(y)  # N: Revealed type is \"builtins.list[Tuple[builtins.int, Unpack[builtins.tuple[Any, ...]], builtins.str]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasForwardRefToFixedUnpack]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nAlias = Tuple[T, Unpack[Ts], S]\nx: Alias[int, Unpack[Other]]\nOther = Tuple[int, str]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasForwardRefToVariadicUnpack]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nAlias = Tuple[T, Unpack[Ts], S]\nx: Alias[int, Unpack[Other]]\nOther = Tuple[int, ...]\nreveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]], builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicInstanceStrictPrefixSuffixCheck]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[T, Unpack[Ts], S]): ...\n\ndef foo(x: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]:\n    y: C[int, Unpack[Ts]]  # E: TypeVarTuple cannot be split\n    z: C[Unpack[Ts], int]  # E: TypeVarTuple cannot be split\n    return x\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicAliasStrictPrefixSuffixCheck]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nAlias = Tuple[T, Unpack[Ts], S]\n\ndef foo(x: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]:\n    y: Alias[int, Unpack[Ts]]  # E: TypeVarTuple cannot be split\n    z: Alias[Unpack[Ts], int]  # E: TypeVarTuple cannot be split\n    return x\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleWithIsInstance]\n# flags: --warn-unreachable\nfrom typing import Generic, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTP = TypeVarTuple(\"TP\")\nclass A(Tuple[Unpack[TP]]): ...\n\ndef test(d: A[int, str]) -> None:\n    if isinstance(d, A):\n        reveal_type(d)  # N: Revealed type is \"Tuple[builtins.int, builtins.str, fallback=__main__.A[builtins.int, builtins.str]]\"\n    else:\n        reveal_type(d)  # E: Statement is unreachable\n\nclass B(Generic[Unpack[TP]]): ...\n\ndef test2(d: B[int, str]) -> None:\n    if isinstance(d, B):\n        reveal_type(d)  # N: Revealed type is \"__main__.B[builtins.int, builtins.str]\"\n    else:\n        reveal_type(d)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testVariadicTupleSubtyping]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef f1(x: Tuple[float, ...]) -> None: ...\ndef f2(x: Tuple[float, Unpack[Tuple[float, ...]]]) -> None: ...\ndef f3(x: Tuple[Unpack[Tuple[float, ...]], float]) -> None: ...\ndef f4(x: Tuple[float, Unpack[Tuple[float, ...]], float]) -> None: ...\n\nt1: Tuple[int, int]\nt2: Tuple[int, Unpack[Tuple[int, ...]]]\nt3: Tuple[Unpack[Tuple[int, ...]], int]\nt4: Tuple[int, Unpack[Tuple[int, ...]], int]\nt5: Tuple[int, ...]\n\ntl: Tuple[int, int, Unpack[Tuple[int, ...]]]\ntr: Tuple[Unpack[Tuple[int, ...]], int, int]\n\nf1(t1)\nf1(t2)\nf1(t3)\nf1(t4)\nf1(t5)\n\nf1(tl)\nf1(tr)\n\nf2(t1)\nf2(t2)\nf2(t3)\nf2(t4)\nf2(t5)  # E: Argument 1 to \"f2\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[float, Unpack[Tuple[float, ...]]]\"\n\nf2(tl)\nf2(tr)\n\nf3(t1)\nf3(t2)\nf3(t3)\nf3(t4)\nf3(t5)  # E: Argument 1 to \"f3\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[Unpack[Tuple[float, ...]], float]\"\n\nf3(tl)\nf3(tr)\n\nf4(t1)\nf4(t2)  # E: Argument 1 to \"f4\" has incompatible type \"Tuple[int, Unpack[Tuple[int, ...]]]\"; expected \"Tuple[float, Unpack[Tuple[float, ...]], float]\"\nf4(t3)  # E: Argument 1 to \"f4\" has incompatible type \"Tuple[Unpack[Tuple[int, ...]], int]\"; expected \"Tuple[float, Unpack[Tuple[float, ...]], float]\"\nf4(t4)\nf4(t5)  # E: Argument 1 to \"f4\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[float, Unpack[Tuple[float, ...]], float]\"\n\nf4(tl)\nf4(tr)\n\nt5_verbose: Tuple[Unpack[Tuple[int, ...]]]\nt5 = t5_verbose  # OK\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleInference]\nfrom typing import List, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\ndef f(x: Tuple[int, Unpack[Tuple[T, ...]]]) -> T: ...\n\nvt0: Tuple[int, ...]\nf(vt0)  # E: Argument 1 to \"f\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[int, Unpack[Tuple[int, ...]]]\"\n\nvt1: Tuple[Unpack[Tuple[int, ...]], int]\nreveal_type(f(vt1))  # N: Revealed type is \"builtins.int\"\n\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\ndef g(x: Tuple[T, Unpack[Ts], S]) -> Tuple[T, Unpack[Ts], S]: ...\ng(vt0)  # E: Argument 1 to \"g\" has incompatible type \"Tuple[int, ...]\"; expected \"Tuple[int, Unpack[Tuple[int, ...]], int]\"\n\nU = TypeVar(\"U\")\ndef h(x: List[Tuple[T, S, U]]) -> Tuple[T, S, U]: ...\nvt2: Tuple[Unpack[Tuple[int, ...]], int]\nvt2 = h(reveal_type([]))  # N: Revealed type is \"builtins.list[Tuple[builtins.int, builtins.int, builtins.int]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicSelfTypeErasure]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass Array(Generic[Unpack[Ts]]):\n    def _close(self) -> None: ...\n\n    def close(self) -> None:\n        self._close()\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicSubclassFixed]\nfrom typing import Generic, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]): ...\nclass C(B[int, str]): ...\nclass D(B[Unpack[Tuple[int, ...]]]): ...\n\ndef fii(x: B[int, int]) -> None: ...\ndef fis(x: B[int, str]) -> None: ...\ndef fiv(x: B[Unpack[Tuple[int, ...]]]) -> None: ...\n\nfii(C())  # E: Argument 1 to \"fii\" has incompatible type \"C\"; expected \"B[int, int]\"\nfii(D())  # E: Argument 1 to \"fii\" has incompatible type \"D\"; expected \"B[int, int]\"\nfis(C())\nfis(D())  # E: Argument 1 to \"fis\" has incompatible type \"D\"; expected \"B[int, str]\"\nfiv(C())  # E: Argument 1 to \"fiv\" has incompatible type \"C\"; expected \"B[Unpack[Tuple[int, ...]]]\"\nfiv(D())\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicSubclassSame]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]): ...\nclass C(B[Unpack[Ts]]): ...\n\ndef fii(x: B[int, int]) -> None: ...\ndef fis(x: B[int, str]) -> None: ...\ndef fiv(x: B[Unpack[Tuple[int, ...]]]) -> None: ...\n\ncii: C[int, int]\ncis: C[int, str]\nciv: C[Unpack[Tuple[int, ...]]]\n\nfii(cii)\nfii(cis)  # E: Argument 1 to \"fii\" has incompatible type \"C[int, str]\"; expected \"B[int, int]\"\nfii(civ)  # E: Argument 1 to \"fii\" has incompatible type \"C[Unpack[Tuple[int, ...]]]\"; expected \"B[int, int]\"\n\nfis(cii)  # E: Argument 1 to \"fis\" has incompatible type \"C[int, int]\"; expected \"B[int, str]\"\nfis(cis)\nfis(civ)  # E: Argument 1 to \"fis\" has incompatible type \"C[Unpack[Tuple[int, ...]]]\"; expected \"B[int, str]\"\n\nfiv(cii)\nfiv(cis)  # E: Argument 1 to \"fiv\" has incompatible type \"C[int, str]\"; expected \"B[Unpack[Tuple[int, ...]]]\"\nfiv(civ)\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicSubclassExtra]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]): ...\n\nT = TypeVar(\"T\")\nclass C(B[int, Unpack[Ts], T]): ...\n\ndef ff(x: B[int, int, int]) -> None: ...\ndef fv(x: B[Unpack[Tuple[int, ...]]]) -> None: ...\n\ncii: C[int, int]\ncis: C[int, str]\nciv: C[Unpack[Tuple[int, ...]]]\n\nff(cii)\nff(cis)  # E: Argument 1 to \"ff\" has incompatible type \"C[int, str]\"; expected \"B[int, int, int]\"\nff(civ)  # E: Argument 1 to \"ff\" has incompatible type \"C[Unpack[Tuple[int, ...]]]\"; expected \"B[int, int, int]\"\n\nfv(cii)\nfv(cis)  # E: Argument 1 to \"fv\" has incompatible type \"C[int, str]\"; expected \"B[Unpack[Tuple[int, ...]]]\"\nfv(civ)\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicSubclassVariadic]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]): ...\nT = TypeVar(\"T\")\nclass C(B[Unpack[Tuple[T, ...]]]): ...\n\ndef ff(x: B[int, int]) -> None: ...\ndef fv(x: B[Unpack[Tuple[int, ...]]]) -> None: ...\n\nci: C[int]\nff(ci)  # E: Argument 1 to \"ff\" has incompatible type \"C[int]\"; expected \"B[int, int]\"\nfv(ci)\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicSubclassMethodAccess]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]):\n    def meth(self) -> Tuple[Unpack[Ts]]: ...\n\nclass C1(B[int, str]): ...\nclass C2(B[Unpack[Ts]]): ...\nT = TypeVar(\"T\")\nclass C3(B[int, Unpack[Ts], T]): ...\nclass C4(B[Unpack[Tuple[T, ...]]]): ...\n\nc1: C1\nreveal_type(c1.meth())  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\nc2f: C2[int, str]\nc2v: C2[Unpack[Tuple[int, ...]]]\nreveal_type(c2f.meth())  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\nreveal_type(c2v.meth())  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nc3f: C3[int, str]\nc3v: C3[Unpack[Tuple[int, ...]]]\nreveal_type(c3f.meth())  # N: Revealed type is \"Tuple[builtins.int, builtins.int, builtins.str]\"\nreveal_type(c3v.meth())  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]], builtins.int]\"\n\nc4: C4[int]\nreveal_type(c4.meth())  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleAnySubtype]\nfrom typing import Any, Generic, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]): ...\nclass C1(B[Unpack[Tuple[Any, ...]]]): ...\nc1 = C1()\nclass C2(B): ...\nc2 = C2()\nx: B[int, str]\nx = c1\nx = c2\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleAnySubtypeTupleType]\nfrom typing import Any, Generic, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Tuple[Unpack[Ts]]): ...\nclass C1(B[Unpack[Tuple[Any, ...]]]): ...\nc1 = C1()\nclass C2(B): ...\nc2 = C2()\nx: B[int, str]\nx = c1\nx = c2\n[builtins fixtures/tuple.pyi]\n\n[case testUnpackingVariadicTuplesTypeVar]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(arg: Tuple[int, Unpack[Ts], str]) -> None:\n    x1, y1, z1 = arg  # E: Variadic tuple unpacking requires a star target\n    reveal_type(x1)  # N: Revealed type is \"Any\"\n    reveal_type(y1)  # N: Revealed type is \"Any\"\n    reveal_type(z1)  # N: Revealed type is \"Any\"\n    x2, *y2, z2 = arg\n    reveal_type(x2)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y2)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z2)  # N: Revealed type is \"builtins.str\"\n    x3, *y3 = arg\n    reveal_type(x3)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y3)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    *y4, z4 = arg\n    reveal_type(y4)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z4)  # N: Revealed type is \"builtins.str\"\n    x5, xx5, *y5, z5, zz5 = arg  # E: Too many assignment targets for variadic unpack\n    reveal_type(x5)  # N: Revealed type is \"Any\"\n    reveal_type(xx5)  # N: Revealed type is \"Any\"\n    reveal_type(y5)  # N: Revealed type is \"builtins.list[Any]\"\n    reveal_type(z5)  # N: Revealed type is \"Any\"\n    reveal_type(zz5)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnpackingVariadicTuplesHomogeneous]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef bar(arg: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:\n    x1, y1, z1 = arg  # E: Variadic tuple unpacking requires a star target\n    reveal_type(x1)  # N: Revealed type is \"Any\"\n    reveal_type(y1)  # N: Revealed type is \"Any\"\n    reveal_type(z1)  # N: Revealed type is \"Any\"\n    x2, *y2, z2 = arg\n    reveal_type(x2)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y2)  # N: Revealed type is \"builtins.list[builtins.float]\"\n    reveal_type(z2)  # N: Revealed type is \"builtins.str\"\n    x3, *y3 = arg\n    reveal_type(x3)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y3)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    *y4, z4 = arg\n    reveal_type(y4)  # N: Revealed type is \"builtins.list[builtins.float]\"\n    reveal_type(z4)  # N: Revealed type is \"builtins.str\"\n    x5, xx5, *y5, z5, zz5 = arg  # E: Too many assignment targets for variadic unpack\n    reveal_type(x5)  # N: Revealed type is \"Any\"\n    reveal_type(xx5)  # N: Revealed type is \"Any\"\n    reveal_type(y5)  # N: Revealed type is \"builtins.list[Any]\"\n    reveal_type(z5)  # N: Revealed type is \"Any\"\n    reveal_type(zz5)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testRepackingVariadicTuplesTypeVar]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(arg: Tuple[int, Unpack[Ts], str]) -> None:\n    x1, *y1, z1 = *arg,\n    reveal_type(x1)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y1)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z1)  # N: Revealed type is \"builtins.str\"\n    x2, *y2, z2 = 1, *arg, 2\n    reveal_type(x2)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y2)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z2)  # N: Revealed type is \"builtins.int\"\n    x3, *y3 = *arg, 42\n    reveal_type(x3)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y3)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    *y4, z4 = 42, *arg\n    reveal_type(y4)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z4)  # N: Revealed type is \"builtins.str\"\n    x5, xx5, *y5, z5, zz5 = 1, *arg, 2\n    reveal_type(x5)  # N: Revealed type is \"builtins.int\"\n    reveal_type(xx5)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y5)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z5)  # N: Revealed type is \"builtins.str\"\n    reveal_type(zz5)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testRepackingVariadicTuplesHomogeneous]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef foo(arg: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:\n    x1, *y1, z1 = *arg,\n    reveal_type(x1)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y1)  # N: Revealed type is \"builtins.list[builtins.float]\"\n    reveal_type(z1)  # N: Revealed type is \"builtins.str\"\n    x2, *y2, z2 = 1, *arg, 2\n    reveal_type(x2)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y2)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z2)  # N: Revealed type is \"builtins.int\"\n    x3, *y3 = *arg, 42\n    reveal_type(x3)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y3)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    *y4, z4 = 42, *arg\n    reveal_type(y4)  # N: Revealed type is \"builtins.list[builtins.float]\"\n    reveal_type(z4)  # N: Revealed type is \"builtins.str\"\n    x5, xx5, *y5, z5, zz5 = 1, *arg, 2\n    reveal_type(x5)  # N: Revealed type is \"builtins.int\"\n    reveal_type(xx5)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y5)  # N: Revealed type is \"builtins.list[builtins.float]\"\n    reveal_type(z5)  # N: Revealed type is \"builtins.str\"\n    reveal_type(zz5)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testPackingVariadicTuplesTypeVar]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(arg: Tuple[int, Unpack[Ts], str]) -> None:\n    x = *arg,\n    reveal_type(x)  # N: Revealed type is \"Tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n    y = 1, *arg, 2\n    reveal_type(y)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, Unpack[Ts`-1], builtins.str, builtins.int]\"\n    z = (*arg, *arg)\n    reveal_type(z)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPackingVariadicTuplesHomogeneous]\n# flags: --enable-incomplete-feature=PreciseTupleTypes\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\na: Tuple[float, ...]\nb: Tuple[int, Unpack[Tuple[float, ...]], str]\n\nx = *a,\nreveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.float, ...]\"\ny = 1, *a, 2\nreveal_type(y)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.int]\"\nz = (*a, *a)\nreveal_type(z)  # N: Revealed type is \"builtins.tuple[builtins.float, ...]\"\n\nx2 = *b,\nreveal_type(x2)  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\ny2 = 1, *b, 2\nreveal_type(y2)  # N: Revealed type is \"Tuple[builtins.int, builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str, builtins.int]\"\nz2 = (*b, *b)\nreveal_type(z2)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleInListSetExpr]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nvt: Tuple[int, Unpack[Tuple[float, ...]], int]\nreveal_type([1, *vt])  # N: Revealed type is \"builtins.list[builtins.float]\"\nreveal_type({1, *vt})  # N: Revealed type is \"builtins.set[builtins.float]\"\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(arg: Tuple[int, Unpack[Ts], str]) -> None:\n    reveal_type([1, *arg])  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type({1, *arg})  # N: Revealed type is \"builtins.set[builtins.object]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testVariadicTupleInTupleContext]\n# flags: --enable-incomplete-feature=PreciseTupleTypes\nfrom typing import Tuple, Optional\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef test(x: Optional[Tuple[Unpack[Ts]]] = None) -> Tuple[Unpack[Ts]]: ...\n\nvt: Tuple[int, Unpack[Tuple[float, ...]], int]\nvt = 1, *test(), 2  # OK, type context is used\nvt2 = 1, *test(), 2  # E: Need type annotation for \"vt2\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleConcatenation]\n# flags: --enable-incomplete-feature=PreciseTupleTypes\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nvtf: Tuple[float, ...]\nvt: Tuple[int, Unpack[Tuple[float, ...]], int]\n\nreveal_type(vt + (1, 2))  # N: Revealed type is \"Tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.int, Literal[1]?, Literal[2]?]\"\nreveal_type((1, 2) + vt)  # N: Revealed type is \"Tuple[Literal[1]?, Literal[2]?, builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.int]\"\nreveal_type(vt + vt)  # N: Revealed type is \"builtins.tuple[Union[builtins.int, builtins.float], ...]\"\nreveal_type(vtf + (1, 2))  # N: Revealed type is \"Tuple[Unpack[builtins.tuple[builtins.float, ...]], Literal[1]?, Literal[2]?]\"\nreveal_type((1, 2) + vtf)  # N: Revealed type is \"Tuple[Literal[1]?, Literal[2]?, Unpack[builtins.tuple[builtins.float, ...]]]\"\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(arg: Tuple[int, Unpack[Ts], str]) -> None:\n    reveal_type(arg + (1, 2))  # N: Revealed type is \"Tuple[builtins.int, Unpack[Ts`-1], builtins.str, Literal[1]?, Literal[2]?]\"\n    reveal_type((1, 2) + arg)  # N: Revealed type is \"Tuple[Literal[1]?, Literal[2]?, builtins.int, Unpack[Ts`-1], builtins.str]\"\n    reveal_type(arg + arg)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleAnyOverload]\nfrom typing import Any, Generic, overload, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass Array(Generic[Unpack[Ts]]): ...\n\nclass A:\n    @overload\n    def f(self, x: Tuple[Unpack[Ts]]) -> Array[Unpack[Ts]]: ...\n    @overload\n    def f(self, x: Any) -> Any: ...\n    def f(self, x: Any) -> Any:\n        ...\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleInferAgainstAny]\nfrom typing import Any, Tuple, TypeVar\nfrom typing_extensions import Unpack\n\nT = TypeVar(\"T\")\n\ndef test(x: int, t: Tuple[T, ...]) -> Tuple[int, Unpack[Tuple[T, ...]]]:\n    ...\na: Any = test(42, ())\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleIndexTypeVar]\nfrom typing import Any, List, Sequence, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef f(data: Sequence[Tuple[Unpack[Ts]]]) -> List[Any]:\n    return [d[0] for d in data]  # E: Tuple index out of range \\\n                                 # N: Variadic tuple can have length 0\n\nT = TypeVar(\"T\")\ndef g(data: Sequence[Tuple[T, Unpack[Ts]]]) -> List[T]:\n    return [d[0] for d in data]  # OK\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleOverloadMatch]\nfrom typing import Any, Generic, overload, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\n_Ts = TypeVarTuple(\"_Ts\")\n_T = TypeVar(\"_T\")\n_T2 = TypeVar(\"_T2\")\n\nclass Container(Generic[_T]): ...\nclass Array(Generic[Unpack[_Ts]]): ...\n\n@overload\ndef build(entity: Container[_T], /) -> Array[_T]: ...\n@overload\ndef build(entity: Container[_T], entity2: Container[_T2], /) -> Array[_T, _T2]: ...\n@overload\ndef build(*entities: Container[Any]) -> Array[Unpack[Tuple[Any, ...]]]: ...\ndef build(*entities: Container[Any]) -> Array[Unpack[Tuple[Any, ...]]]:\n    ...\n\ndef test(a: Container[Any], b: Container[int], c: Container[str]):\n    reveal_type(build(a, b))  # N: Revealed type is \"__main__.Array[Any, builtins.int]\"\n    reveal_type(build(b, c))  # N: Revealed type is \"__main__.Array[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleOverloadArbitraryLength]\nfrom typing import Any, Tuple, TypeVar, TypeVarTuple, Unpack, overload\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n@overload\ndef add(self: Tuple[Unpack[Ts]], other: Tuple[T]) -> Tuple[Unpack[Ts], T]:\n    ...\n@overload\ndef add(self: Tuple[T, ...], other: Tuple[T, ...]) -> Tuple[T, ...]:\n    ...\ndef add(self: Any, other: Any) -> Any:\n    ...\ndef test(a: Tuple[int, str], b: Tuple[bool], c: Tuple[bool, ...]):\n    reveal_type(add(a, b))  # N: Revealed type is \"Tuple[builtins.int, builtins.str, builtins.bool]\"\n    reveal_type(add(b, c))  # N: Revealed type is \"builtins.tuple[builtins.bool, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleOverloadOverlap]\nfrom typing import Union, overload, Tuple\nfrom typing_extensions import Unpack\n\nclass Int(int): ...\n\nA = Tuple[int, Unpack[Tuple[int, ...]]]\nB = Tuple[int, Unpack[Tuple[str, ...]]]\n\n@overload\ndef f(arg: A) -> int: ...\n@overload\ndef f(arg: B) -> str: ...\ndef f(arg: Union[A, B]) -> Union[int, str]:\n    ...\n\nA1 = Tuple[int, Unpack[Tuple[Int, ...]]]\nB1 = Tuple[Unpack[Tuple[Int, ...]], int]\n\n@overload\ndef f1(arg: A1) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f1(arg: B1) -> str: ...\ndef f1(arg: Union[A1, B1]) -> Union[int, str]:\n    ...\n\nA2 = Tuple[int, int, int]\nB2 = Tuple[int, Unpack[Tuple[int, ...]]]\n\n@overload\ndef f2(arg: A2) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f2(arg: B2) -> str: ...\ndef f2(arg: Union[A2, B2]) -> Union[int, str]:\n    ...\n\nA3 = Tuple[int, int, int]\nB3 = Tuple[int, Unpack[Tuple[str, ...]]]\n\n@overload\ndef f3(arg: A3) -> int: ...\n@overload\ndef f3(arg: B3) -> str: ...\ndef f3(arg: Union[A3, B3]) -> Union[int, str]:\n    ...\n\nA4 = Tuple[int, int, Unpack[Tuple[int, ...]]]\nB4 = Tuple[int]\n\n@overload\ndef f4(arg: A4) -> int: ...\n@overload\ndef f4(arg: B4) -> str: ...\ndef f4(arg: Union[A4, B4]) -> Union[int, str]:\n    ...\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleIndexOldStyleNonNormalizedAndNonLiteral]\nfrom typing import Any, Tuple\nfrom typing_extensions import Unpack\n\nt: Tuple[Unpack[Tuple[int, ...]]]\nreveal_type(t[42])  # N: Revealed type is \"builtins.int\"\ni: int\nreveal_type(t[i])  # N: Revealed type is \"builtins.int\"\nt1: Tuple[int, Unpack[Tuple[int, ...]]]\nreveal_type(t1[i])  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleNotConcreteCallable]\nfrom typing_extensions import Unpack, TypeVarTuple\nfrom typing import Callable, TypeVar, Tuple\n\nT = TypeVar(\"T\")\nArgs = TypeVarTuple(\"Args\")\nArgs2 = TypeVarTuple(\"Args2\")\n\ndef submit(fn: Callable[[Unpack[Args]], T], *args: Unpack[Args]) -> T:\n    ...\n\ndef submit2(fn: Callable[[int, Unpack[Args]], T], *args: Unpack[Tuple[int, Unpack[Args]]]) -> T:\n    ...\n\ndef foo(func: Callable[[Unpack[Args]], T], *args: Unpack[Args]) -> T:\n   return submit(func, *args)\n\ndef foo2(func: Callable[[Unpack[Args2]], T], *args: Unpack[Args2]) -> T:\n   return submit(func, *args)\n\ndef foo3(func: Callable[[int, Unpack[Args2]], T], *args: Unpack[Args2]) -> T:\n   return submit2(func, 1, *args)\n\ndef foo_bad(func: Callable[[Unpack[Args2]], T], *args: Unpack[Args2]) -> T:\n   return submit2(func, 1, *args)  # E: Argument 1 to \"submit2\" has incompatible type \"Callable[[VarArg(Unpack[Args2])], T]\"; expected \"Callable[[int, VarArg(Unpack[Args2])], T]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleParamSpecInteraction]\nfrom typing_extensions import Unpack, TypeVarTuple, ParamSpec\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\nArgs = TypeVarTuple(\"Args\")\nArgs2 = TypeVarTuple(\"Args2\")\nP = ParamSpec(\"P\")\n\ndef submit(fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    ...\n\ndef foo(func: Callable[[Unpack[Args]], T], *args: Unpack[Args]) -> T:\n   return submit(func, *args)\n\ndef foo2(func: Callable[[Unpack[Args]], T], *args: Unpack[Args2]) -> T:\n   return submit(func, *args)  # E: Argument 2 to \"submit\" has incompatible type \"*Tuple[Unpack[Args2]]\"; expected \"Unpack[Args]\"\n\ndef foo3(func: Callable[[int, Unpack[Args2]], T], *args: Unpack[Args2]) -> T:\n   return submit(func, 1, *args)\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleEmptySpecialCase]\nfrom typing import Any, Callable, Generic\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\nclass MyClass(Generic[Unpack[Ts]]):\n    func: Callable[[Unpack[Ts]], object]\n\n    def __init__(self, func: Callable[[Unpack[Ts]], object]) -> None:\n        self.func = func\n\nexplicit: MyClass[()]\nreveal_type(explicit)  # N: Revealed type is \"__main__.MyClass[()]\"\nreveal_type(explicit.func)  # N: Revealed type is \"def () -> builtins.object\"\n\na: Any\nexplicit_2 = MyClass[()](a)\nreveal_type(explicit_2)  # N: Revealed type is \"__main__.MyClass[()]\"\nreveal_type(explicit_2.func)  # N: Revealed type is \"def () -> builtins.object\"\n\nAlias = MyClass[()]\nexplicit_3: Alias\nreveal_type(explicit_3)  # N: Revealed type is \"__main__.MyClass[()]\"\nreveal_type(explicit_3.func)  # N: Revealed type is \"def () -> builtins.object\"\n\nexplicit_4 = Alias(a)\nreveal_type(explicit_4)  # N: Revealed type is \"__main__.MyClass[()]\"\nreveal_type(explicit_4.func)  # N: Revealed type is \"def () -> builtins.object\"\n\ndef no_args() -> None: ...\nimplicit = MyClass(no_args)\nreveal_type(implicit)  # N: Revealed type is \"__main__.MyClass[()]\"\nreveal_type(implicit.func)  # N: Revealed type is \"def () -> builtins.object\"\n\ndef one_arg(__a: int) -> None: ...\nx = MyClass(one_arg)\nx = explicit  # E: Incompatible types in assignment (expression has type \"MyClass[()]\", variable has type \"MyClass[int]\")\n\n# Consistently handle special case for no argument aliases\nDirect = MyClass\ny = Direct(one_arg)\nreveal_type(y)  # N: Revealed type is \"__main__.MyClass[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleRuntimeTypeApplication]\nfrom typing import Generic, TypeVar, Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[T, Unpack[Ts], S]): ...\n\nInts = Tuple[int, int]\nx = C[Unpack[Ints]]()\nreveal_type(x)  # N: Revealed type is \"__main__.C[builtins.int, builtins.int]\"\n\ny = C[Unpack[Tuple[int, ...]]]()\nreveal_type(y)  # N: Revealed type is \"__main__.C[builtins.int, Unpack[builtins.tuple[builtins.int, ...]], builtins.int]\"\n\nz = C[int]()  # E: Bad number of arguments, expected: at least 2, given: 1\nreveal_type(z)  # N: Revealed type is \"__main__.C[Any, Unpack[builtins.tuple[Any, ...]], Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleTupleSubclassPrefixSuffix]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ni: int\n\nclass A(Tuple[int, Unpack[Tuple[int, ...]]]): ...\na: A\nreveal_type(a[i])  # N: Revealed type is \"builtins.int\"\n\nclass B(Tuple[Unpack[Tuple[int, ...]], int]): ...\nb: B\nreveal_type(b[i])  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicClassSubclassInit]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]):\n    def __init__(self, x: Tuple[Unpack[Ts]], *args: Unpack[Ts]) -> None: ...\nreveal_type(B)  # N: Revealed type is \"def [Ts] (x: Tuple[Unpack[Ts`1]], *args: Unpack[Ts`1]) -> __main__.B[Unpack[Ts`1]]\"\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass C(B[T, S]): ...\nreveal_type(C)  # N: Revealed type is \"def [T, S] (x: Tuple[T`1, S`2], T`1, S`2) -> __main__.C[T`1, S`2]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicClassGenericSelf]\nfrom typing import Tuple, Generic, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]):\n    def copy(self: T) -> T: ...\n    def on_pair(self: B[T, S]) -> Tuple[T, S]: ...\n\nb1: B[int]\nreveal_type(b1.on_pair())  # E: Invalid self argument \"B[int]\" to attribute function \"on_pair\" with type \"Callable[[B[T, S]], Tuple[T, S]]\" \\\n                           # N: Revealed type is \"Tuple[Never, Never]\"\nb2: B[int, str]\nreveal_type(b2.on_pair())  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\nb3: B[int, str, int]\nreveal_type(b3.on_pair())  # E: Invalid self argument \"B[int, str, int]\" to attribute function \"on_pair\" with type \"Callable[[B[T, S]], Tuple[T, S]]\" \\\n                           # N: Revealed type is \"Tuple[Never, Never]\"\n\nclass C(B[T, S]): ...\nc: C[int, str]\nreveal_type(c.copy())  # N: Revealed type is \"__main__.C[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicClassNewStyleSelf]\nfrom typing import Generic, TypeVar, Self\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass B(Generic[Unpack[Ts]]):\n    next: Self\n    def copy(self) -> Self:\n        return self.next\n\nb: B[int, str, int]\nreveal_type(b.next)  # N: Revealed type is \"__main__.B[builtins.int, builtins.str, builtins.int]\"\nreveal_type(b.copy())  # N: Revealed type is \"__main__.B[builtins.int, builtins.str, builtins.int]\"\nreveal_type(B.copy(b))  # N: Revealed type is \"__main__.B[builtins.int, builtins.str, builtins.int]\"\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass C(B[T, S]): ...\nc: C[int, str]\n\nreveal_type(c.next)  # N: Revealed type is \"__main__.C[builtins.int, builtins.str]\"\nreveal_type(c.copy())  # N: Revealed type is \"__main__.C[builtins.int, builtins.str]\"\nreveal_type(C.copy(c))  # N: Revealed type is \"__main__.C[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleDataclass]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\n\n@dataclass\nclass B(Generic[Unpack[Ts]]):\n    items: Tuple[Unpack[Ts]]\n\nreveal_type(B)  # N: Revealed type is \"def [Ts] (items: Tuple[Unpack[Ts`1]]) -> __main__.B[Unpack[Ts`1]]\"\nb = B((1, \"yes\"))\nreveal_type(b.items)  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n@dataclass\nclass C(B[T, S]):\n    first: T\n    second: S\n\nreveal_type(C)  # N: Revealed type is \"def [T, S] (items: Tuple[T`1, S`2], first: T`1, second: S`2) -> __main__.C[T`1, S`2]\"\nc = C((1, \"yes\"), 2, \"no\")\nreveal_type(c.items)  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\nreveal_type(c.first)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.second)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dataclasses.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testVariadicTupleInProtocol]\nfrom typing import Protocol, Tuple, List\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass P(Protocol[Unpack[Ts]]):\n    def items(self) -> Tuple[Unpack[Ts]]: ...\n\nclass PC(Protocol[Unpack[Ts]]):\n    def meth(self, *args: Unpack[Ts]) -> None: ...\n\ndef get_items(x: P[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...\ndef match(x: PC[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...\n\nclass Bad:\n    def items(self) -> List[int]: ...\n    def meth(self, *, named: int) -> None: ...\n\nclass Good:\n    def items(self) -> Tuple[int, str]: ...\n    def meth(self, __x: int, y: str) -> None: ...\n\ng: Good\nreveal_type(get_items(g))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\nreveal_type(match(g))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\nb: Bad\nget_items(b)  # E: Argument 1 to \"get_items\" has incompatible type \"Bad\"; expected \"P[Unpack[Tuple[Never, ...]]]\" \\\n              # N: Following member(s) of \"Bad\" have conflicts: \\\n              # N:     Expected: \\\n              # N:         def items(self) -> Tuple[Never, ...] \\\n              # N:     Got: \\\n              # N:         def items(self) -> List[int]\nmatch(b)  # E: Argument 1 to \"match\" has incompatible type \"Bad\"; expected \"PC[Unpack[Tuple[Never, ...]]]\" \\\n          # N: Following member(s) of \"Bad\" have conflicts: \\\n          # N:     Expected: \\\n          # N:         def meth(self, *args: Never) -> None \\\n          # N:     Got: \\\n          # N:         def meth(self, *, named: int) -> None\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleCollectionCheck]\nfrom typing import Tuple, Optional\nfrom typing_extensions import Unpack\n\nallowed: Tuple[int, Unpack[Tuple[int, ...]]]\n\nx: Optional[int]\nif x in allowed:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testJoinOfVariadicTupleCallablesNoCrash]\nfrom typing import Callable, Tuple\n\nf: Callable[[int, *Tuple[str, ...], int], None]\ng: Callable[[int, *Tuple[str, ...], int], None]\nreveal_type([f, g])  # N: Revealed type is \"builtins.list[def (builtins.int, *Unpack[Tuple[Unpack[builtins.tuple[builtins.str, ...]], builtins.int]])]\"\n\nh: Callable[[int, *Tuple[str, ...], str], None]\nreveal_type([f, h])  # N: Revealed type is \"builtins.list[def (builtins.int, *Unpack[Tuple[Unpack[builtins.tuple[builtins.str, ...]], Never]])]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleBothUnpacksSimple]\nfrom typing import Tuple\nfrom typing_extensions import Unpack, TypeVarTuple, TypedDict\n\nclass Keywords(TypedDict):\n    a: str\n    b: str\n\nInts = Tuple[int, ...]\n\ndef f(*args: Unpack[Ints], other: str = \"no\", **kwargs: Unpack[Keywords]) -> None: ...\nreveal_type(f)  # N: Revealed type is \"def (*args: builtins.int, other: builtins.str =, **kwargs: Unpack[TypedDict('__main__.Keywords', {'a': builtins.str, 'b': builtins.str})])\"\nf(1, 2, a=\"a\", b=\"b\")  # OK\nf(1, 2, 3)  # E: Missing named argument \"a\" for \"f\" \\\n            # E: Missing named argument \"b\" for \"f\"\n\nTs = TypeVarTuple(\"Ts\")\ndef g(*args: Unpack[Ts], other: str = \"no\", **kwargs: Unpack[Keywords]) -> None: ...\nreveal_type(g)  # N: Revealed type is \"def [Ts] (*args: Unpack[Ts`-1], other: builtins.str =, **kwargs: Unpack[TypedDict('__main__.Keywords', {'a': builtins.str, 'b': builtins.str})])\"\ng(1, 2, a=\"a\", b=\"b\")  # OK\ng(1, 2, 3)  # E: Missing named argument \"a\" for \"g\" \\\n            # E: Missing named argument \"b\" for \"g\"\n\ndef bad(\n    *args: Unpack[Keywords],  # E: \"Keywords\" cannot be unpacked (must be tuple or TypeVarTuple)\n    **kwargs: Unpack[Ints],  # E: Unpack item in ** argument must be a TypedDict\n) -> None: ...\nreveal_type(bad)  # N: Revealed type is \"def (*args: Any, **kwargs: Any)\"\n\ndef bad2(\n    one: int,\n    *args: Unpack[Keywords],  # E: \"Keywords\" cannot be unpacked (must be tuple or TypeVarTuple)\n    other: str = \"no\",\n     **kwargs: Unpack[Ints],  # E: Unpack item in ** argument must be a TypedDict\n) -> None: ...\nreveal_type(bad2)  # N: Revealed type is \"def (one: builtins.int, *args: Any, other: builtins.str =, **kwargs: Any)\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleBothUnpacksCallable]\nfrom typing import Callable, Tuple\nfrom typing_extensions import Unpack, TypedDict\n\nclass Keywords(TypedDict):\n    a: str\n    b: str\nInts = Tuple[int, ...]\n\ncb: Callable[[Unpack[Ints], Unpack[Keywords]], None]\nreveal_type(cb)  # N: Revealed type is \"def (*builtins.int, **Unpack[TypedDict('__main__.Keywords', {'a': builtins.str, 'b': builtins.str})])\"\n\ncb2: Callable[[int, Unpack[Ints], int, Unpack[Keywords]], None]\nreveal_type(cb2)  # N: Revealed type is \"def (builtins.int, *Unpack[Tuple[Unpack[builtins.tuple[builtins.int, ...]], builtins.int]], **Unpack[TypedDict('__main__.Keywords', {'a': builtins.str, 'b': builtins.str})])\"\ncb2(1, 2, 3, a=\"a\", b=\"b\")\ncb2(1, a=\"a\", b=\"b\")  # E: Too few arguments\ncb2(1, 2, 3, a=\"a\")  # E: Missing named argument \"b\"\n\nbad1: Callable[[Unpack[Ints], Unpack[Ints]], None]  # E: More than one Unpack in a type is not allowed\nreveal_type(bad1)  # N: Revealed type is \"def (*builtins.int)\"\nbad2: Callable[[Unpack[Keywords], Unpack[Keywords]], None]  # E: \"Keywords\" cannot be unpacked (must be tuple or TypeVarTuple)\nreveal_type(bad2)  # N: Revealed type is \"def (*Any, **Unpack[TypedDict('__main__.Keywords', {'a': builtins.str, 'b': builtins.str})])\"\nbad3: Callable[[Unpack[Keywords], Unpack[Ints]], None]  # E: \"Keywords\" cannot be unpacked (must be tuple or TypeVarTuple) \\\n                                                        # E: More than one Unpack in a type is not allowed\nreveal_type(bad3)  # N: Revealed type is \"def (*Any)\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleBothUnpacksApplication]\nfrom typing import Callable, TypeVar, Optional\nfrom typing_extensions import Unpack, TypeVarTuple, TypedDict\n\nclass Keywords(TypedDict):\n    a: str\n    b: str\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\ndef test(\n    x: int,\n    func: Callable[[Unpack[Ts]], T],\n    *args: Unpack[Ts],\n    other: Optional[str] = None,\n    **kwargs: Unpack[Keywords],\n) -> T:\n    if bool():\n        func(*args, **kwargs)  # E: Extra argument \"a\" from **args\n    return func(*args)\ndef test2(\n    x: int,\n    func: Callable[[Unpack[Ts], Unpack[Keywords]], T],\n    *args: Unpack[Ts],\n    other: Optional[str] = None,\n    **kwargs: Unpack[Keywords],\n) -> T:\n    if bool():\n        func(*args)  # E: Missing named argument \"a\" \\\n                     # E: Missing named argument \"b\"\n    return func(*args, **kwargs)\n[builtins fixtures/tuple.pyi]\n\n[case testUnpackTupleSpecialCaseNoCrash]\nfrom typing import Tuple, TypeVar\nfrom typing_extensions import Unpack\n\nT = TypeVar(\"T\")\n\ndef foo(*x: object) -> None: ...\ndef bar(*x: int) -> None: ...\ndef baz(*x: T) -> T: ...\n\nkeys: Tuple[Unpack[Tuple[int, ...]]]\n\nfoo(keys, 1)\nfoo(*keys, 1)\n\nbar(keys, 1)  # E: Argument 1 to \"bar\" has incompatible type \"Tuple[Unpack[Tuple[int, ...]]]\"; expected \"int\"\nbar(*keys, 1)  # OK\n\nreveal_type(baz(keys, 1))  # N: Revealed type is \"builtins.object\"\nreveal_type(baz(*keys, 1))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicTupleContextNoCrash]\nfrom typing import Tuple, Unpack\n\nx: Tuple[int, Unpack[Tuple[int, ...]]] = ()  # E: Incompatible types in assignment (expression has type \"Tuple[()]\", variable has type \"Tuple[int, Unpack[Tuple[int, ...]]]\")\ny: Tuple[int, Unpack[Tuple[int, ...]]] = (1, 2)\nz: Tuple[int, Unpack[Tuple[int, ...]]] = (1,)\nw: Tuple[int, Unpack[Tuple[int, ...]]] = (1, *[2, 3, 4])\nt: Tuple[int, Unpack[Tuple[int, ...]]] = (1, *(2, 3, 4))\n[builtins fixtures/tuple.pyi]\n\n[case testAliasToCallableWithUnpack]\nfrom typing import Any, Callable, Tuple, Unpack\n\n_CallableValue = Callable[[Unpack[Tuple[Any, ...]]], Any]\ndef higher_order(f: _CallableValue) -> None: ...\n\ndef good1(*args: int) -> None: ...\ndef good2(*args: str) -> int: ...\n\ndef bad1(a: str, b: int, /) -> None: ...\ndef bad2(c: bytes, *args: int) -> str: ...\ndef bad3(*, d: str) -> int: ...\ndef bad4(**kwargs: None) -> None: ...\n\nhigher_order(good1)\nhigher_order(good2)\n\n#  https://github.com/python/mypy/issues/16567\n#  https://github.com/python/mypy/issues/16568\n# higher_order(bad1)  E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[str, int], None]\"; expected \"Callable[[VarArg(Any)], Any]\"\nhigher_order(bad2)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[bytes, VarArg(int)], str]\"; expected \"Callable[[VarArg(Any)], Any]\"\nhigher_order(bad3)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[NamedArg(str, 'd')], int]\"; expected \"Callable[[VarArg(Any)], Any]\"\nhigher_order(bad4)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[KwArg(None)], None]\"; expected \"Callable[[VarArg(Any)], Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAliasToCallableWithUnpack2]\nfrom typing import Any, Callable, Tuple, Unpack\n\n_CallableValue = Callable[[int, str, Unpack[Tuple[Any, ...]], int], Any]\ndef higher_order(f: _CallableValue) -> None: ...\n\ndef good(a: int, b: str, *args: Unpack[Tuple[Unpack[Tuple[Any, ...]], int]]) -> int: ...\ndef bad1(a: str, b: int, /) -> None: ...\ndef bad2(c: bytes, *args: int) -> str: ...\ndef bad3(*, d: str) -> int: ...\ndef bad4(**kwargs: None) -> None: ...\n\nhigher_order(good)\nhigher_order(bad1)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[str, int], None]\"; expected \"Callable[[int, str, VarArg(Unpack[Tuple[Unpack[Tuple[Any, ...]], int]])], Any]\"\nhigher_order(bad2)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[bytes, VarArg(int)], str]\"; expected \"Callable[[int, str, VarArg(Unpack[Tuple[Unpack[Tuple[Any, ...]], int]])], Any]\"\nhigher_order(bad3)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[NamedArg(str, 'd')], int]\"; expected \"Callable[[int, str, VarArg(Unpack[Tuple[Unpack[Tuple[Any, ...]], int]])], Any]\"\nhigher_order(bad4)  # E: Argument 1 to \"higher_order\" has incompatible type \"Callable[[KwArg(None)], None]\"; expected \"Callable[[int, str, VarArg(Unpack[Tuple[Unpack[Tuple[Any, ...]], int]])], Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAliasToCallableWithUnpackInvalid]\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\nAlias = Callable[[Unpack[T]], int]  # E: \"T\" cannot be unpacked (must be tuple or TypeVarTuple)\nx: Alias[int]\nreveal_type(x)  # N: Revealed type is \"def (*Any) -> builtins.int\"\nx = good\nx = bad  # E: Incompatible types in assignment (expression has type \"Callable[[VarArg(int), NamedArg(int, 'y')], int]\", variable has type \"Callable[[VarArg(Any)], int]\")\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleInvariant]\nfrom typing import Generic, Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\nTs = TypeVarTuple(\"Ts\")\n\nclass Array(Generic[Unpack[Ts]]): ...\n\ndef pointwise_multiply(x: Array[Unpack[Ts]], y: Array[Unpack[Ts]]) -> Array[Unpack[Ts]]: ...\n\ndef a1(x: Array[int], y: Array[str], z: Array[int, str]) -> None:\n    reveal_type(pointwise_multiply(x, x))  # N: Revealed type is \"__main__.Array[builtins.int]\"\n    reveal_type(pointwise_multiply(x, y))  # E: Cannot infer type argument 1 of \"pointwise_multiply\" \\\n                                           # N: Revealed type is \"__main__.Array[Unpack[builtins.tuple[Any, ...]]]\"\n    reveal_type(pointwise_multiply(x, z))  # E: Cannot infer type argument 1 of \"pointwise_multiply\" \\\n                                           # N: Revealed type is \"__main__.Array[Unpack[builtins.tuple[Any, ...]]]\"\n\ndef func(x: Array[Unpack[Ts]], *args: Unpack[Ts]) -> Tuple[Unpack[Ts]]:\n    ...\n\ndef a2(x: Array[int, str]) -> None:\n    reveal_type(func(x, 2, \"Hello\"))  # N: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n    reveal_type(func(x, 2))           # E: Cannot infer type argument 1 of \"func\" \\\n                                      # N: Revealed type is \"builtins.tuple[Any, ...]\"\n    reveal_type(func(x, 2, \"Hello\", True))   # E: Cannot infer type argument 1 of \"func\" \\\n                                             # N: Revealed type is \"builtins.tuple[Any, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleTypeApplicationOverload]\nfrom typing import Generic, TypeVar, TypeVarTuple, Unpack, overload, Callable\n\nT = TypeVar(\"T\")\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\nTs = TypeVarTuple(\"Ts\")\n\nclass C(Generic[T, Unpack[Ts]]):\n    @overload\n    def __init__(self, f: Callable[[Unpack[Ts]], T]) -> None: ...\n    @overload\n    def __init__(self, f: Callable[[T1, T2, T3, Unpack[Ts]], T], a: T1, b: T2, c: T3) -> None: ...\n    def __init__(self, f, *args, **kwargs) -> None:\n        ...\n\nreveal_type(C[int, str])  # N: Revealed type is \"Overload(def (f: def (builtins.str) -> builtins.int) -> __main__.C[builtins.int, builtins.str], def [T1, T2, T3] (f: def (T1`-1, T2`-2, T3`-3, builtins.str) -> builtins.int, a: T1`-1, b: T2`-2, c: T3`-3) -> __main__.C[builtins.int, builtins.str])\"\nAlias = C[int, str]\n\ndef f(x: int, y: int, z: int, t: int) -> str: ...\nx = C(f, 0, 0, \"hm\")  # E: Argument 1 to \"C\" has incompatible type \"Callable[[int, int, int, int], str]\"; expected \"Callable[[int, int, str, int], str]\"\nreveal_type(x)  # N: Revealed type is \"__main__.C[builtins.str, builtins.int]\"\nreveal_type(C(f))  # N: Revealed type is \"__main__.C[builtins.str, builtins.int, builtins.int, builtins.int, builtins.int]\"\nC[()]  # E: At least 1 type argument(s) expected, none given\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleAgainstParamSpecActualSuccess]\nfrom typing import Generic, TypeVar, TypeVarTuple, Unpack, Callable, Tuple, List\nfrom typing_extensions import ParamSpec\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\n\nclass CM(Generic[R]): ...\ndef cm(fn: Callable[P, R]) -> Callable[P, CM[R]]: ...\n\nTs = TypeVarTuple(\"Ts\")\n@cm\ndef test(*args: Unpack[Ts]) -> Tuple[Unpack[Ts]]: ...\n\nreveal_type(test)  # N: Revealed type is \"def [Ts] (*args: Unpack[Ts`-1]) -> __main__.CM[Tuple[Unpack[Ts`-1]]]\"\nreveal_type(test(1, 2, 3))  # N: Revealed type is \"__main__.CM[Tuple[Literal[1]?, Literal[2]?, Literal[3]?]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleAgainstParamSpecActualFailedNoCrash]\nfrom typing import Generic, TypeVar, TypeVarTuple, Unpack, Callable, Tuple, List\nfrom typing_extensions import ParamSpec\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\n\nclass CM(Generic[R]): ...\ndef cm(fn: Callable[P, List[R]]) -> Callable[P, CM[R]]: ...\n\nTs = TypeVarTuple(\"Ts\")\n@cm  # E: Argument 1 to \"cm\" has incompatible type \"Callable[[VarArg(Unpack[Ts])], Tuple[Unpack[Ts]]]\"; expected \"Callable[[VarArg(Never)], List[Never]]\"\ndef test(*args: Unpack[Ts]) -> Tuple[Unpack[Ts]]: ...\n\nreveal_type(test)  # N: Revealed type is \"def (*args: Never) -> __main__.CM[Never]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleAgainstParamSpecActualPrefix]\nfrom typing import Generic, TypeVar, TypeVarTuple, Unpack, Callable, Tuple, List\nfrom typing_extensions import ParamSpec, Concatenate\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\nclass CM(Generic[R]): ...\ndef cm(fn: Callable[Concatenate[T, P], R]) -> Callable[Concatenate[List[T], P], CM[R]]: ...\n\nTs = TypeVarTuple(\"Ts\")\n@cm\ndef test(x: T, *args: Unpack[Ts]) -> Tuple[T, Unpack[Ts]]: ...\n\nreveal_type(test)  # N: Revealed type is \"def [T, Ts] (builtins.list[T`2], *args: Unpack[Ts`-2]) -> __main__.CM[Tuple[T`2, Unpack[Ts`-2]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMixingTypeVarTupleAndParamSpec]\nfrom typing import Generic, ParamSpec, TypeVarTuple, Unpack, Callable, TypeVar\n\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nclass A(Generic[P, Unpack[Ts]]): ...\nclass B(Generic[Unpack[Ts], P]): ...\n\na: A[[int, str], int, str]\nreveal_type(a)  # N: Revealed type is \"__main__.A[[builtins.int, builtins.str], builtins.int, builtins.str]\"\nb: B[int, str, [int, str]]\nreveal_type(b)  # N: Revealed type is \"__main__.B[builtins.int, builtins.str, [builtins.int, builtins.str]]\"\n\nx: A[int, str, [int, str]]  # E: Can only replace ParamSpec with a parameter types list or another ParamSpec, got \"int\"\nreveal_type(x)  # N: Revealed type is \"__main__.A[Any, Unpack[builtins.tuple[Any, ...]]]\"\ny: B[[int, str], int, str]  # E: Can only replace ParamSpec with a parameter types list or another ParamSpec, got \"str\"\nreveal_type(y)  # N: Revealed type is \"__main__.B[Unpack[builtins.tuple[Any, ...]], Any]\"\n\nR = TypeVar(\"R\")\nclass C(Generic[P, R]):\n    fn: Callable[P, None]\n\nc: C[int, str]  # E: Can only replace ParamSpec with a parameter types list or another ParamSpec, got \"int\"\nreveal_type(c.fn)  # N: Revealed type is \"def (*Any, **Any)\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typevar-unbound.test",
    "content": "[case testUnboundTypeVar]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef f() -> T: # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n    ...\nf()\n\nU = TypeVar('U', bound=int)\n\ndef g() -> U: # E: A function returning TypeVar should receive at least one argument containing the same TypeVar \\\n              # N: Consider using the upper bound \"int\" instead\n    ...\n\nV = TypeVar('V', int, str)\n\ndef h() -> V:  # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n    ...\n\n[case testInnerFunctionTypeVar]\n\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef g(a: T) -> T:\n    def f() -> T:\n        ...\n    return f()\n\n[case testUnboundIterableOfTypeVars]\nfrom typing import Iterable, TypeVar\n\nT = TypeVar('T')\n\ndef f() -> Iterable[T]:\n    ...\nf()\n\n[case testBoundTypeVar]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef f(a: T, b: T, c: int) -> T:\n    ...\n\n[case testNestedBoundTypeVar]\nfrom typing import Callable, List, Union, Tuple, TypeVar\n\nT = TypeVar('T')\n\ndef f(a: Union[int, T], b: str) -> T:\n    ...\n\ndef g(a: Callable[..., T], b: str) -> T:\n    ...\n\ndef h(a: List[Union[Callable[..., T]]]) -> T:\n    ...\n\ndef j(a: List[Union[Callable[..., Tuple[T, T]], int]]) -> T:\n    ...\n[builtins fixtures/tuple.pyi]\n\n[case testUnboundedTypevarUnpacking]\nfrom typing import TypeVar\nT = TypeVar(\"T\")\ndef f(t: T) -> None:\n    a, *b = t  # E: \"object\" object is not iterable\n\n[case testTypeVarType]\nfrom typing import Mapping, Type, TypeVar, Union\nT = TypeVar(\"T\")\n\nclass A: ...\nclass B: ...\n\nlookup_table: Mapping[str, Type[Union[A,B]]]\ndef load(lookup_table: Mapping[str, Type[T]], lookup_key: str) -> T:\n    ...\nreveal_type(load(lookup_table, \"a\"))  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n\nlookup_table_a: Mapping[str, Type[A]]\ndef load2(lookup_table: Mapping[str, Type[Union[T, int]]], lookup_key: str) -> T:\n    ...\nreveal_type(load2(lookup_table_a, \"a\"))  # N: Revealed type is \"__main__.A\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTypeAssignment]\n# Adapted from https://github.com/python/mypy/issues/12115\nfrom typing import TypeVar, Type, Callable, Union, Any\n\nt1: Type[bool] = bool\nt2: Union[Type[bool], Type[str]]\n\nT1 = TypeVar(\"T1\", bound=Union[bool, str])\ndef foo1(t: Type[T1]) -> None: ...\nfoo1(t1)\nfoo1(t2)\n\nT2 = TypeVar(\"T2\", bool, str)\ndef foo2(t: Type[T2]) -> None: ...\nfoo2(t1)\n# Rejected correctly: T2 cannot be Union[bool, str]\nfoo2(t2)  # E: Value of type variable \"T2\" of \"foo2\" cannot be \"Union[bool, str]\" \\\n          # N: \"T2\" of \"foo2\" is a constrained type variable, it is not generic\n\nT3 = TypeVar(\"T3\")\ndef foo3(t: Type[T3]) -> None: ...\nfoo3(t1)\nfoo3(t2)\n\ndef foo4(t: Type[Union[bool, str]]) -> None: ...\nfoo4(t1)\nfoo4(t2)\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-typevar-values.test",
    "content": "-- Test cases for type variables with values restriction.\n\n\n[case testCallGenericFunctionWithTypeVarValueRestriction]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> None: pass\nf(1)\nf('x')\nf(object()) # E: Value of type variable \"T\" of \"f\" cannot be \"object\" \\\n            # N: \"T\" of \"f\" is a constrained type variable, it is not generic\n\n[case testCallGenericFunctionWithTypeVarValueRestrictionUsingContext]\nfrom typing import TypeVar, List\nT = TypeVar('T', int, str)\ndef f(x: T) -> List[T]: pass\ni = [1]\ns = ['x']\no = [object()]\nif int():\n    i = f(1)\n    s = f('')\n    o = f(1) \\\n      # E: Incompatible types in assignment (expression has type \"List[int]\", variable has type \"List[object]\") \\\n      # N: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance \\\n      # N: Consider using \"Sequence\" instead, which is covariant\n[builtins fixtures/list.pyi]\n\n[case testCallGenericFunctionWithTypeVarValueRestrictionAndAnyArgs]\nfrom typing import TypeVar, Any, cast\nT = TypeVar('T', int, str)\ndef f(x: T) -> None: pass\nf(cast(Any, object()))\n[out]\n\n[case testCallGenericFunctionWithTypeVarValueRestrictionInDynamicFunc]\nfrom typing import TypeVar, Any\nT = TypeVar('T', int, str)\ndef f(x: T) -> None: pass\ndef g():\n    f(object())\n[out]\n\n[case testCallGenericFunctionWithTypeVarValueRestrictionUsingSubtype]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> None: pass\nclass S(str): pass\nf(S())\n[out]\n\n[case testCheckGenericFunctionBodyWithTypeVarValues]\nfrom typing import TypeVar\nclass A:\n    def f(self, x: int) -> A: return self\nclass B:\n    def f(self, x: int) -> B: return self\nAB = TypeVar('AB', A, B)\ndef f(x: AB) -> AB:\n    x = x.f(1)\n    return x.f(1)\n\n[case testCheckGenericFunctionBodyWithTypeVarValues2]\nfrom typing import TypeVar\nclass A:\n    def f(self) -> A: return A()\n    def g(self) -> B: return B()\nclass B:\n    def f(self) -> A: return A()\n    def g(self) -> B: return B()\nAB = TypeVar('AB', A, B)\ndef f(x: AB) -> AB:\n    return x.f() # Error\ndef g(x: AB) -> AB:\n    return x.g() # Error\n[out]\nmain:10: error: Incompatible return value type (got \"A\", expected \"B\")\nmain:12: error: Incompatible return value type (got \"B\", expected \"A\")\n\n[case testTypeInferenceAndTypeVarValues]\nfrom typing import TypeVar\nclass A:\n    def f(self) -> A: return self\n    def g(self) -> B: return B()\nclass B:\n    def f(self) -> B: return self\n    def g(self) -> B: return B()\nAB = TypeVar('AB', A, B)\ndef f(x: AB) -> AB:\n    y = x\n    if y:\n        return y.f()\n    else:\n        return y.g() # E: Incompatible return value type (got \"B\", expected \"A\")\n[out]\n\n[case testTypeDeclaredBasedOnTypeVarWithValues]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T:\n    a: T\n    b: T\n    if 1:\n        a = x\n        b = x\n        a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        b = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        return x\n[out]\n\n[case testIsinstanceAndTypeVarValues]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T:\n    if isinstance(x, int):\n        return 2\n    return x\ndef g(x: T) -> T:\n    if isinstance(x, str):\n        return ''\n    return x\ndef h(x: T) -> T:\n    if isinstance(x, int):\n        return '' # E: Incompatible return value type (got \"str\", expected \"int\")\n    return x\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceAndTypeVarValues2]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T:\n    if isinstance(x, int):\n        return 2\n    else:\n        return ''\ndef g(x: T) -> T:\n    if isinstance(x, int):\n        return '' # E: Incompatible return value type (got \"str\", expected \"int\")\n    else:\n        return 2  # E: Incompatible return value type (got \"int\", expected \"str\")\n    return x\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceAndTypeVarValues3]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T:\n    if isinstance(x, int):\n        y = 1\n    else:\n        y = ''\n    return y\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndTypeVarValues4]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T:\n    if isinstance(x, int):\n        y = 1\n    else:\n        y = object()\n    return y # E: Incompatible return value type (got \"object\", expected \"str\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceAndTypeVarValues5]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T:\n    if isinstance(x, int):\n        y = object()\n    else:\n        y = ''\n    return y # E: Incompatible return value type (got \"object\", expected \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceWithUserDefinedTypeAndTypeVarValues]\n# flags: --warn-unreachable\nfrom typing import TypeVar\nclass A: pass\nclass B: pass\nT1 = TypeVar('T1', A, B)\ndef f1(x: T1) -> None:\n    y = x\n    if isinstance(x, A):\n        x = y\n        x = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    else:\n        x = B()\n        x = y\n        x.foo() # E: \"B\" has no attribute \"foo\"\n\nclass C:\n    field: int\nclass D:\n    field: str\nT2 = TypeVar('T2', C, D)\ndef f2(x: T2) -> None:\n    y = x\n    if isinstance(x, C):\n        # C and D are non-overlapping, so this branch is never checked\n        x = y\n        x = C()\n    else:\n        x = D()\n        x = y\n        x.foo() # E: \"D\" has no attribute \"foo\"\n\nS = TypeVar('S', int, str)\ndef g(x: S) -> None:\n    y = x\n    if isinstance(x, int):\n        x = y\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testIsinstanceWithUserDefinedTypeAndTypeVarValues2]\nfrom typing import TypeVar\nclass S(str): pass\nT = TypeVar('T', S, int)\ndef f(x: T) -> None:\n    y = x\n    if isinstance(x, S):\n        # This is checked only when type of x is str.\n        x = y\n        x = S()\n        x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"S\")\n    else:\n        x = y\n        x = 1\n        x = S() # E: Incompatible types in assignment (expression has type \"S\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testTypeVarValuesAndNestedCalls]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(m: T) -> int: pass\ndef h(x: int) -> int: pass\ndef g(a: T) -> None:\n    h(f(a))\n[out]\n\n[case testGenericTypeWithTypevarValues]\nfrom typing import TypeVar, Generic, Any\nX = TypeVar('X', int, str)\nclass A(Generic[X]): pass\na: A[int]\nb: A[str]\nd: A[object]  # E: Value of type variable \"X\" of \"A\" cannot be \"object\" \\\n              # N: \"X\" of \"A\" is a constrained type variable, it is not generic\nc: A[Any]\n\n[case testConstructGenericTypeWithTypevarValuesAndTypeInference]\nfrom typing import TypeVar, Generic, Any, cast\nX = TypeVar('X', int, str)\nclass A(Generic[X]):\n    def __init__(self, x: X) -> None: pass\nA(1)\nA('x')\nA(cast(Any, object()))\nA(object()) # E: Value of type variable \"X\" of \"A\" cannot be \"object\" \\\n            # N: \"X\" of \"A\" is a constrained type variable, it is not generic\n\n[case testGenericTypeWithTypevarValuesAndTypevarArgument]\nfrom typing import TypeVar, Generic\nclass C: pass\nX = TypeVar('X', int, str)\nY = TypeVar('Y', int, C)\nZ = TypeVar('Z')\nclass D(Generic[X]):\n    def __init__(self, x: X) -> None: pass\ndef f(x: X) -> None:\n    a: D[X]\ndef g(x: Y) -> None:\n    a: D[Y]\ndef h(x: Z) -> None:\n    a: D[Z]\n[out]\nmain:11: error: Invalid type argument value for \"D\"\nmain:11: note: \"X\" of \"D\" is a constrained type variable, it is not generic\nmain:13: error: Type variable \"Z\" not valid as type argument value for \"D\"\n\n[case testGenericTypeWithTypevarValuesAndSubtypePromotion]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass S(str): pass\nclass C(Generic[X]):\n    def __init__(self, x: X) -> None: pass\nx: C[str]\ny = C(S())\nif int():\n    x = y\n    y = x\nc_int = C(1) # type: C[int]\nif int():\n    y = c_int # E: Incompatible types in assignment (expression has type \"C[int]\", variable has type \"C[str]\")\n\n[case testGenericTypeBodyWithTypevarValues]\nfrom typing import TypeVar, Generic\nclass A:\n    def f(self, x: int) -> None: pass\n    def g(self, x: int) -> None: pass\n    def h(self, x: str) -> None: pass\nclass B:\n    def f(self, x: int) -> None: pass\n    def g(self, x: str) -> None: pass\n    def h(self, x: int) -> None: pass\nX = TypeVar('X', A, B)\nclass C(Generic[X]):\n    def f(self, x: X) -> None:\n        x.f(1)\n        x.g(1) # E: Argument 1 to \"g\" of \"B\" has incompatible type \"int\"; expected \"str\"\n        x.h(1) # E: Argument 1 to \"h\" of \"A\" has incompatible type \"int\"; expected \"str\"\n[out]\n\n[case testAttributeInGenericTypeWithTypevarValues1]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    x = None  # type: X\n    def f(self, x: X) -> None:\n        self.x = x\n        self.x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[out]\n\n[case testAttributeInGenericTypeWithTypevarValues2]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    x = None  # type: X\ncn = C() # type: C[int]\ncn.x = 1\ncn.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ncs = C() # type: C[str]\ncs.x = ''\ncs.x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAttributeInGenericTypeWithTypevarValues3]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    def f(self, x: X) -> None:\n        self.x = x  # type: X\nci: C[int]\ncs: C[str]\nreveal_type(ci.x) # N: Revealed type is \"builtins.int\"\nreveal_type(cs.x) # N: Revealed type is \"builtins.str\"\n\n[case testAttributeInGenericTypeWithTypevarValuesUsingInference1]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    def f(self, x: X) -> None:\n        self.x = x # E: Need type annotation for \"x\"\nci: C[int]\ncs: C[str]\nreveal_type(ci.x) # N: Revealed type is \"Any\"\nreveal_type(cs.x) # N: Revealed type is \"Any\"\n\n[case testAttributeInGenericTypeWithTypevarValuesUsingInference2]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    def f(self, x: X) -> None:\n        self.x = 1\n        reveal_type(self.x) # N: Revealed type is \"builtins.int\"\nci: C[int]\ncs: C[str]\nreveal_type(ci.x) # N: Revealed type is \"builtins.int\"\nreveal_type(cs.x) # N: Revealed type is \"builtins.int\"\n\n[case testAttributeInGenericTypeWithTypevarValuesUsingInference3]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    x: X\n    def f(self) -> None:\n        self.y = self.x # E: Need type annotation for \"y\"\nci: C[int]\ncs: C[str]\nreveal_type(ci.y) # N: Revealed type is \"Any\"\nreveal_type(cs.y) # N: Revealed type is \"Any\"\n\n[case testInferredAttributeInGenericClassBodyWithTypevarValues]\nfrom typing import TypeVar, Generic\nX = TypeVar('X', int, str)\nclass C(Generic[X]):\n    x = 1\nC.x = 1\nC.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testMultipleClassTypevarsWithValues1]\nfrom typing import TypeVar, Generic\nclass A:\n    def f(self, x: int) -> None: pass\nclass B:\n    def f(self, x: str) -> None: pass\nX = TypeVar('X', A, B)\nY = TypeVar('Y', int, str)\nclass C(Generic[X, Y]):\n    def f(self, x: X, y: Y) -> None:\n        x.f(y)\n[out]\nmain:10: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nmain:10: error: Argument 1 to \"f\" of \"B\" has incompatible type \"int\"; expected \"str\"\n\n[case testMultipleClassTypevarsWithValues2]\nfrom typing import TypeVar, Generic\nclass A: pass\nclass B: pass\nX = TypeVar('X', A, B)\nY = TypeVar('Y', int, str)\nclass C(Generic[X, Y]): pass\na: C[A, int]\nb: C[B, str]\nc: C[int, int]  # E: Value of type variable \"X\" of \"C\" cannot be \"int\" \\\n                # N: \"X\" of \"C\" is a constrained type variable, it is not generic\nd: C[A, A]      # E: Value of type variable \"Y\" of \"C\" cannot be \"A\" \\\n                # N: \"Y\" of \"C\" is a constrained type variable, it is not generic\n\n[case testCallGenericFunctionUsingMultipleTypevarsWithValues]\nfrom typing import TypeVar\nclass A: pass\nclass B: pass\nX = TypeVar('X', A, B)\nY = TypeVar('Y', int, str)\ndef f(x: X, y: Y) -> None: pass\nf(A(), '')\nf(B(), 1)\nf(A(), A())  # E: Value of type variable \"Y\" of \"f\" cannot be \"A\" \\\n             # N: \"Y\" of \"f\" is a constrained type variable, it is not generic\nf(1, 1)  # E: Value of type variable \"X\" of \"f\" cannot be \"int\" \\\n         # N: \"X\" of \"f\" is a constrained type variable, it is not generic\n\n[case testGenericFunctionWithNormalAndRestrictedTypevar]\nfrom typing import TypeVar, Generic\nX = TypeVar('X')\nY = TypeVar('Y', int, str)\nclass C(Generic[Y]):\n    def __init__(self, y: Y) -> None: pass\ndef f(x: X, y: Y, z: int) -> None:\n    C(y)\n    C(x)  # Error\n    if int():\n        z = x # Error\n        z = y # Error\n    y.foo # Error\n[out]\nmain:8: error: Value of type variable \"Y\" of \"C\" cannot be \"X\"\nmain:8: note: \"Y\" of \"C\" is a constrained type variable, it is not generic\nmain:10: error: Incompatible types in assignment (expression has type \"X\", variable has type \"int\")\nmain:11: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:12: error: \"int\" has no attribute \"foo\"\nmain:12: error: \"str\" has no attribute \"foo\"\n\n[case testTypeVarWithValueInferredFromObjectReturnTypeContext]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef c1(x: object) -> None: pass\ndef c2(x: int) -> None: pass\ndef c3(x: str) -> None: pass\ndef g(x: T) -> T: pass\nc1(g(''))\nc2(g(1))\nc3(g(''))\nc2(g(''))  # E: Argument 1 to \"c2\" has incompatible type \"str\"; expected \"int\"\nc3(g(1))   # E: Argument 1 to \"c3\" has incompatible type \"int\"; expected \"str\"\n\n[case testTypeVarWithValueInferredFromObjectReturnTypeContext2]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\nclass ss(str): pass\ndef c(x: ss) -> None: pass\ndef g(x: T) -> T: pass\nc(g(''))\nc(g(1))\n[out]\nmain:6: error: Argument 1 to \"c\" has incompatible type \"str\"; expected \"ss\"\nmain:7: error: Argument 1 to \"c\" has incompatible type \"int\"; expected \"ss\"\n\n[case testDefineAttributeInGenericMethodUsingTypeVarWithValues]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\nclass A:\n    def f(self, x: T) -> None:\n        self.x = x # E: Need type annotation for \"x\"\n        self.y = [x] # E: Need type annotation for \"y\"\n        self.z = 1\nreveal_type(A().x)  # N: Revealed type is \"Any\"\nreveal_type(A().y)  # N: Revealed type is \"Any\"\nreveal_type(A().z)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n\n-- Special cases\n-- -------------\n\n\n[case testTypevarValuesSpecialCase1]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T', int, str)\nclass A(Generic[T]):\n    @abstractmethod\n    def f(self) -> 'A[T]': pass\nclass B(A[str]):\n    @abstractmethod\n    def f(self) -> 'B': pass\nclass C(A[str]):\n    @abstractmethod\n    def f(self) -> int: # E: Return type \"int\" of \"f\" incompatible with return type \"A[str]\" in supertype \"A\"\n        pass\n[out]\n\n[case testDefaultArgumentValueInGenericClassWithTypevarValues]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', int, str)\nclass C(Generic[T]):\n    def f(self, x: int = 2) -> None: pass\n\n[case testTypevarValuesWithOverloadedFunctionSpecialCase]\nfrom foo import *\n[file foo.pyi]\nfrom typing import TypeVar, overload, Callable\n\nT = TypeVar('T', int, str)\ndef f(x: T) -> None:\n     y = m(g, x)\n     if int():\n         x = y\n         y = object() # Error\n\nA = TypeVar('A')\nR = TypeVar('R')\ndef m(f: Callable[[A], R], it: A) -> A: pass\n\n@overload\ndef g(x: int) -> int: return x\n@overload\ndef g(x: str) -> str: return x\n[out]\ntmp/foo.pyi:8: error: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\ntmp/foo.pyi:8: error: Incompatible types in assignment (expression has type \"object\", variable has type \"str\")\n\n[case testGenericFunctionSubtypingWithTypevarValues]\nfrom typing import TypeVar\nclass A: pass\nT = TypeVar('T', int, str)\nU = TypeVar('U', str, A, int)\ndef f(x: T) -> T: pass\ndef g(x: U) -> U: pass\na = f\nif int():\n    a = f\nif int():\n    a = g\nb = g\nif int():\n    b = g\nif int():\n    b = f # E: Incompatible types in assignment (expression has type \"Callable[[T], T]\", variable has type \"Callable[[U], U]\")\n\n[case testInnerFunctionWithTypevarValues]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\nU = TypeVar('U', int, str)\ndef outer(x: T) -> T:\n    def inner(y: T) -> T:\n        return x\n    def inner2(y: U) -> U:\n        return y\n    inner(x)\n    inner(3) # E: Argument 1 to \"inner\" has incompatible type \"int\"; expected \"str\"\n    inner2(x)\n    inner2(3)\n    outer(3)\n    return x\n[out]\n\n[case testInnerFunctionMutualRecursionWithTypevarValues]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef outer(x: T) -> T:\n    def inner1(y: T) -> T:\n        return inner2(y)\n    def inner2(y: T) -> T:\n        return inner1('a') # E: Argument 1 to \"inner1\" has incompatible type \"str\"; expected \"int\"\n    return inner1(x)\n[out]\n\n[case testClassMemberTypeVarInFunctionBody]\nfrom typing import TypeVar, List\nS = TypeVar('S')\nclass C:\n    T = TypeVar('T', bound=int)\n    def f(self, x: T) -> T:\n        L = List[S]\n        y: L[C.T] = [x]\n        C.T  # E: Type variable \"C.T\" cannot be used as an expression\n        A = C.T  # E: Type variable \"C.T\" cannot be used as an expression\n        return y[0]\n\n[builtins fixtures/list.pyi]\n\n[case testTypeVarWithAnyTypeBound]\n# flags: --follow-imports=skip\nfrom typing import Type, TypeVar\nfrom a import A\nT = TypeVar('T', bound=A)\ndef method(t: Type[T]) -> None:\n    t.a\n[file a.py]\nclass A:\n    a: int = 7\n[out]\n\n[case testParameterLessGenericAsRestriction]\nfrom typing import Sequence, Iterable, TypeVar\nS = TypeVar('S', Sequence, Iterable)\ndef my_len(s: S) -> None: pass\ndef crash() -> None: my_len((0,))\n[builtins fixtures/tuple.pyi]\n\n[case testReferenceToDecoratedFunctionAndTypeVarValues]\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\nS = TypeVar('S', int, str)\n\ndef dec(f: Callable[..., T]) -> Callable[..., T]: ...\n\n@dec\ndef g(s: S) -> Callable[[S], None]: ...\n\ndef f(x: S) -> None:\n    h = g(x)\n    h(x)\n\n[case testTypeVarWithTypedDictBoundInIndexExpression]\nfrom typing import TypeVar\nfrom typing_extensions import TypedDict\n\nclass Data(TypedDict):\n    x: int\n\n\nT = TypeVar(\"T\", bound=Data)\n\n\ndef f(data: T) -> None:\n    reveal_type(data[\"x\"]) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarWithUnionTypedDictBoundInIndexExpression]\nfrom typing import TypeVar, Union, Dict\nfrom typing_extensions import TypedDict\n\nclass Data(TypedDict):\n    x: int\n\n\nT = TypeVar(\"T\", bound=Union[Data, Dict[str, str]])\n\n\ndef f(data: T) -> None:\n    reveal_type(data[\"x\"]) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n\n[case testTypeVarWithTypedDictValueInIndexExpression]\nfrom typing import TypeVar, Union, Dict\nfrom typing_extensions import TypedDict\n\nclass Data(TypedDict):\n    x: int\n\n\nT = TypeVar(\"T\", Data, Dict[str, str])\n\n\ndef f(data: T) -> None:\n    _: Union[str, int] = data[\"x\"]\n[builtins fixtures/dict.pyi]\n\n[case testSelfTypeVarIndexExpr]\nfrom typing import TypeVar, Union, Type\nfrom typing_extensions import TypedDict\n\nT = TypeVar(\"T\", bound=\"Indexable\")\n\nclass Indexable:\n    def __init__(self, index: str) -> None:\n        self.index = index\n\n    def __getitem__(self: T, index: str) -> T:\n        return self._new_instance(index)\n\n    @classmethod\n    def _new_instance(cls: Type[T], index: str) -> T:\n        return cls(\"foo\")\n\n    def m(self: T) -> T:\n        return self[\"foo\"]\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeVarWithValueDeferral]\nfrom typing import TypeVar, Callable\n\nT = TypeVar(\"T\", \"A\", \"B\")\nFunc = Callable[[], T]\n\nclass A: ...\nclass B: ...\n\n[case testTypeCommentInGenericTypeWithConstrainedTypeVar]\nfrom typing import Generic, TypeVar\n\nNT = TypeVar(\"NT\", int, float)\n\nclass Foo1(Generic[NT]):\n    p = 1  # type: int\n\nclass Foo2(Generic[NT]):\n    p, q = 1, 2.0  # type: (int, float)\n\nclass Foo3(Generic[NT]):\n    def bar(self) -> None:\n        p = 1  # type: int\n\nclass Foo4(Generic[NT]):\n    def bar(self) -> None:\n        p, q = 1, 2.0  # type: (int, float)\n\ndef foo3(x: NT) -> None:\n    p = 1  # type: int\n\ndef foo4(x: NT) -> None:\n    p, q = 1, 2.0  # type: (int, float)\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-underscores.test",
    "content": "[case testUnderscoresBasics]\nx: int\nx = 1000_000\nx = 0x_FF_FF_FF_FF\ny: str = 1000_000.000_001  # E: Incompatible types in assignment (expression has type \"float\", variable has type \"str\")\n"
  },
  {
    "path": "test-data/unit/check-union-error-syntax.test",
    "content": "[case testUnionErrorSyntax]\n# flags: --python-version 3.10 --no-force-union-syntax\nfrom typing import Union\nx : Union[bool, str]\nx = 3 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"bool | str\")\n\n[case testOrErrorSyntax]\n# flags: --python-version 3.10 --force-union-syntax\nfrom typing import Union\nx : Union[bool, str]\nx = 3 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Union[bool, str]\")\n\n[case testOrNoneErrorSyntax]\n# flags: --python-version 3.10 --no-force-union-syntax\nfrom typing import Union\nx : Union[bool, None]\nx = 3 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"bool | None\")\n\n[case testOptionalErrorSyntax]\n# flags: --python-version 3.10 --force-union-syntax\nfrom typing import Union\nx : Union[bool, None]\nx = 3 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Optional[bool]\")\n\n[case testNoneAsFinalItem]\n# flags: --python-version 3.10 --no-force-union-syntax\nfrom typing import Union\nx : Union[bool, None, str]\nx = 3 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"bool | str | None\")\n\n[case testLiteralOrErrorSyntax]\n# flags: --python-version 3.10 --no-force-union-syntax\nfrom typing import Union\nfrom typing_extensions import Literal\nx : Union[Literal[1], Literal[2], str]\nx = 3 # E: Incompatible types in assignment (expression has type \"Literal[3]\", variable has type \"Literal[1, 2] | str\")\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralUnionErrorSyntax]\n# flags: --python-version 3.10 --force-union-syntax\nfrom typing import Union\nfrom typing_extensions import Literal\nx : Union[Literal[1], Literal[2], str]\nx = 3 # E: Incompatible types in assignment (expression has type \"Literal[3]\", variable has type \"Union[str, Literal[1, 2]]\")\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralOrNoneErrorSyntax]\n# flags: --python-version 3.10 --no-force-union-syntax\nfrom typing import Union\nfrom typing_extensions import Literal\nx : Union[Literal[1], None]\nx = 3 # E: Incompatible types in assignment (expression has type \"Literal[3]\", variable has type \"Literal[1] | None\")\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralOptionalErrorSyntax]\n# flags: --python-version 3.10 --force-union-syntax\nfrom typing import Union\nfrom typing_extensions import Literal\nx : Union[Literal[1], None]\nx = 3 # E: Incompatible types in assignment (expression has type \"Literal[3]\", variable has type \"Optional[Literal[1]]\")\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-union-or-syntax.test",
    "content": "-- Type checking of union types with '|' syntax\n\n[case testUnionOrSyntaxWithTwoBuiltinsTypes]\n# flags: --python-version 3.10\nfrom __future__ import annotations\ndef f(x: int | str) -> int | str:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    z: int | str\n    reveal_type(z)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    return x\nreveal_type(f)  # N: Revealed type is \"def (x: Union[builtins.int, builtins.str]) -> Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOrSyntaxWithThreeBuiltinsTypes]\n# flags: --python-version 3.10\ndef f(x: int | str | float) -> int | str | float:\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.float]\"\n    z: int | str | float\n    reveal_type(z)  # N: Revealed type is \"Union[builtins.int, builtins.str, builtins.float]\"\n    return x\nreveal_type(f)  # N: Revealed type is \"def (x: Union[builtins.int, builtins.str, builtins.float]) -> Union[builtins.int, builtins.str, builtins.float]\"\n\n[case testUnionOrSyntaxWithTwoTypes]\n# flags: --python-version 3.10\nclass A: pass\nclass B: pass\ndef f(x: A | B) -> A | B:\n    reveal_type(x)  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n    z: A | B\n    reveal_type(z)  # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n    return x\nreveal_type(f)  # N: Revealed type is \"def (x: Union[__main__.A, __main__.B]) -> Union[__main__.A, __main__.B]\"\n\n[case testUnionOrSyntaxWithThreeTypes]\n# flags: --python-version 3.10\nclass A: pass\nclass B: pass\nclass C: pass\ndef f(x: A | B | C) -> A | B | C:\n    reveal_type(x)  # N: Revealed type is \"Union[__main__.A, __main__.B, __main__.C]\"\n    z: A | B | C\n    reveal_type(z)  # N: Revealed type is \"Union[__main__.A, __main__.B, __main__.C]\"\n    return x\nreveal_type(f)  # N: Revealed type is \"def (x: Union[__main__.A, __main__.B, __main__.C]) -> Union[__main__.A, __main__.B, __main__.C]\"\n\n[case testUnionOrSyntaxWithLiteral]\n# flags: --python-version 3.10\nfrom typing_extensions import Literal\nreveal_type(Literal[4] | str)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOrSyntaxWithBadOperator]\n# flags: --python-version 3.10\nx: 1 + 2  # E: Invalid type comment or annotation\n\n[case testUnionOrSyntaxWithBadOperands]\n# flags: --python-version 3.10\nx: int | 42  # E: Invalid type: try using Literal[42] instead?\ny: 42 | int  # E: Invalid type: try using Literal[42] instead?\nz: str | 42 | int  # E: Invalid type: try using Literal[42] instead?\n\n[case testUnionOrSyntaxWithGenerics]\n# flags: --python-version 3.10\nfrom typing import List\nx: List[int | str]\nreveal_type(x)  # N: Revealed type is \"builtins.list[Union[builtins.int, builtins.str]]\"\n[builtins fixtures/list.pyi]\n\n[case testUnionOrSyntaxWithQuotedFunctionTypesPre310]\n# flags: --python-version 3.9\nfrom typing import Union\ndef f(x: 'Union[int, str, None]') -> 'Union[int, None]':\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str, None]\"\n    return 42\nreveal_type(f)  # N: Revealed type is \"def (x: Union[builtins.int, builtins.str, None]) -> Union[builtins.int, None]\"\n\ndef g(x: \"int | str | None\") -> \"int | None\":\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str, None]\"\n    return 42\nreveal_type(g)  # N: Revealed type is \"def (x: Union[builtins.int, builtins.str, None]) -> Union[builtins.int, None]\"\n\n[case testUnionOrSyntaxWithQuotedVariableTypesPre310]\n# flags: --python-version 3.9\ny: \"int | str\"\nreveal_type(y)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\n[case testUnionOrSyntaxWithTypeAliasWorking]\n# flags: --python-version 3.10\nT = int | str\nx: T\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nS = list[int] | str | None\ny: S\nreveal_type(y)  # N: Revealed type is \"Union[builtins.list[builtins.int], builtins.str, None]\"\nU = str | None\nz: U\nreveal_type(z)  # N: Revealed type is \"Union[builtins.str, None]\"\n\ndef f(): pass\n\nX = int | str | f()\nb: X  # E: Variable \"__main__.X\" is not valid as a type \\\n    # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/type.pyi]\n\n[case testUnionOrSyntaxWithinRuntimeContextNotAllowed]\n# flags: --python-version 3.9\nfrom __future__ import annotations\nfrom typing import List\nT = int | str  # E: `X | Y` syntax for unions requires Python 3.10 or above \\\n               # E: Unsupported left operand type for | (\"Type[int]\")\nclass C(List[int | str]):  # E: `X | Y` syntax for unions requires Python 3.10 or above\n    pass\nC()\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOrSyntaxWithinRuntimeContextNotAllowed2]\n# flags: --python-version 3.9\nfrom __future__ import annotations\nfrom typing import cast\ncast(str | int, 'x')  # E: `X | Y` syntax for unions requires Python 3.10 or above\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testUnionOrSyntaxInComment]\nx = 1  # type: int | str\n\n[case testUnionOrSyntaxFutureImport]\nfrom __future__ import annotations\nx: int | None\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOrSyntaxMissingFutureImport]\n# flags: --python-version 3.9\nx: int | None  # E: `X | Y` syntax for unions requires Python 3.10 or above\n\n[case testUnionOrSyntaxInStubFile]\n# flags: --python-version 3.9\nfrom lib import x\n[file lib.pyi]\nx: int | None\n\n[case testUnionOrSyntaxInMiscRuntimeContexts]\n# flags: --python-version 3.10\nfrom typing import cast\n\nclass C(list[int | None]):\n    pass\n\ndef f() -> object: pass\n\nreveal_type(cast(str | None, f()))  # N: Revealed type is \"Union[builtins.str, None]\"\nreveal_type(list[str | None]())  # N: Revealed type is \"builtins.list[Union[builtins.str, None]]\"\n[builtins fixtures/type.pyi]\n\n[case testUnionOrSyntaxRuntimeContextInStubFile]\nimport lib\nreveal_type(lib.x)  # N: Revealed type is \"Union[builtins.int, builtins.list[builtins.str], None]\"\nreveal_type(lib.y)  # N: Revealed type is \"builtins.list[Union[builtins.int, None]]\"\n\n[file lib.pyi]\nA = int | list[str] | None\nx: A\nB = list[int | None]\ny: B\nclass C(list[int | None]):\n    pass\n[builtins fixtures/list.pyi]\n\n[case testUnionOrSyntaxInIsinstance]\n# flags: --python-version 3.10\nclass C: pass\n\ndef f(x: int | str | C) -> None:\n    if isinstance(x, int | str):\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.C\"\n\ndef g(x: int | str | tuple[int, str] | C) -> None:\n    if isinstance(x, int | str | tuple):\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str, Tuple[builtins.int, builtins.str]]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/isinstance_python3_10.pyi]\n\n[case testUnionOrSyntaxInIsinstanceNotSupported]\n# flags: --python-version 3.9\nfrom typing import Union\ndef f(x: Union[int, str, None]) -> None:\n    if isinstance(x, int | str):\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"None\"\n[builtins fixtures/isinstance.pyi]\n\n[case testImplicit604TypeAliasWithCyclicImportInStub]\n# flags: --python-version 3.10\nfrom was_builtins import foo\nreveal_type(foo)  # N: Revealed type is \"Union[builtins.str, was_mmap.mmap]\"\n[file was_builtins.pyi]\nimport was_mmap\nWriteableBuffer = was_mmap.mmap\nReadableBuffer = str | WriteableBuffer\nfoo: ReadableBuffer\n[file was_mmap.pyi]\nfrom was_builtins import *\nclass mmap: ...\n[builtins fixtures/type.pyi]\n\n[case testTypeAliasWithNewUnionIsInstance]\n# flags: --python-version 3.10\nSimpleAlias = int | str\n\ndef foo(x: int | str | tuple):\n    if isinstance(x, SimpleAlias):\n        reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n\nParameterizedAlias = str | list[str]\n\n# these are false negatives:\nisinstance(5, str | list[str])\nisinstance(5, ParameterizedAlias)\n[builtins fixtures/type.pyi]\n\n[case testIsInstanceUnionNone]\n# flags: --python-version 3.10\ndef foo(value: str | bool | None):\n    assert not isinstance(value, str | None)\n    reveal_type(value)  # N: Revealed type is \"builtins.bool\"\n\ndef bar(value: object):\n    assert isinstance(value, str | None)\n    reveal_type(value)  # N: Revealed type is \"Union[builtins.str, None]\"\n[builtins fixtures/type.pyi]\n\n\n# TODO: Get this test to pass\n[case testImplicit604TypeAliasWithCyclicImportNotInStub-xfail]\n# flags: --python-version 3.10\nfrom was_builtins import foo\nreveal_type(foo)  # N: Revealed type is \"Union[builtins.str, was_mmap.mmap]\"\n[file was_builtins.py]\nimport was_mmap\nWriteableBuffer = was_mmap.mmap\nReadableBuffer = str | WriteableBuffer\nfoo: ReadableBuffer\n[file was_mmap.py]\nfrom was_builtins import *\nclass mmap: ...\n"
  },
  {
    "path": "test-data/unit/check-unions.test",
    "content": "-- Type checking of union types\n\n[case testUnion1]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None:\n    if isinstance(x, int):\n        y = 1\n        y = x\n    elif isinstance(x, str):\n        z = 'a'\n        z = x\n[builtins fixtures/isinstance.pyi]\n\n[case testUnion2]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None:\n    if isinstance(x, int):\n        y = 1\n        y = x\n    else:\n        z = 'a'\n        z = x\n[builtins fixtures/isinstance.pyi]\n\n[case testUnion3]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None:\n    if isinstance(x, int):\n        y = 1\n        if int():\n            y = x\n    else:\n        z = 2\n        if int():\n            z = x # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testUnionAnyIsInstance]\nfrom typing import Any, Union\n\ndef func(v: Union[int, Any]) -> None:\n    if isinstance(v, int):\n        reveal_type(v) # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(v) # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testUnionAttributeAccess]\nfrom typing import Union\n\nclass A: y = 1\nclass B: y = 2\nclass C: pass\nclass D: pass\n\nu: Union[A, C, D]\nv: Union[C, D]\nw: Union[A, B]\nx: Union[A, C]\ny: int\nz: str\n\nif int():\n    y = w.y\nv.y           # E: Item \"C\" of \"Union[C, D]\" has no attribute \"y\" \\\n              # E: Item \"D\" of \"Union[C, D]\" has no attribute \"y\"\nu.y           # E: Item \"C\" of \"Union[A, C, D]\" has no attribute \"y\" \\\n              # E: Item \"D\" of \"Union[A, C, D]\" has no attribute \"y\"\nif int():\n    z = w.y       # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nw.y = 'a'     # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    y = x.y       # E: Item \"C\" of \"Union[A, C]\" has no attribute \"y\"\nzz = x.y      # E: Item \"C\" of \"Union[A, C]\" has no attribute \"y\"\nif int():\n    z = zz        # E: Incompatible types in assignment (expression has type \"Union[int, Any]\", variable has type \"str\")\n\n[builtins fixtures/isinstance.pyi]\n\n[case testUnionMethodCalls]\nfrom typing import Union\n\nclass A:\n    def foo(self) -> int: pass\nclass B:\n    def foo(self) -> int: pass\nclass C:\n    def foo(self) -> str: pass\n\nx: Union[A, B]\ny: Union[A, C]\ni: int\n\nx.foo()\ny.foo()\ni = x.foo()\nif int():\n    i = y.foo()   # E: Incompatible types in assignment (expression has type \"Union[int, str]\", variable has type \"int\")\n\n[builtins fixtures/isinstance.pyi]\n\n[case testUnionIndexing]\nfrom typing import Union, List\nx: Union[List[int], str]\nx[2]\nx[2] + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n         # N: Left operand is of type \"Union[int, str]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionAsOverloadArg]\nfrom foo import *\nx = 0\nif int():\n    x = f(1)\nif int():\n    x = f('')\ns = ''\nif int():\n    s = f(int)\nif int():\n    s = f(1)    # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    x = f(int)  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[file foo.pyi]\nfrom typing import Union, overload\n@overload\ndef f(x: Union[int, str]) -> int: pass\n@overload\ndef f(x: type) -> str: pass\n\n[case testUnionWithNoneItem]\n# flags: --no-strict-optional\nfrom typing import Union\ndef f() -> Union[int, None]: pass\nx = 1\nx = f()\n\n[case testUnionWithEllipsis]\nfrom typing import Union\ndef f(x: Union[int, EllipsisType]) -> int:\n    if x is Ellipsis:\n        reveal_type(x) # N: Revealed type is \"builtins.ellipsis\"\n        x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    return x\n[builtins fixtures/isinstancelist.pyi]\n\n[case testOptional]\nfrom typing import Optional\ndef f(x: Optional[int]) -> None: pass\nf(1)\nf(None)\nf('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"Optional[int]\"\n\n[case testUnionWithNoReturn]\nfrom typing import Union, NoReturn\ndef f() -> Union[int, NoReturn]: ...\nreveal_type(f()) # N: Revealed type is \"builtins.int\"\n\n[case testUnionSimplificationGenericFunction]\nfrom typing import TypeVar, Union, List\nT = TypeVar('T')\ndef f(x: List[T]) -> Union[T, int]: pass\ndef g(y: str) -> None: pass\na = f([1])\ng(a) # E: Argument 1 to \"g\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/list.pyi]\n\n[case testUnionSimplificationGenericClass]\nfrom typing import TypeVar, Union, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass C(Generic[T, U]):\n    def f(self, x: str) -> Union[T, U]: pass\na = C() # type: C[int, int]\nb = a.f('a')\na.f(b) # E: Argument 1 to \"f\" of \"C\" has incompatible type \"int\"; expected \"str\"\n\n[case testUnionOrderEquivalence]\nfrom typing import Union\n\ndef foo(): pass\n\nS = str\nT = int\n\nif foo():\n    def f(x: Union[int, str]) -> None: pass\nelif foo():\n    def f(x: Union[str, int]) -> None: pass\nelif foo():\n    def f(x: Union[int, str, int, int, str]) -> None: pass\nelif foo():\n    def f(x: Union[int, str, float]) -> None: pass  # E: All conditional function variants must have identical signatures \\\n                                                    # N: Original: \\\n                                                    # N:     def f(x: Union[int, str]) -> None \\\n                                                    # N: Redefinition: \\\n                                                    # N:     def f(x: Union[int, str, float]) -> None\nelif foo():\n    def f(x: Union[S, T]) -> None: pass\nelif foo():\n    def f(x: Union[str]) -> None: pass  # E: All conditional function variants must have identical signatures \\\n                                        # N: Original: \\\n                                        # N:     def f(x: Union[int, str]) -> None \\\n                                        # N: Redefinition: \\\n                                        # N:     def f(x: str) -> None\nelse:\n    def f(x: Union[Union[int, T], Union[S, T], str]) -> None: pass\n\n# Checks bidirectionality of testing. The first definition of g is consistent with\n# the second, but not vice-versa.\nif foo():\n    def g(x: Union[int, str, bytes]) -> None: pass\nelse:\n    def g(x: Union[int, str]) -> None: pass  # E: All conditional function variants must have identical signatures \\\n                                             # N: Original: \\\n                                             # N:     def g(x: Union[int, str, bytes]) -> None \\\n                                             # N: Redefinition: \\\n                                             # N:     def g(x: Union[int, str]) -> None\n\n[case testUnionSimplificationSpecialCases]\n# flags: --no-strict-optional\nfrom typing import Any, TypeVar, Union\n\nclass C(Any): pass\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\na = None # type: Any\n\nreveal_type(u(C(), None))  # N: Revealed type is \"__main__.C\"\nreveal_type(u(None, C()))  # N: Revealed type is \"__main__.C\"\n\nreveal_type(u(C(), a))  # N: Revealed type is \"Union[Any, __main__.C]\"\nreveal_type(u(a, C()))  # N: Revealed type is \"Union[__main__.C, Any]\"\n\nreveal_type(u(C(), C()))  # N: Revealed type is \"__main__.C\"\nreveal_type(u(a, a))  # N: Revealed type is \"Any\"\n\n[case testUnionSimplificationSpecialCase2]\nfrom typing import Any, TypeVar, Union\n\nclass C(Any): pass\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\ndef f(x: T) -> None:\n    reveal_type(u(C(), x)) # N: Revealed type is \"Union[T`-1, __main__.C]\"\n    reveal_type(u(x, C())) # N: Revealed type is \"Union[__main__.C, T`-1]\"\n\n[case testUnionSimplificationSpecialCase3]\nfrom typing import Any, TypeVar, Generic, Union\n\nclass C(Any): pass\n\nV = TypeVar('V')\nT = TypeVar('T')\n\nclass M(Generic[V]):\n    def get(self, default: T) -> Union[V, T]: ...\n\ndef f(x: M[C]) -> None:\n    y = x.get(None)\n    reveal_type(y) # N: Revealed type is \"Union[__main__.C, None]\"\n\n[case testUnionSimplificationSpecialCases2]\n# flags: --no-strict-optional\nfrom typing import Any, TypeVar, Union\n\nclass C(Any): pass\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\na = None # type: Any\n\n# Base-class-Any and None, simplify\nreveal_type(u(C(), None))  # N: Revealed type is \"__main__.C\"\nreveal_type(u(None, C()))  # N: Revealed type is \"__main__.C\"\n\n# Normal instance type and None, simplify\nreveal_type(u(1, None))  # N: Revealed type is \"builtins.int\"\nreveal_type(u(None, 1))  # N: Revealed type is \"builtins.int\"\n\n# Normal instance type and base-class-Any, no simplification\nreveal_type(u(C(), 1))  # N: Revealed type is \"Union[builtins.int, __main__.C]\"\nreveal_type(u(1, C()))  # N: Revealed type is \"Union[__main__.C, builtins.int]\"\n\n# Normal instance type and Any, no simplification\nreveal_type(u(1, a))  # N: Revealed type is \"Union[Any, builtins.int]\"\nreveal_type(u(a, 1))  # N: Revealed type is \"Union[builtins.int, Any]\"\n\n# Any and base-class-Any, no simplification\nreveal_type(u(C(), a))  # N: Revealed type is \"Union[Any, __main__.C]\"\nreveal_type(u(a, C()))  # N: Revealed type is \"Union[__main__.C, Any]\"\n\n# Two normal instance types, simplify\nreveal_type(u(1, object()))  # N: Revealed type is \"builtins.object\"\nreveal_type(u(object(), 1))  # N: Revealed type is \"builtins.object\"\n\n# Two normal instance types, no simplification\nreveal_type(u(1, ''))  # N: Revealed type is \"Union[builtins.str, builtins.int]\"\nreveal_type(u('', 1))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\n[case testUnionSimplificationWithDuplicateItems]\nfrom typing import Any, TypeVar, Union\n\nclass C(Any): pass\n\nT = TypeVar('T')\nS = TypeVar('S')\nR = TypeVar('R')\ndef u(x: T, y: S, z: R) -> Union[R, S, T]: pass\n\na: Any\n\nreveal_type(u(1, 1, 1))  # N: Revealed type is \"builtins.int\"\nreveal_type(u(C(), C(), None))  # N: Revealed type is \"Union[None, __main__.C]\"\nreveal_type(u(a, a, 1))  # N: Revealed type is \"Union[builtins.int, Any]\"\nreveal_type(u(a, C(), a))  # N: Revealed type is \"Union[Any, __main__.C]\"\nreveal_type(u('', 1, 1))  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\n[case testUnionAndBinaryOperation]\nfrom typing import Union\nclass A: pass\ndef f(x: Union[int, str, A]):\n    x + object() # E: Unsupported left operand type for + (\"A\") \\\n                 # N: Left operand is of type \"Union[int, str, A]\" \\\n                 # E: Unsupported operand types for + (\"int\" and \"object\") \\\n                 # E: Unsupported operand types for + (\"str\" and \"object\")\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingDownNamedTupleUnion]\nfrom typing import NamedTuple, Union\n\nA = NamedTuple('A', [('y', int)])\nB = NamedTuple('B', [('x', int)])\nC = NamedTuple('C', [('x', int)])\n\ndef foo(a: Union[A, B, C]):\n    if isinstance(a, (B, C)):\n        reveal_type(a) # N: Revealed type is \"Union[Tuple[builtins.int, fallback=__main__.B], Tuple[builtins.int, fallback=__main__.C]]\"\n        a.x\n        a.y # E: Item \"B\" of \"Union[B, C]\" has no attribute \"y\" \\\n            # E: Item \"C\" of \"Union[B, C]\" has no attribute \"y\"\n        b = a # type: Union[B, C]\n[builtins fixtures/isinstance.pyi]\n\n[case testSimplifyingUnionAndTypePromotions]\nfrom typing import TypeVar, Union\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[T, S]: pass\n\nreveal_type(u(1, 2.3))  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\nreveal_type(u(2.3, 1))  # N: Revealed type is \"Union[builtins.float, builtins.int]\"\nreveal_type(u(False, 2.2)) # N: Revealed type is \"Union[builtins.bool, builtins.float]\"\nreveal_type(u(2.2, False)) # N: Revealed type is \"Union[builtins.float, builtins.bool]\"\n[builtins fixtures/primitives.pyi]\n\n[case testSimplifyingUnionWithTypeTypes1]\nfrom typing import TypeVar, Union, Type, Any\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\nt_o: Type[object]\nt_s: Type[str]\nt_a: Type[Any]\n\n# Two identical items\nreveal_type(u(t_o, t_o)) # N: Revealed type is \"Type[builtins.object]\"\nreveal_type(u(t_s, t_s)) # N: Revealed type is \"Type[builtins.str]\"\nreveal_type(u(t_a, t_a)) # N: Revealed type is \"Type[Any]\"\nreveal_type(u(type, type)) # N: Revealed type is \"def (x: builtins.object) -> builtins.type\"\n\n# One type, other non-type\nreveal_type(u(t_s, 1)) # N: Revealed type is \"Union[builtins.int, Type[builtins.str]]\"\nreveal_type(u(1, t_s)) # N: Revealed type is \"Union[Type[builtins.str], builtins.int]\"\nreveal_type(u(type, 1)) # N: Revealed type is \"Union[builtins.int, def (x: builtins.object) -> builtins.type]\"\nreveal_type(u(1, type)) # N: Revealed type is \"Union[def (x: builtins.object) -> builtins.type, builtins.int]\"\nreveal_type(u(t_a, 1)) # N: Revealed type is \"Union[builtins.int, Type[Any]]\"\nreveal_type(u(1, t_a)) # N: Revealed type is \"Union[Type[Any], builtins.int]\"\nreveal_type(u(t_o, 1)) # N: Revealed type is \"Union[builtins.int, Type[builtins.object]]\"\nreveal_type(u(1, t_o)) # N: Revealed type is \"Union[Type[builtins.object], builtins.int]\"\n\n[case testSimplifyingUnionWithTypeTypes2]\nfrom typing import TypeVar, Union, Type, Any\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\nt_o: Type[object]\nt_s: Type[str]\nt_a: Type[Any]\nt: type\n\n# Union with object\nreveal_type(u(t_o, object())) # N: Revealed type is \"builtins.object\"\nreveal_type(u(object(), t_o)) # N: Revealed type is \"builtins.object\"\nreveal_type(u(t_s, object())) # N: Revealed type is \"builtins.object\"\nreveal_type(u(object(), t_s)) # N: Revealed type is \"builtins.object\"\nreveal_type(u(t_a, object())) # N: Revealed type is \"builtins.object\"\nreveal_type(u(object(), t_a)) # N: Revealed type is \"builtins.object\"\n\n# Union between type objects\nreveal_type(u(t_o, t_a)) # N: Revealed type is \"Union[Type[Any], Type[builtins.object]]\"\nreveal_type(u(t_a, t_o)) # N: Revealed type is \"Union[Type[builtins.object], Type[Any]]\"\nreveal_type(u(t_s, t_o)) # N: Revealed type is \"Type[builtins.object]\"\nreveal_type(u(t_o, t_s)) # N: Revealed type is \"Type[builtins.object]\"\nreveal_type(u(t_o, type)) # N: Revealed type is \"Type[builtins.object]\"\nreveal_type(u(type, t_o)) # N: Revealed type is \"Type[builtins.object]\"\nreveal_type(u(t_a, t)) # N: Revealed type is \"builtins.type\"\nreveal_type(u(t, t_a)) # N: Revealed type is \"builtins.type\"\n# The following should arguably not be simplified, but it's unclear how to fix then\n# without causing regressions elsewhere.\nreveal_type(u(t_o, t)) # N: Revealed type is \"builtins.type\"\nreveal_type(u(t, t_o)) # N: Revealed type is \"builtins.type\"\n\n[case testNotSimplifyingUnionWithMetaclass]\nfrom typing import TypeVar, Union, Type, Any\n\nclass M(type): pass\nclass M2(M): pass\nclass A(metaclass=M): pass\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\na: Any\nt_a: Type[A]\n\nreveal_type(u(M(*a), t_a)) # N: Revealed type is \"__main__.M\"\nreveal_type(u(t_a, M(*a))) # N: Revealed type is \"__main__.M\"\n\nreveal_type(u(M2(*a), t_a)) # N: Revealed type is \"Union[Type[__main__.A], __main__.M2]\"\nreveal_type(u(t_a, M2(*a))) # N: Revealed type is \"Union[__main__.M2, Type[__main__.A]]\"\n\n[case testSimplifyUnionWithCallable]\nfrom typing import TypeVar, Union, Any, Callable\n\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\n\nclass C: pass\nclass D(C): pass\n\nD_C: Callable[[D], C]\nA_C: Callable[[Any], C]\nD_A: Callable[[D], Any]\nC_C: Callable[[C], C]\nD_D: Callable[[D], D]\ni_C: Callable[[int], C]\n\n# TODO: Test argument names and kinds once we have flexible callable types.\n\nreveal_type(u(D_C, D_C)) # N: Revealed type is \"def (__main__.D) -> __main__.C\"\n\nreveal_type(u(A_C, D_C)) # N: Revealed type is \"Union[def (__main__.D) -> __main__.C, def (Any) -> __main__.C]\"\nreveal_type(u(D_C, A_C)) # N: Revealed type is \"Union[def (Any) -> __main__.C, def (__main__.D) -> __main__.C]\"\n\nreveal_type(u(D_A, D_C)) # N: Revealed type is \"Union[def (__main__.D) -> __main__.C, def (__main__.D) -> Any]\"\nreveal_type(u(D_C, D_A)) # N: Revealed type is \"Union[def (__main__.D) -> Any, def (__main__.D) -> __main__.C]\"\n\nreveal_type(u(D_C, C_C)) # N: Revealed type is \"def (__main__.D) -> __main__.C\"\nreveal_type(u(C_C, D_C)) # N: Revealed type is \"def (__main__.D) -> __main__.C\"\n\nreveal_type(u(D_C, D_D)) # N: Revealed type is \"def (__main__.D) -> __main__.C\"\nreveal_type(u(D_D, D_C)) # N: Revealed type is \"def (__main__.D) -> __main__.C\"\n\nreveal_type(u(D_C, i_C)) # N: Revealed type is \"Union[def (builtins.int) -> __main__.C, def (__main__.D) -> __main__.C]\"\n\n[case testUnionOperatorMethodSpecialCase]\nfrom typing import Union\nclass C:\n    def __le__(self, x: 'C') -> int: ...\nclass D:\n    def __le__(self, other) -> int: ...\nclass E:\n    def __ge__(self, other: Union[C, D]) -> int: ...\n\n[case testUnionSimplificationWithBoolIntAndFloat]\nfrom typing import List, Union\nl = reveal_type([]) # type: List[Union[bool, int, float]] \\\n    # N: Revealed type is \"builtins.list[Union[builtins.int, builtins.float]]\"\nreveal_type(l) \\\n    # N: Revealed type is \"builtins.list[Union[builtins.bool, builtins.int, builtins.float]]\"\n[builtins fixtures/list.pyi]\n\n[case testUnionSimplificationWithBoolIntAndFloat2]\nfrom typing import List, Union\nl = reveal_type([]) # type: List[Union[bool, int, float, str]] \\\n    # N: Revealed type is \"builtins.list[Union[builtins.int, builtins.float, builtins.str]]\"\nreveal_type(l) \\\n    # N: Revealed type is \"builtins.list[Union[builtins.bool, builtins.int, builtins.float, builtins.str]]\"\n[builtins fixtures/list.pyi]\n\n[case testNestedUnionsProcessedCorrectly]\nfrom typing import Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\ndef foo(bar: Union[Union[A, B], C]) -> None:\n    if isinstance(bar, A):\n        reveal_type(bar)  # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(bar)  # N: Revealed type is \"Union[__main__.B, __main__.C]\"\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testAssignAnyToUnion]\nfrom typing import Union, Any\nx: Union[int, str]\na: Any\nif bool():\n    x = a\n    # TODO: Maybe we should infer Any as the type instead.\n    reveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/bool.pyi]\n\n[case testAssignAnyToUnionWithAny]\nfrom typing import Union, Any\nx: Union[int, Any]\na: Any\nif bool():\n    x = a\n    reveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, Any]\"\n[builtins fixtures/bool.pyi]\n\n[case testUnionMultiassignSingle]\nfrom typing import Union, Tuple, Any\n\na: Union[Tuple[int], Tuple[float]]\n(a1,) = a\nreveal_type(a1)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\n\nb: Union[Tuple[int], Tuple[str]]\n(b1,) = b\nreveal_type(b1)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionMultiassignDouble]\nfrom typing import Union, Tuple\n\nc: Union[Tuple[int, int], Tuple[int, float]]\n(c1, c2) = c\nreveal_type(c1)  # N: Revealed type is \"builtins.int\"\nreveal_type(c2)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionMultiassignGeneric]\nfrom typing import Union, Tuple, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n\ndef pack_two(x: T, y: S) -> Union[Tuple[T, T], Tuple[S, S]]:\n    pass\n\n(x, y) = pack_two(1, 'a')\nreveal_type(x)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionMultiassignAny]\nfrom typing import Union, Tuple, Any\n\nd: Union[Any, Tuple[float, float]]\n(d1, d2) = d\nreveal_type(d1)  # N: Revealed type is \"Union[Any, builtins.float]\"\nreveal_type(d2)  # N: Revealed type is \"Union[Any, builtins.float]\"\n\ne: Union[Any, Tuple[float, float], int]\n(e1, e2) = e  # E: \"int\" object is not iterable\n[builtins fixtures/tuple.pyi]\n\n[case testUnionMultiassignNotJoin]\nfrom typing import Union, List\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\na: Union[List[B], List[C]]\nx, y = a\nreveal_type(x)  # N: Revealed type is \"Union[__main__.B, __main__.C]\"\n[builtins fixtures/list.pyi]\n\n[case testUnionMultiassignRebind]\nfrom typing import Union, List\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\nobj: object\na: Union[List[B], List[C]]\nobj, new = a\nreveal_type(obj)  # N: Revealed type is \"Union[__main__.B, __main__.C]\"\nreveal_type(new)  # N: Revealed type is \"Union[__main__.B, __main__.C]\"\n\nobj = 1\nreveal_type(obj)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testUnionMultiassignAlreadyDeclared]\nfrom typing import Union, Tuple\n\na: Union[Tuple[int, int], Tuple[int, float]]\na1: object\na2: int\n(a1, a2) = a  # E: Incompatible types in assignment (expression has type \"float\", variable has type \"int\")\n\nb: Union[Tuple[float, int], Tuple[int, int]]\nb1: object\nb2: int\n(b1, b2) = b\nreveal_type(b1) # N: Revealed type is \"Union[builtins.float, builtins.int]\"\nreveal_type(b2) # N: Revealed type is \"builtins.int\"\n\nc: Union[Tuple[int, int], Tuple[int, int]]\nc1: object\nc2: int\n(c1, c2) = c\nreveal_type(c1)  # N: Revealed type is \"builtins.int\"\nreveal_type(c2)  # N: Revealed type is \"builtins.int\"\n\nd: Union[Tuple[int, int], Tuple[int, float]]\nd1: object\n(d1, d2) = d\nreveal_type(d1)  # N: Revealed type is \"builtins.int\"\nreveal_type(d2)  # N: Revealed type is \"Union[builtins.int, builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionMultiassignIndexed]\nfrom typing import Union, Tuple, List\n\nclass B:\n    x: object\n\nx: List[int]\nb: B\n\na: Union[Tuple[int, int], Tuple[int, object]]\n(x[0], b.x) = a\nreveal_type(x[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(b.x)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/list.pyi]\n\n[case testUnionMultiassignIndexedWithError]\nfrom typing import Union, Tuple, List\n\nclass A: pass\nclass B:\n    x: int\n\nx: List[A]\nb: B\n\na: Union[Tuple[int, int], Tuple[int, object]]\n(x[0], b.x) = a  # E: Incompatible types in assignment (expression has type \"int\", target has type \"A\") \\\n                 # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\nreveal_type(x[0])  # N: Revealed type is \"__main__.A\"\nreveal_type(b.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testUnionMultiassignPacked]\nfrom typing import Union, Tuple, List\n\na: Union[Tuple[int, int, int], Tuple[int, int, str]]\na1: int\na2: object\n(a1, *xs, a2) = a\n\nreveal_type(a1)  # N: Revealed type is \"builtins.int\"\nreveal_type(xs)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(a2)  # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/list.pyi]\n\n[case testUnpackingUnionOfListsInFunction]\nfrom typing import Union, List\n\ndef f(x: bool) -> Union[List[int], List[str]]:\n    if x:\n        return [1, 1]\n    else:\n        return ['a', 'a']\n\ndef g(x: bool) -> None:\n    a, b = f(x)\n    reveal_type(a) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    reveal_type(b) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/list.pyi]\n\n[case testUnionOfVariableLengthTupleUnpacking]\nfrom typing import Tuple, Union\nVarTuple = Union[Tuple[int, int], Tuple[int, int, int]]\n\ndef make_tuple() -> VarTuple:\n    pass\nx = make_tuple()\n\na, b = x # E: Too many values to unpack (2 expected, 3 provided)\na, b, c = x # E: Need more than 2 values to unpack (3 expected)\nc, *d = x\nreveal_type(c) # N: Revealed type is \"builtins.int\"\nreveal_type(d) # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnionOfNonIterableUnpacking]\nfrom typing import Union\nbad: Union[int, str]\n\nx, y = bad # E: \"int\" object is not iterable \\\n           # E: Unpacking a string is disallowed\nreveal_type(x) # N: Revealed type is \"Any\"\nreveal_type(y) # N: Revealed type is \"Any\"\n[out]\n\n[case testStringDisallowedUnpacking]\nfrom typing import Dict\n\nd: Dict[str, str]\n\nfor a, b in d: # E: Unpacking a string is disallowed\n    pass\n\ns = \"foo\"\na, b = s # E: Unpacking a string is disallowed\n\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testUnionAlwaysTooMany]\nfrom typing import Union, Tuple\nbad: Union[Tuple[int, int, int], Tuple[str, str, str]]\n\nx, y = bad # E: Too many values to unpack (2 expected, 3 provided)\nreveal_type(x) # N: Revealed type is \"Any\"\nreveal_type(y) # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnionAlwaysTooFew]\nfrom typing import Union, Tuple\nbad: Union[Tuple[int, int, int], Tuple[str, str, str]]\n\nx, y, z, w = bad # E: Need more than 3 values to unpack (4 expected)\nreveal_type(x) # N: Revealed type is \"Any\"\nreveal_type(y) # N: Revealed type is \"Any\"\nreveal_type(z) # N: Revealed type is \"Any\"\nreveal_type(w) # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnionUnpackingChainedTuple]\nfrom typing import Union, Tuple\ngood: Union[Tuple[int, int], Tuple[str, str]]\n\nx, y = t = good\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(t) # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.str, builtins.str]]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnionUnpackingChainedTuple2]\nfrom typing import Union, Tuple\ngood: Union[Tuple[int, int], Tuple[str, str]]\n\nt = x, y = good\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(t) # N: Revealed type is \"Union[Tuple[builtins.int, builtins.int], Tuple[builtins.str, builtins.str]]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnionUnpackingChainedTuple3]\nfrom typing import Union, Tuple\ngood: Union[Tuple[int, int], Tuple[str, str]]\n\nx, y = a, b = good\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(a) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(b) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnionUnpackingChainedList]\nfrom typing import Union, List\ngood: Union[List[int], List[str]]\n\nlst = x, y = good\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(lst) # N: Revealed type is \"Union[builtins.list[builtins.int], builtins.list[builtins.str]]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testUnionUnpackingChainedList2]\nfrom typing import Union, List\ngood: Union[List[int], List[str]]\n\nx, *y, z = lst = good\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.list[builtins.int], builtins.list[builtins.str]]\"\nreveal_type(z) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(lst) # N: Revealed type is \"Union[builtins.list[builtins.int], builtins.list[builtins.str]]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testUnionUnpackingInForTuple]\nfrom typing import Union, Tuple, NamedTuple\nclass NTInt(NamedTuple):\n    x: int\n    y: int\nclass NTStr(NamedTuple):\n    x: str\n    y: str\n\nt1: NTInt\nreveal_type(t1.__iter__) # N: Revealed type is \"def () -> typing.Iterator[builtins.int]\"\nnt: Union[NTInt, NTStr]\nreveal_type(nt.__iter__) # N: Revealed type is \"Union[def () -> typing.Iterator[builtins.int], def () -> typing.Iterator[builtins.str]]\"\nfor nx in nt:\n    reveal_type(nx) # N: Revealed type is \"Union[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 \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/for.pyi]\n[out]\n\n[case testUnionUnpackingInForList]\nfrom typing import Union, List, Tuple\n\nt: Union[List[Tuple[int, int]], List[Tuple[str, str]]]\nfor x, y in t:\n    reveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    reveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\nt2: List[Union[Tuple[int, int], Tuple[str, str]]]\nfor x2, y2 in t2:\n    reveal_type(x2) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n    reveal_type(y2) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/for.pyi]\n[out]\n\n[case testUnionUnpackingDoubleBinder]\nfrom typing import Union, Tuple\n\nx: object\ny: object\nclass A: pass\nclass B: pass\n\nt1: Union[Tuple[A, A], Tuple[B, B]]\nt2: Union[Tuple[int, int], Tuple[str, str]]\n\nx, y = t1\nreveal_type(x) # N: Revealed type is \"Union[__main__.A, __main__.B]\"\nreveal_type(y) # N: Revealed type is \"Union[__main__.A, __main__.B]\"\n\nx, y = t2\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n\nx, y = object(), object()\nreveal_type(x) # N: Revealed type is \"builtins.object\"\nreveal_type(y) # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnionUnpackingFromNestedTuples]\nfrom typing import Union, Tuple\n\nt: Union[Tuple[int, Tuple[int, int]], Tuple[str, Tuple[str, str]]]\nx, (y, z) = t\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(z) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNestedUnionUnpackingFromNestedTuples]\nfrom typing import Union, Tuple\n\nclass A: pass\nclass B: pass\n\nt: Union[Tuple[int, Union[Tuple[int, int], Tuple[A, A]]], Tuple[str, Union[Tuple[str, str], Tuple[B, B]]]]\nx, (y, z) = t\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, __main__.A, builtins.str, __main__.B]\"\nreveal_type(z) # N: Revealed type is \"Union[builtins.int, __main__.A, builtins.str, __main__.B]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNestedUnionUnpackingFromNestedTuplesBinder]\nfrom typing import Union, Tuple\n\nclass A: pass\nclass B: pass\n\nx: object\ny: object\nz: object\n\nt: Union[Tuple[int, Union[Tuple[int, int], Tuple[A, A]]], Tuple[str, Union[Tuple[str, str], Tuple[B, B]]]]\nx, (y, z) = t\nreveal_type(x) # N: Revealed type is \"Union[builtins.int, builtins.str]\"\nreveal_type(y) # N: Revealed type is \"Union[builtins.int, __main__.A, builtins.str, __main__.B]\"\nreveal_type(z) # N: Revealed type is \"Union[builtins.int, __main__.A, builtins.str, __main__.B]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUnpackUnionNoCrashOnPartialNone]\nfrom typing import Dict, Tuple, List, Any\n\na: Any\nd: Dict[str, Tuple[List[Tuple[str, str]], str]]\nx, _ = d.get(a, (None, None))\n\nfor y in x: pass # E: Item \"None\" of \"Optional[List[Tuple[str, str]]]\" has no attribute \"__iter__\" (not iterable)\nif x:\n    for s, t in x:\n        reveal_type(s) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testUnpackUnionNoCrashOnPartialNone2]\nfrom typing import Dict, Tuple, List, Any\n\na: Any\nx = None\nd: Dict[str, Tuple[List[Tuple[str, str]], str]]\nx, _ = d.get(a, (None, None))\n\nfor y in x: pass # E: Item \"None\" of \"Optional[List[Tuple[str, str]]]\" has no attribute \"__iter__\" (not iterable)\nif x:\n    for s, t in x:\n        reveal_type(s) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testUnpackUnionNoCrashOnPartialNoneBinder]\nfrom typing import Dict, Tuple, List, Any\n\nx: object\na: Any\nd: Dict[str, Tuple[List[Tuple[str, str]], str]]\nx, _ = d.get(a, (None, None))\nreveal_type(x) # N: Revealed type is \"Union[builtins.list[Tuple[builtins.str, builtins.str]], None]\"\n\nif x:\n    for y in x: pass\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testUnpackUnionNoCrashOnPartialList]\nfrom typing import Dict, Tuple, List, Any\n\na: Any\nd: Dict[str, Tuple[List[Tuple[str, str]], str]]\nx, _ = d.get(a, ([], \"\"))\nreveal_type(x) # N: Revealed type is \"builtins.list[Tuple[builtins.str, builtins.str]]\"\n\nfor y in x: pass\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testLongUnionFormatting]\nfrom typing import Any, Generic, TypeVar, Union\n\nT = TypeVar('T')\n\nclass ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes(Generic[T]):\n    pass\n\nx: Union[ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[int],\n         ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[object],\n         ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[float],\n         ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[str],\n         ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[Any],\n         ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[bytes]]\n\ndef takes_int(arg: int) -> None: pass\n\ntakes_int(x)  # E: Argument 1 to \"takes_int\" has incompatible type \"Union[ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[int], ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[object], ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[float], ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[str], ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[Any], ExtremelyLongTypeNameWhichIsGenericSoWeCanUseItMultipleTimes[bytes]]\"; expected \"int\"\n\n[case testRecursiveForwardReferenceInUnion]\nfrom typing import List, Union\n\ndef test() -> None:\n    MYTYPE = List[Union[str, \"MYTYPE\"]]  # E: Cannot resolve name \"MYTYPE\" (possible cyclic definition) \\\n                                         # N: Recursive types are not allowed at function scope \\\n                                         # E: Cannot resolve name \"MYTYPE\" (possible cyclic definition) \\\n                                         # N: Recursive types are not allowed at function scope\n[builtins fixtures/list.pyi]\n\n[case testNonStrictOptional]\n# flags: --no-strict-optional\nfrom typing import Optional, List\n\ndef union_test1(x):\n    # type: (Optional[List[int]]) -> Optional[int]\n    if x is None:\n        return x\n    else:\n        return x[0]\n\ndef union_test2(x):\n    # type: (Optional[List[int]]) -> Optional[int]\n    if isinstance(x, type(None)):\n        return x\n    else:\n        return x[0]\n\ndef f(): return 0\n\ndef union_test3():\n    # type: () -> int\n    x = f()\n    assert x is None\n    x = f()\n    return x + 1\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testInvariance]\nfrom typing import List, Union\nfrom enum import Enum\n\nclass Boop(Enum):\n    FOO = 1\n\ndef do_thing_with_enums(enums: Union[List[Enum], Enum]) -> None: ...\n\nboop: List[Boop] = []\ndo_thing_with_enums(boop)  # E: Argument 1 to \"do_thing_with_enums\" has incompatible type \"List[Boop]\"; expected \"Union[List[Enum], Enum]\" \\\n                           # N: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance \\\n                           # N: Consider using \"Sequence\" instead, which is covariant\n[builtins fixtures/isinstancelist.pyi]\n\n[case testAssignUnionWithTenaryExprWithEmptyCollection]\nfrom typing import Dict, List, Union\nx: Union[int, List[int]] = 1 if bool() else []\ny: Union[int, Dict[int, int]] = 1 if bool() else {}\n\nu: Union[int, List[int]] = [] if bool() else 1\nv: Union[int, Dict[int, int]] = {} if bool() else 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testFlattenTypeAliasWhenAliasedAsUnion]\nfrom typing import Union\n\nT1 = int\nT2 = Union[T1, float]\nT3 = Union[T2, complex]\nT4 = Union[T3, int]\n\ndef foo(a: T2, b: T2) -> T2:\n    return a + b\n\ndef bar(a: T4, b: T4) -> T4:  # test multi-level alias\n    return a + b\n[builtins fixtures/ops.pyi]\n\n[case testJoinUnionWithUnionAndAny]\nfrom typing import TypeVar, Union, Any\nT = TypeVar(\"T\")\ndef f(x: T, y: T) -> T:\n    return x\nx: Union[None, Any]\ny: Union[int, None]\nreveal_type(f(x, y)) # N: Revealed type is \"Union[None, Any, builtins.int]\"\nreveal_type(f(y, x)) # N: Revealed type is \"Union[builtins.int, None, Any]\"\n\n[case testNestedProtocolUnions]\nfrom typing import Union, Iterator, Iterable\ndef foo(\n    values: Union[\n        Iterator[Union[\n            Iterator[Union[Iterator[int], Iterable[int]]],\n            Iterable[Union[Iterator[int], Iterable[int]]],\n        ]],\n        Iterable[Union[\n            Iterator[Union[Iterator[int], Iterable[int]]],\n            Iterable[Union[Iterator[int], Iterable[int]]],\n        ]],\n    ]\n) -> Iterator[int]:\n    for i in values:\n        for j in i:\n            for k in j:\n                yield k\nfoo([[[1]]])\n[builtins fixtures/list.pyi]\n\n[case testNestedProtocolGenericUnions]\nfrom typing import Union, Iterator, List\ndef foo(\n    values: Union[\n        Iterator[Union[\n            Iterator[Union[Iterator[int], List[int]]],\n            List[Union[Iterator[int], List[int]]],\n        ]],\n        List[Union[\n            Iterator[Union[Iterator[int], List[int]]],\n            List[Union[Iterator[int], List[int]]],\n        ]],\n    ]\n) -> Iterator[int]:\n    for i in values:\n        for j in i:\n            for k in j:\n                yield k\nfoo([[[1]]])\n[builtins fixtures/list.pyi]\n\n[case testNestedProtocolGenericUnionsDeep]\nfrom typing import TypeVar, Union, Iterator, List\nT = TypeVar(\"T\")\nIter = Union[Iterator[T], List[T]]\ndef foo(\n    values: Iter[Iter[Iter[Iter[Iter[int]]]]],\n) -> Iterator[int]:\n    for i in values:\n        for j in i:\n            for k in j:\n                for l in k:\n                    for m in l:\n                        yield m\nfoo([[[[[1]]]]])\n[builtins fixtures/list.pyi]\n\n[case testNestedInstanceUnsimplifiedUnion]\nfrom typing import TypeVar, Union, Iterator, List, Any\nT = TypeVar(\"T\")\n\nIter = Union[Iterator[T], List[T]]\ndef foo(\n    values: Iter[Union[Any, Any]],\n) -> Iterator[Any]:\n    for i in values:\n        yield i\nfoo([1])\n[builtins fixtures/list.pyi]\n\n[case testNestedInstanceTypeAlias]\nfrom typing import TypeVar, Union, Iterator, List, Any\nT = TypeVar(\"T\")\n\nIter = Union[Iterator[T], List[T]]\ndef foo(\n    values: Iter[\"Any\"],\n) -> Iterator[Any]:\n    for i in values:\n        yield i\nfoo([1])\n[builtins fixtures/list.pyi]\n\n[case testGenericUnionMemberWithTypeVarConstraints]\n\nfrom typing import Generic, TypeVar, Union\n\nT = TypeVar('T', str, int)\n\nclass C(Generic[T]): ...\n\ndef f(s: Union[T, C[T]]) -> T:  ...\n\nci: C[int]\ncs: C[str]\n\nreveal_type(f(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(''))  # N: Revealed type is \"builtins.str\"\nreveal_type(f(ci))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(cs))  # N: Revealed type is \"builtins.str\"\n\n\n[case testNestedInstanceTypeAliasUnsimplifiedUnion]\nfrom typing import TypeVar, Union, Iterator, List, Any\nT = TypeVar(\"T\")\n\nIter = Union[Iterator[T], List[T]]\ndef foo(\n    values: Iter[\"Union[Any, Any]\"],\n) -> Iterator[Any]:\n    for i in values:\n        yield i\nfoo([1])\n[builtins fixtures/list.pyi]\n\n[case testUnionIterableContainer]\nfrom typing import Iterable, Container, Union\n\ni: Iterable[str]\nc: Container[str]\nu: Union[Iterable[str], Container[str]]\nni: Union[Iterable[str], int]\nnc: Union[Container[str], int]\n\n'x' in i\n'x' in c\n'x' in u\n'x' in ni  # E: Unsupported right operand type for in (\"Union[Iterable[str], int]\")\n'x' in nc  # E: Unsupported right operand type for in (\"Union[Container[str], int]\")\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testDescriptorAccessForUnionOfTypes]\nfrom typing import overload, Generic, Any, TypeVar, List, Optional, Union, Type\n\n_T_co = TypeVar(\"_T_co\", bound=Any, covariant=True)\n\nclass Mapped(Generic[_T_co]):\n    def __init__(self, value: _T_co):\n        self.value = value\n\n    @overload\n    def __get__(\n        self, instance: None, owner: Any\n    ) -> List[_T_co]:\n        ...\n\n    @overload\n    def __get__(self, instance: object, owner: Any) -> _T_co:\n        ...\n\n    def __get__(\n        self, instance: Optional[object], owner: Any\n    ) -> Union[List[_T_co], _T_co]:\n        return self.value\n\nclass A:\n    field_1: Mapped[int] = Mapped(1)\n    field_2: Mapped[str] = Mapped('1')\n\nclass B:\n    field_1: Mapped[int] = Mapped(2)\n    field_2: Mapped[str] = Mapped('2')\n\nmix: Union[Type[A], Type[B]]\nreveal_type(mix)  # N: Revealed type is \"Union[Type[__main__.A], Type[__main__.B]]\"\nreveal_type(mix.field_1)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(mix().field_1)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n\n[case testDescriptorAccessForUnionOfTypesWithNoStrictOptional]\n# mypy: no-strict-optional\nfrom typing import overload, Generic, Any, TypeVar, List, Optional, Union, Type\n\nclass Descriptor:\n    @overload\n    def __get__(\n        self, instance: None, owner: type\n    ) -> str:\n        ...\n\n    @overload\n    def __get__(self, instance: object, owner: type) -> int:\n        ...\n\n    def __get__(\n        self, instance: Optional[object], owner: type\n    ) -> Union[str, int]:\n        ...\n\nclass A:\n    field = Descriptor()\n\na_class_or_none: Optional[Type[A]]\nx: str = a_class_or_none.field\n\na_or_none: Optional[A]\ny: int = a_or_none.field\n[builtins fixtures/list.pyi]\n\n[case testLargeUnionsShort]\nfrom typing import Union\n\nclass C1: ...\nclass C2: ...\nclass C3: ...\nclass C4: ...\nclass C5: ...\nclass C6: ...\nclass C7: ...\nclass C8: ...\nclass C9: ...\nclass C10: ...\nclass C11: ...\n\nu: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11]\nx: int = u  # E: Incompatible types in assignment (expression has type \"Union[C1, C2, C3, C4, C5, <6 more items>]\", variable has type \"int\")\n\n[case testLargeUnionsLongIfNeeded]\nfrom typing import Union\n\nclass C1: ...\nclass C2: ...\nclass C3: ...\nclass C4: ...\nclass C5: ...\nclass C6: ...\nclass C7: ...\nclass C8: ...\nclass C9: ...\nclass C10: ...\n\nx: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, int]\ny: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, str]\nx = y  # E: Incompatible types in assignment (expression has type \"Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, str]\", variable has type \"Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, int]\") \\\n       # N: Item in the first union not in the second: \"str\"\n\n[case testLargeUnionsNoneShown]\nfrom typing import Union\n\nclass C1: ...\nclass C2: ...\nclass C3: ...\nclass C4: ...\nclass C5: ...\nclass C6: ...\nclass C7: ...\nclass C8: ...\nclass C9: ...\nclass C10: ...\nclass C11: ...\n\nx: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11]\ny: Union[C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, None]\nx = y  # E: Incompatible types in assignment (expression has type \"Union[C1, C2, C3, C4, C5, <6 more items>, None]\", variable has type \"Union[C1, C2, C3, C4, C5, <6 more items>]\") \\\n       # N: Item in the first union not in the second: \"None\"\n"
  },
  {
    "path": "test-data/unit/check-unreachable-code.test",
    "content": "-- Type checker test cases for conditional checks that result in some\n-- blocks classified as unreachable (they are not type checked or semantically\n-- analyzed).\n--\n-- For example, we skip blocks that will not be executed on the active\n-- Python version.\n\n[case testConditionalTypeAliasPY3]\nimport typing\ndef f(): pass\nPY3 = f()\nif PY3:\n    t = int\n    x = object() + 'x' # E: Unsupported left operand type for + (\"object\")\nelse:\n    t = str\n    y = 'x' / 1\nx\nz = 1 # type: t\n\n[case testConditionalAssignmentPY2]\nimport typing\ndef f(): pass\nPY2 = f()\nif PY2:\n    x = object() + 'x'\nelse:\n    y = 'x' / 1 # E: Unsupported left operand type for / (\"str\")\ny\n\n[case testConditionalImport]\nimport typing\ndef f(): pass\nPY2 = f()\nif PY2:\n    import fuzzybar\n    from barbar import *\n    from pawwaw import a, bc\nelse:\n    import m\n[file m.py]\nimport typing\nx = 1\nif int():\n    x = 'a'\n[out]\ntmp/m.py:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testNegatedMypyConditional]\nimport typing\nMYPY = 0\nif not MYPY:\n    import xyz753\nelse:\n    import pow123 # E\n[builtins fixtures/bool.pyi]\n[out]\nmain:6: error: Cannot find implementation or library stub for module named \"pow123\"\nmain:6: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testMypyConditional]\nimport typing\nMYPY = 0\nif MYPY:\n    None + 1 # E: Unsupported left operand type for + (\"None\")\nelse:\n    None + ''\n[builtins fixtures/bool.pyi]\n\n[case testTypeCheckingConditional]\nimport typing\nif typing.TYPE_CHECKING:\n    import pow123 # E\nelse:\n    import xyz753\n[typing fixtures/typing-medium.pyi]\n[out]\nmain:3: error: Cannot find implementation or library stub for module named \"pow123\"\nmain:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testTypeCheckingConditionalFromImport]\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import pow123 # E\nelse:\n    import xyz753\n[typing fixtures/typing-medium.pyi]\n[out]\nmain:3: error: Cannot find implementation or library stub for module named \"pow123\"\nmain:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testNegatedTypeCheckingConditional]\nimport typing\nif not typing.TYPE_CHECKING:\n    import pow123 # E\nelse:\n    import xyz753\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\nmain:5: error: Cannot find implementation or library stub for module named \"xyz753\"\nmain:5: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testUndefinedTypeCheckingConditional]\nif not TYPE_CHECKING: # E\n    import pow123\nelse:\n    import xyz753\n[builtins fixtures/bool.pyi]\n[out]\nmain:1: error: Name \"TYPE_CHECKING\" is not defined\nmain:4: error: Cannot find implementation or library stub for module named \"xyz753\"\nmain:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testConditionalClassDefPY3]\ndef f(): pass\nPY3 = f()\nif PY3:\n    pass\nelse:\n    class X(object):\n        pass\n\n[case testUnreachabilityAndElifPY3]\ndef f(): pass\nPY3 = f()\nif PY3:\n    pass\nelif bool():\n    import nonexistent\n    1 + ''\nelse:\n    import bad_name\n    1 + ''\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testSysVersionInfo]\nimport sys\nif sys.version_info[0] >= 3:\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nreveal_type(foo())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoReversedOperandsOrder]\nimport sys\nif (3,) <= sys.version_info:\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nreveal_type(foo())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoNegated]\nimport sys\nif not (sys.version_info[0] < 3):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nreveal_type(foo())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced1]\nimport sys\nif sys.version_info[:1] >= (3,):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced2]\nimport sys\nif sys.version_info[:2] >= (3, 0):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced3]\nimport sys\nif sys.version_info[:] >= (3, 0):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced4]\nimport sys\nif sys.version_info[0:2] >= (3, 0):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced5]\nimport sys\nif sys.version_info[0:] >= (3,):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced6]\nimport sys\nif sys.version_info[1:] >= (5,):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced7]\nimport sys\nif sys.version_info >= (3, 5):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced8]\n# Our pyversion only has (major, minor),\n# so testing for (major, minor, bugfix) is unsupported.\nimport sys\nif sys.version_info >= (3, 5, 0):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''  # E: All conditional function variants must have identical signatures \\\n                                 # N: Original: \\\n                                 # N:     def foo() -> int \\\n                                 # N: Redefinition: \\\n                                 # N:     def foo() -> str\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoSliced9]\n# Our pyversion only has (major, minor),\n# so testing for (minor, bugfix) is unsupported (also it's silly :-).\nimport sys\nif sys.version_info[1:] >= (5, 0):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''  # E: All conditional function variants must have identical signatures \\\n                                 # N: Original: \\\n                                 # N:     def foo() -> int \\\n                                 # N: Redefinition: \\\n                                 # N:     def foo() -> str\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatform1]\nimport sys\nif sys.platform == 'fictional':\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + ''\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatform2]\nimport sys\nif sys.platform != 'fictional':\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatformNegated]\nimport sys\nif not (sys.platform == 'fictional'):\n    def foo() -> int: return 0\nelse:\n    def foo() -> str: return ''\nfoo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoClass]\nimport sys\nif sys.version_info < (3, 5):\n    class C:\n        pass\nelse:\n    class C:\n        def foo(self) -> int: return 0\nC().foo() + 0\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoImport]\nimport sys\nif sys.version_info >= (3, 5):\n    import collections\nelse:\n    collections = None\nPt = collections.namedtuple('Pt', 'x y z')\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoVariable]\nimport sys\nif sys.version_info >= (3, 5):\n    x = ''\nelse:\n    x = 0\nx + ''\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoInClass]\nimport sys\nclass C:\n    if sys.version_info >= (3, 5):\n        def foo(self) -> int: return 0\n    else:\n        def foo(self) -> str: return ''\nreveal_type(C().foo())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysVersionInfoInFunction]\nimport sys\ndef foo() -> None:\n    if sys.version_info >= (3, 5):\n        x = ''\n    else:\n        x = 0\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatformInMethod]\nimport sys\nclass C:\n    def foo(self) -> None:\n        if sys.platform != 'fictional':\n            x = ''\n        else:\n            x = 0\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatformInFunctionImport1]\nimport sys\ndef foo() -> None:\n    if sys.platform != 'fictional':\n        import a\n    else:\n        import b as a\n    a.x\n[file a.py]\nx = 1\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatformInFunctionImport2]\nimport sys\ndef foo() -> None:\n    if sys.platform == 'fictional':\n        import b as a\n    else:\n        import a\n    a.x\n[file a.py]\nx = 1\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testSysPlatformInFunctionImport3]\nfrom typing import Callable\nimport sys\n\ndef idf(x: Callable[[], None]) -> Callable[[], None]: return x\n\n@idf\ndef foo() -> None:\n    if sys.platform == 'fictional':\n        import b as a\n    else:\n        import a\n    a.x\n[file a.py]\nx = 1\n[builtins fixtures/ops.pyi]\n[out]\n\n\n[case testSysPlatformInMethodImport2]\n\nimport sys\nclass A:\n    def foo(self) -> None:\n        if sys.platform == 'fictional':\n            import b as a\n        else:\n            import a\n        a.x\n[file a.py]\nx = 1\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testCustomSysVersionInfo]\n# flags: --python-version 3.11\nimport sys\nif sys.version_info == (3, 11):\n    x = \"foo\"\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testCustomSysVersionInfo2]\n# flags: --python-version 3.11\nimport sys\nif sys.version_info == (3, 6):\n    x = \"foo\"\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testCustomSysPlatform]\n# flags: --platform linux\nimport sys\nif sys.platform == 'linux':\n    x = \"foo\"\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testCustomSysPlatform2]\n# flags: --platform win32\nimport sys\nif sys.platform == 'linux':\n    x = \"foo\"\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testCustomSysPlatformStartsWith]\n# flags: --platform win32\nimport sys\nif sys.platform.startswith('win'):\n    x = \"foo\"\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testShortCircuitInExpression]\nimport typing\ndef make() -> bool: pass\nPY2 = PY3 = make()\n\na = PY2 and 's'\nb = PY3 and 's'\nc = PY2 or 's'\nd = PY3 or 's'\ne = (PY2 or PY3) and 's'\nf = (PY3 or PY2) and 's'\ng = (PY2 or PY3) or 's'\nh = (PY3 or PY2) or 's'\nreveal_type(a)  # N: Revealed type is \"builtins.bool\"\nreveal_type(b)  # N: Revealed type is \"Literal['s']\"\nreveal_type(c)  # N: Revealed type is \"Literal['s']\"\nreveal_type(d)  # N: Revealed type is \"builtins.bool\"\nreveal_type(e)  # N: Revealed type is \"Literal['s']\"\nreveal_type(f)  # N: Revealed type is \"Literal['s']\"\nreveal_type(g)  # N: Revealed type is \"builtins.bool\"\nreveal_type(h)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testShortCircuitAndWithConditionalAssignment]\n# flags: --platform linux\nimport sys\n\ndef f(): pass\nPY2 = f()\nif PY2 and sys.platform == 'linux':\n    x = 'foo'\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nif sys.platform == 'linux' and PY2:\n    y = 'foo'\nelse:\n    y = 3\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n\n[case testShortCircuitOrWithConditionalAssignment]\n# flags: --platform linux\nimport sys\n\ndef f(): pass\nPY2 = f()\nif PY2 or sys.platform == 'linux':\n    x = 'foo'\nelse:\n    x = 3\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\nif sys.platform == 'linux' or PY2:\n    y = 'foo'\nelse:\n    y = 3\nreveal_type(y)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n\n[case testShortCircuitNoEvaluation]\n# flags: --platform linux --always-false COMPILE_TIME_FALSE\nimport sys\n\nif sys.platform == 'darwin':\n    mac_only = 'junk'\n\n# `mac_only` should not be evaluated\nif sys.platform == 'darwin' and mac_only:\n    pass\nif sys.platform == 'linux' or mac_only:\n    pass\n\nCOMPILE_TIME_FALSE = 'junk'\n\nif COMPILE_TIME_FALSE:\n    compile_time_false_only = 'junk'\n\n# `compile_time_false_only` should not be evaluated\nif COMPILE_TIME_FALSE and compile_time_false_only:\n    pass\nif not COMPILE_TIME_FALSE or compile_time_false_only:\n    pass\n\nMYPY = False\n\nif not MYPY:\n    mypy_only = 'junk'\n\n# `mypy_only` should not be evaluated\nif not MYPY and mypy_only:\n    pass\nif MYPY or mypy_only:\n    pass\n[builtins fixtures/ops.pyi]\n\n[case testSemanticAnalysisFalseButTypeNarrowingTrue]\n# flags: --always-false COMPILE_TIME_FALSE\nfrom typing import Literal\n\nindeterminate: str\nCOMPILE_TIME_FALSE: Literal[True]  # type-narrowing: mapped in 'if' only\na = COMPILE_TIME_FALSE or indeterminate\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\nb = indeterminate or COMPILE_TIME_FALSE\nreveal_type(b)  # N: Revealed type is \"Union[builtins.str, Literal[True]]\"\n[typing fixtures/typing-medium.pyi]\n\n[case testSemanticAnalysisTrueButTypeNarrowingFalse]\n# flags: --always-true COMPILE_TIME_TRUE\nfrom typing import Literal\n\nindeterminate: str\nCOMPILE_TIME_TRUE: Literal[False]  # type narrowed to `else` only\na = COMPILE_TIME_TRUE or indeterminate\nreveal_type(a)  # N: Revealed type is \"Literal[False]\"\nb = indeterminate or COMPILE_TIME_TRUE\nreveal_type(b)  # N: Revealed type is \"Union[builtins.str, Literal[False]]\"\n\n[typing fixtures/typing-medium.pyi]\n[case testConditionalAssertWithoutElse]\nimport typing\n\nclass A: pass\nclass B(A): pass\n\nx = A()\nreveal_type(x)  # N: Revealed type is \"__main__.A\"\n\nif typing.TYPE_CHECKING:\n    assert isinstance(x, B)\n    reveal_type(x)  # N: Revealed type is \"__main__.B\"\n\nreveal_type(x)  # N: Revealed type is \"__main__.B\"\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testUnreachableWhenSuperclassIsAny]\nfrom typing import Any\n\n# This can happen if we're importing a class from a missing module\nParent: Any\nclass Child(Parent):\n    def foo(self) -> int:\n        reveal_type(self)       # N: Revealed type is \"__main__.Child\"\n        if self is None:\n            reveal_type(self)\n            return None\n        reveal_type(self)       # N: Revealed type is \"__main__.Child\"\n        return 3\n\n    def bar(self) -> int:\n        if 1:\n            self = super(Child, self).something()\n            reveal_type(self)       # N: Revealed type is \"__main__.Child\"\n            if self is None:\n                reveal_type(self)\n                return None\n            reveal_type(self)       # N: Revealed type is \"__main__.Child\"\n            return 3\n[builtins fixtures/isinstance.pyi]\n\n[case testUnreachableWhenSuperclassIsAnyNoStrictOptional]\n# flags: --no-strict-optional\nfrom typing import Any\n\nParent: Any\nclass Child(Parent):\n    def foo(self) -> int:\n        reveal_type(self)       # N: Revealed type is \"__main__.Child\"\n        if self is None:\n            reveal_type(self)   # N: Revealed type is \"None\"\n            return None\n        reveal_type(self)       # N: Revealed type is \"__main__.Child\"\n        return 3\n[builtins fixtures/isinstance.pyi]\n\n[case testUnreachableAfterToplevelAssert]\nimport sys\nreveal_type(0)  # N: Revealed type is \"Literal[0]?\"\nassert sys.platform == 'lol'\nreveal_type('')  # No error here :-)\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableAfterToplevelAssert2]\nimport sys\nreveal_type(0)  # N: Revealed type is \"Literal[0]?\"\nassert sys.version_info[0] == 1\nreveal_type('')  # No error here :-)\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableAfterToplevelAssert3]\nreveal_type(0)  # N: Revealed type is \"Literal[0]?\"\nMYPY = False\nassert not MYPY\nreveal_type('')  # No error here :-)\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableAfterToplevelAssert4]\n# flags: --always-false NOPE\nreveal_type(0)  # N: Revealed type is \"Literal[0]?\"\nNOPE = False\nassert NOPE\nreveal_type('')  # No error here :-)\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableAfterToplevelAssertImport]\nimport foo\nfoo.bar()  # E: \"object\" has no attribute \"bar\"\n[file foo.py]\nimport sys\nassert sys.platform == 'lol'\ndef bar() -> None: pass\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableAfterToplevelAssertImport2]\n# flags: --platform lol\nimport foo\nfoo.bar()  # No error :-)\n[file foo.py]\nimport sys\nassert sys.platform == 'lol'\ndef bar() -> None: pass\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableAfterToplevelAssertNotInsideIf]\nimport sys\nif sys.version_info[0] >= 2:\n    assert sys.platform == 'lol'\n    reveal_type('')  # N: Revealed type is \"Literal['']?\"\nreveal_type('')  # N: Revealed type is \"Literal['']?\"\n[builtins fixtures/ops.pyi]\n\n[case testUnreachableFlagWithBadControlFlow1]\n# flags: --warn-unreachable\na: int\nif isinstance(a, int):\n    reveal_type(a)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(a)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableFlagWithBadControlFlow2]\n# flags: --warn-unreachable\nb: int\nwhile isinstance(b, int):\n    reveal_type(b)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(b)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableFlagWithBadControlFlow3]\n# flags: --warn-unreachable\ndef foo(c: int) -> None:\n    reveal_type(c)  # N: Revealed type is \"builtins.int\"\n    assert not isinstance(c, int)\n    reveal_type(c)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableFlagWithBadControlFlow4]\n# flags: --warn-unreachable\nd: int\nif False:\n    reveal_type(d)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableFlagWithBadControlFlow5]\n# flags: --warn-unreachable\ne: int\nif True:\n    reveal_type(e)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(e)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableFlagStatementAfterReturn]\n# flags: --warn-unreachable\ndef foo(x: int) -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    return\n    reveal_type(x)  # E: Statement is unreachable\n\n[case testUnreachableFlagTryBlocks]\n# flags: --warn-unreachable\n\ndef foo(x: int) -> int:\n    try:\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n        return x\n        reveal_type(x)      # E: Statement is unreachable\n    finally:\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n        if True:\n            reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        else:\n            reveal_type(x)  # E: Statement is unreachable\n\ndef bar(x: int) -> int:\n    try:\n        if True:\n            raise Exception()\n        reveal_type(x)      # E: Statement is unreachable\n    except:\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n        return x\n    else:\n        reveal_type(x)      # E: Statement is unreachable\n\ndef baz(x: int) -> int:\n    try:\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n    except:\n        # Mypy assumes all lines could throw an exception\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n        return x\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.int\"\n        return x\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableFlagIgnoresSemanticAnalysisUnreachable]\n# flags: --warn-unreachable --python-version 3.8 --platform win32 --always-false FOOBAR\nimport sys\nfrom typing import TYPE_CHECKING\n\nx: int\nif TYPE_CHECKING:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)\n\nif not TYPE_CHECKING:\n    reveal_type(x)\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif sys.platform == 'darwin':\n    reveal_type(x)\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif sys.platform == 'win32':\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)\n\nif sys.version_info == (2, 7):\n    reveal_type(x)\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nif sys.version_info == (3, 8):\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)\n\nFOOBAR = \"\"\nif FOOBAR:\n    reveal_type(x)\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/ops.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testUnreachableFlagIgnoresSemanticAnalysisExprUnreachable]\n# flags: --warn-unreachable --always-false FOOBAR\nimport sys\nfrom typing import TYPE_CHECKING\n\nFOOBAR = \"\"\n\ndef foo() -> bool: ...\n\nlst = [1, 2, 3]\n\na = FOOBAR and foo()\nb = (not FOOBAR) or foo()\nc = 1 if FOOBAR else 2\nd = [x for x in lst if FOOBAR]\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testUnreachableFlagOkWithDeadStatements]\n# flags: --warn-unreachable\nfrom typing import NoReturn\ndef assert_never(x: NoReturn) -> NoReturn:\n    assert False\n\ndef nonthrowing_assert_never(x: NoReturn) -> None: ...\n\ndef expect_str(x: str) -> str: pass\n\nx: int\nif False:\n    assert False\n    reveal_type(x)  # E: Statement is unreachable\n\nif False:\n    raise Exception()\n    reveal_type(x)  # E: Statement is unreachable\n\nif False:\n    assert_never(x)\n    reveal_type(x)  # E: Statement is unreachable\n\nif False:\n    nonthrowing_assert_never(x)  # E: Statement is unreachable\n    reveal_type(x)\n\nif False:\n    # Ignore obvious type errors\n    assert_never(expect_str(x))\n    reveal_type(x)  # E: Statement is unreachable\n[builtins fixtures/exception.pyi]\n\n[case testNeverVariants]\nfrom typing import Never\nfrom typing_extensions import Never as TENever\nfrom typing import NoReturn\nfrom typing_extensions import NoReturn as TENoReturn\nfrom mypy_extensions import NoReturn as MENoReturn\n\nbottom1: Never\nreveal_type(bottom1)  # N: Revealed type is \"Never\"\nbottom2: TENever\nreveal_type(bottom2)  # N: Revealed type is \"Never\"\nbottom3: NoReturn\nreveal_type(bottom3)  # N: Revealed type is \"Never\"\nbottom4: TENoReturn\nreveal_type(bottom4)  # N: Revealed type is \"Never\"\nbottom5: MENoReturn\nreveal_type(bottom5)  # N: Revealed type is \"Never\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableFlagExpressions]\n# flags: --warn-unreachable\ndef foo() -> bool: ...\n\nlst = [1, 2, 3, 4]\n\na = True or foo()                        # E: Right operand of \"or\" is never evaluated\nb = 42 or False                          # E: Right operand of \"or\" is never evaluated\nd = False and foo()                      # E: Right operand of \"and\" is never evaluated\ne = True or (True or (True or foo()))    # E: Right operand of \"or\" is never evaluated\nf = (True or foo()) or (True or foo())   # E: Right operand of \"or\" is never evaluated  # E: Right operand of \"or\" is never evaluated\n\nk = [x for x in lst if isinstance(x, int) or foo()]  # E: Right operand of \"or\" is never evaluated\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableFlagMiscTestCaseMissingMethod]\n# flags: --warn-unreachable\n\nclass Case1:\n    def test1(self) -> bool:\n        return False and self.missing()  # E: Right operand of \"and\" is never evaluated\n\n    def test2(self) -> bool:\n        return not self.property_decorator_missing and self.missing()  # E: Function \"property_decorator_missing\" could always be true in boolean context \\\n            # E: Right operand of \"and\" is never evaluated\n\n    def property_decorator_missing(self) -> bool:\n        return True\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableFlagWithGenerics]\n# flags: --warn-unreachable\nfrom typing import TypeVar, Generic\n\nT1 = TypeVar('T1', bound=int)\nT2 = TypeVar('T2', int, str)\nT3 = TypeVar('T3', None, str)\n\ndef test1(x: T1) -> T1:\n    if isinstance(x, int):\n        reveal_type(x)  # N: Revealed type is \"T1`-1\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n    return x\n\ndef test2(x: T2) -> T2:\n    if isinstance(x, int):\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\n    if False:\n        # This is unreachable, but we don't report an error, unfortunately.\n        # The presence of the TypeVar with values unfortunately currently shuts\n        # down type-checking for this entire function.\n        # TODO: Find a way of removing this limitation\n        reveal_type(x)\n\n    return x\n\nclass Test3(Generic[T2]):\n    x: T2\n\n    def func(self) -> None:\n        if isinstance(self.x, int):\n            reveal_type(self.x)  # N: Revealed type is \"builtins.int\"\n        else:\n            reveal_type(self.x)  # N: Revealed type is \"builtins.str\"\n\n        if False:\n            # Same issue as above\n            reveal_type(self.x)\n\n\nclass Test4(Generic[T3]):\n    def __init__(self, x: T3):\n        # https://github.com/python/mypy/issues/9456\n        # On TypeVars with value restrictions, we currently have no way\n        # of checking a statement for all the type expansions.\n        # Thus unreachable warnings are disabled\n        if x and False:\n            pass\n        # This test should fail after this limitation is removed.\n        if False and x:\n            pass\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableBlockStaysUnreachableWithTypeVarConstraints]\n# flags: --always-false COMPILE_TIME_FALSE\nfrom typing import TypeVar\nCOMPILE_TIME_FALSE = False\nT = TypeVar(\"T\", int, str)\ndef foo(x: T) -> T:\n    if COMPILE_TIME_FALSE:\n        return \"bad\"\n    return x\n\n[case testUnreachableFlagContextManagersNoSuppress]\n# flags: --warn-unreachable\nfrom contextlib import contextmanager\nfrom typing import Optional, Iterator, Any\nfrom typing_extensions import Literal\nclass DoesNotSuppress1:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Optional[bool]: ...\n\nclass DoesNotSuppress2:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Literal[False]: ...\n\nclass DoesNotSuppress3:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Any: ...\n\nclass DoesNotSuppress4:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> None: ...\n\n@contextmanager\ndef simple() -> Iterator[int]:\n    yield 3\n\ndef cond() -> bool: ...\n\ndef noop() -> None: ...\n\ndef f_no_suppress_1a() -> int:\n    with DoesNotSuppress1():\n        return 3\n    noop()              # E: Statement is unreachable\n\ndef f_no_suppress_1b() -> int:\n    with DoesNotSuppress1():\n        if cond():\n            return 3\n        else:\n            return 3\n    noop()                  # E: Statement is unreachable\n\ndef f_no_suppress_2() -> int:\n    with DoesNotSuppress2():\n        return 3\n    noop()                  # E: Statement is unreachable\n\ndef f_no_suppress_3() -> int:\n    with DoesNotSuppress3():\n        return 3\n    noop()                  # E: Statement is unreachable\n\ndef f_no_suppress_4() -> int:\n    with DoesNotSuppress4():\n        return 3\n    noop()                  # E: Statement is unreachable\n\ndef f_no_suppress_5() -> int:\n    with simple():\n        return 3\n    noop()                  # E: Statement is unreachable\n\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableFlagContextManagersSuppressed]\n# flags: --warn-unreachable\nfrom contextlib import contextmanager\nfrom typing import Optional, Iterator, Any\nfrom typing_extensions import Literal\n\nclass DoesNotSuppress:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Optional[bool]: ...\n\nclass Suppresses1:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> bool: ...\n\nclass Suppresses2:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Literal[True]: ...\n\ndef cond() -> bool: ...\n\ndef noop() -> None: ...\n\ndef f_suppress_1a() -> int:  # E: Missing return statement\n    with Suppresses1():\n        return 3\n    noop()\n\ndef f_suppress_1b() -> int:  # E: Missing return statement\n    with Suppresses1():\n        if cond():\n            return 3\n        else:\n            return 3\n    noop()\n\ndef f_suppress_2() -> int:  # E: Missing return statement\n    with Suppresses2():\n        return 3\n    noop()\n\ndef f_mix() -> int:         # E: Missing return statement\n    with DoesNotSuppress(), Suppresses1(), DoesNotSuppress():\n        return 3\n    noop()\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableFlagContextManagersSuppressedNoStrictOptional]\n# flags: --warn-unreachable --no-strict-optional\nfrom contextlib import contextmanager\nfrom typing import Optional, Iterator, Any\nfrom typing_extensions import Literal\n\nclass DoesNotSuppress1:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Optional[bool]: ...\n\n# Normally, this should suppress. But when strict-optional mode is disabled, we can't\n# necessarily distinguish between bool and Optional[bool]. So we default to assuming\n# no suppression, since that's what most context managers will do.\nclass DoesNotSuppress2:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> bool: ...\n\n# But if we see Literal[True], it's pretty unlikely the return type is actually meant to\n# be 'Optional[Literal[True]]'. So, we optimistically assume this is meant to be suppressing.\nclass Suppresses:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> Literal[True]: ...\n\ndef noop() -> None: ...\n\ndef f_no_suppress_1() -> int:\n    with DoesNotSuppress1():\n        return 3\n    noop()  # E: Statement is unreachable\n\ndef f_no_suppress_2() -> int:\n    with DoesNotSuppress1():\n        return 3\n    noop()  # E: Statement is unreachable\n\ndef f_suppress() -> int:  # E: Missing return statement\n    with Suppresses():\n        return 3\n    noop()\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableFlagContextAsyncManagersNoSuppress]\n# flags: --warn-unreachable\nfrom contextlib import asynccontextmanager\nfrom typing import Optional, AsyncIterator, Any\nfrom typing_extensions import Literal\n\nclass DoesNotSuppress1:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> Optional[bool]: ...\n\nclass DoesNotSuppress2:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> Literal[False]: ...\n\nclass DoesNotSuppress3:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> Any: ...\n\nclass DoesNotSuppress4:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> None: ...\n\n@asynccontextmanager\nasync def simple() -> AsyncIterator[int]:\n    yield 3\n\ndef cond() -> bool: ...\n\ndef noop() -> None: ...\n\nasync def f_no_suppress_1a() -> int:\n    async with DoesNotSuppress1():\n        return 3\n    noop()              # E: Statement is unreachable\n\nasync def f_no_suppress_1b() -> int:\n    async with DoesNotSuppress1():\n        if cond():\n            return 3\n        else:\n            return 3\n    noop()                  # E: Statement is unreachable\n\nasync def f_no_suppress_2() -> int:\n    async with DoesNotSuppress2():\n        return 3\n    noop()                  # E: Statement is unreachable\n\nasync def f_no_suppress_3() -> int:\n    async with DoesNotSuppress3():\n        return 3\n    noop()                  # E: Statement is unreachable\n\nasync def f_no_suppress_4() -> int:\n    async with DoesNotSuppress4():\n        return 3\n    noop()                  # E: Statement is unreachable\n\nasync def f_no_suppress_5() -> int:\n    async with simple():\n        return 3\n    noop()                  # E: Statement is unreachable\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableFlagContextAsyncManagersSuppressed]\n# flags: --warn-unreachable\nfrom contextlib import asynccontextmanager\nfrom typing import Optional, AsyncIterator, Any\nfrom typing_extensions import Literal\n\nclass DoesNotSuppress:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> Optional[bool]: ...\n\nclass Suppresses1:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> bool: ...\n\nclass Suppresses2:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> Literal[True]: ...\n\ndef cond() -> bool: ...\n\ndef noop() -> None: ...\n\nasync def f_suppress_1() -> int:  # E: Missing return statement\n    async with Suppresses1():\n        return 3\n    noop()\n\nasync def f_suppress_2() -> int:  # E: Missing return statement\n    async with Suppresses1():\n        if cond():\n            return 3\n        else:\n            return 3\n    noop()\n\nasync def f_suppress_3() -> int:  # E: Missing return statement\n    async with Suppresses2():\n        return 3\n    noop()\n\nasync def f_mix() -> int:         # E: Missing return statement\n    async with DoesNotSuppress(), Suppresses1(), DoesNotSuppress():\n        return 3\n    noop()\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableFlagContextAsyncManagersAbnormal]\n# flags: --warn-unreachable\nfrom contextlib import asynccontextmanager\nfrom typing import Optional, AsyncIterator, Any\nfrom typing_extensions import Literal\n\nclass RegularManager:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> bool: ...\n\nclass AsyncManager:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> bool: ...\n\ndef noop() -> None: ...\n\nasync def f_bad_1() -> int:\n    async with RegularManager():  # E: \"RegularManager\" has no attribute \"__aenter__\"; maybe \"__enter__\"? \\\n                                  # E: \"RegularManager\" has no attribute \"__aexit__\"; maybe \"__exit__\"?\n        return 3\n    noop()                        # E: Statement is unreachable\n\ndef f_bad_2() -> int:\n    with AsyncManager():  # E: \"AsyncManager\" has no attribute \"__enter__\"; maybe \"__aenter__\"? \\\n                          # E: \"AsyncManager\" has no attribute \"__exit__\"; maybe \"__aexit__\"?\n        return 3\n    noop()                # E: Statement is unreachable\n\n# TODO: We should consider reporting an error when the user tries using\n# context manager with malformed signatures instead of silently continuing.\n\nclass RegularManagerMalformedSignature:\n    def __enter__(self) -> int: ...\n    def __exit__(self, exctype: object, excvalue: object, traceback: object) -> object: ...\n\nclass AsyncManagerMalformedSignature:\n    async def __aenter__(self) -> int: ...\n    async def __aexit__(self, exctype: object, excvalue: object, traceback: object) -> object: ...\n\ndef f_malformed_1() -> int:\n    with RegularManagerMalformedSignature():\n        return 3\n    noop()                  # E: Statement is unreachable\n\nasync def f_malformed_2() -> int:\n    async with AsyncManagerMalformedSignature():\n        return 3\n    noop()                  # E: Statement is unreachable\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testUnreachableUntypedFunction]\n# flags: --warn-unreachable\n\ndef test_untyped_fn(obj):\n    assert obj.prop is True\n\n    obj.update(prop=False)\n    obj.reload()\n\n    assert obj.prop is False\n    reveal_type(obj.prop)\n\ndef test_typed_fn(obj) -> None:\n    assert obj.prop is True\n\n    obj.update(prop=False)\n    obj.reload()\n\n    assert obj.prop is False\n    reveal_type(obj.prop)  # E: Statement is unreachable\n\n[case testUnreachableCheckedUntypedFunction]\n# flags: --warn-unreachable --check-untyped-defs\n\ndef test_untyped_fn(obj):\n    assert obj.prop is True\n\n    obj.update(prop=False)\n    obj.reload()\n\n    assert obj.prop is False\n    reveal_type(obj.prop)  # E: Statement is unreachable\n\n[case testConditionalTypeVarException]\n# every part of this test case was necessary to trigger the crash\nimport sys\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", int, str)\n\ndef f(t: T) -> None:\n    if sys.platform == \"lol\":\n        try:\n            pass\n        except BaseException as e:\n            pass\n[builtins fixtures/dict.pyi]\n\n\n[case testUnreachableLiteral]\n# flags: --warn-unreachable\nfrom typing_extensions import Literal\n\ndef nope() -> Literal[False]: ...\n\ndef f() -> None:\n    if nope():\n        x = 1  # E: Statement is unreachable\n[builtins fixtures/dict.pyi]\n\n[case testUnreachableLiteralFrom__bool__]\n# flags: --warn-unreachable\nfrom typing_extensions import Literal\n\nclass Truth:\n    def __bool__(self) -> Literal[True]: ...\n\nclass Lie:\n    def __bool__(self) -> Literal[False]: ...\n\nclass Maybe:\n    def __bool__(self) -> Literal[True | False]: ...\n\nt = Truth()\nif t:\n    x = 1\nelse:\n    x = 2  # E: Statement is unreachable\n\nif Lie():\n    x = 3  # E: Statement is unreachable\n\nif Maybe():\n    x = 4\n\n\ndef foo() -> bool: ...\n\ny = Truth() or foo()  # E: Right operand of \"or\" is never evaluated\nz = Lie() and foo()  # E: Right operand of \"and\" is never evaluated\n[builtins fixtures/dict.pyi]\n\n[case testUnreachableModuleBody1]\n# flags: --warn-unreachable\nfrom typing import NoReturn\ndef foo() -> NoReturn:\n    raise Exception(\"foo\")\nfoo()\nx = 1  # E: Statement is unreachable\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableModuleBody2]\n# flags: --warn-unreachable\nraise Exception\nx = 1  # E: Statement is unreachable\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableNoReturnBinaryOps]\n# flags: --warn-unreachable\nfrom typing import NoReturn\n\na: NoReturn\na and 1  # E: Right operand of \"and\" is never evaluated\na or 1  # E: Right operand of \"or\" is never evaluated\na or a  # E: Right operand of \"or\" is never evaluated\n1 and a and 1  # E: Right operand of \"and\" is never evaluated\na and a  # E: Right operand of \"and\" is never evaluated\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableFlagWithTerminalBranchInDeferredNode]\n# flags: --warn-unreachable\nfrom typing import NoReturn\n\ndef assert_never(x: NoReturn) -> NoReturn: ...\n\ndef force_forward_ref() -> int:\n    return 4\n\ndef f(value: None) -> None:\n    x\n    if value is not None:\n        assert_never(value)\n\nx = force_forward_ref()\n[builtins fixtures/exception.pyi]\n\n[case testSetitemNoReturn]\n# flags: --warn-unreachable\nfrom typing import NoReturn\nclass Foo:\n    def __setitem__(self, key: str, value: str) -> NoReturn:\n        raise Exception\nFoo()['a'] = 'a'\nx = 0  # E: Statement is unreachable\n[builtins fixtures/exception.pyi]\n\n[case TestNoImplicNoReturnFromError]\n# flags: --warn-unreachable\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\nclass Foo:\n    def __setitem__(self, key: str, value: str) -> T:  # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n        raise Exception\n\ndef f() -> None:\n    Foo()['a'] = 'a'\n    x = 0 # This should not be reported as unreachable\n[builtins fixtures/exception.pyi]\n\n[case testIntentionallyEmptyGeneratorFunction]\n# flags: --warn-unreachable\nfrom typing import Generator\n\ndef f() -> Generator[None, None, None]:\n    return\n    yield\n\n[case testIntentionallyEmptyGeneratorFunction_None]\n# flags: --warn-unreachable\nfrom typing import Generator\n\ndef f() -> Generator[None, None, None]:\n    return None\n    yield None\n\n[case testLambdaNoReturn]\n# flags: --warn-unreachable\nfrom typing import Callable, NoReturn\n\ndef foo() -> NoReturn:\n    raise\n\nf1 = lambda: foo()\nx = 0  # not unreachable\n\nf2: Callable[[], NoReturn] = lambda: foo()\nx = 0  # not unreachable\n"
  },
  {
    "path": "test-data/unit/check-unsupported.test",
    "content": "-- Tests for unsupported features\n\n\n[case testDecorateOverloadedFunction]\nfrom foo import *\n[file foo.pyi]\n# The error messages are not the most informative ever.\ndef d(x): pass\n@d\ndef f(): pass\ndef f(x): pass # E\ndef g(): pass\n@d # E\ndef g(x): pass\n[out]\ntmp/foo.pyi:5: error: Name \"f\" already defined on line 3\ntmp/foo.pyi:7: error: Name \"g\" already defined on line 6\n"
  },
  {
    "path": "test-data/unit/check-varargs.test",
    "content": "-- Test cases for the type checker related to varargs.\n\n\n-- Varargs within body\n-- -------------------\n\n\n[case testVarArgsWithinFunction]\nfrom typing import Tuple\ndef f( *b: 'B') -> None:\n    ab: Tuple[B, ...]\n    ac: Tuple[C, ...]\n    if int():\n        b = ac # E: Incompatible types in assignment (expression has type \"Tuple[C, ...]\", variable has type \"Tuple[B, ...]\")\n        ac = b # E: Incompatible types in assignment (expression has type \"Tuple[B, ...]\", variable has type \"Tuple[C, ...]\")\n        b = ab\n        ab = b\n\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n[case testVarArgsAreTuple]\nfrom typing import Tuple, Sequence\ndef want_tuple(types: Tuple[type, ...]): pass\ndef want_sequence(types: Sequence[type]): pass\ndef test(*t: type) -> None:\n    want_tuple(t)\n    want_sequence(t)\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n-- Calling varargs function\n-- ------------------------\n\n\n[case testCallingVarArgsFunction]\ndef f( *a: 'A') -> None: pass\n\ndef g() -> None: pass\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\na: A\nb: B\nc: C\n\nf(c)       # E: Argument 1 to \"f\" has incompatible type \"C\"; expected \"A\"\nf(a, b, c) # E: Argument 3 to \"f\" has incompatible type \"C\"; expected \"A\"\nf(g())     # E: \"g\" does not return a value (it only ever returns None) \\\n           # E: Argument 1 to \"f\" has incompatible type \"None\"; expected \"A\"\nf(a, g())  # E: \"g\" does not return a value (it only ever returns None) \\\n           # E: Argument 2 to \"f\" has incompatible type \"None\"; expected \"A\"\nf()\nf(a)\nf(b)\nf(a, b, a, b)\n[builtins fixtures/list.pyi]\n\n[case testCallingVarArgsFunctionWithAlsoNormalArgs]\ndef f(a: 'C', *b: 'A') -> None: pass\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\na: A\nb: B\nc: C\n\nf(a)       # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"C\"\nf(c, c)    # E: Argument 2 to \"f\" has incompatible type \"C\"; expected \"A\"\nf(c, a, b, c)  # E: Argument 4 to \"f\" has incompatible type \"C\"; expected \"A\"\nf(c)\nf(c, a)\nf(c, b, b, a, b)\n[builtins fixtures/list.pyi]\n\n[case testCallingVarArgsFunctionWithDefaultArgs]\n# flags: --implicit-optional --no-strict-optional\ndef f(a: 'C' = None, *b: 'A') -> None:\n    pass\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\na: A\nb: B\nc: C\n\nf(a)           # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"Optional[C]\"\nf(c, c)        # E: Argument 2 to \"f\" has incompatible type \"C\"; expected \"A\"\nf(c, a, b, c)  # E: Argument 4 to \"f\" has incompatible type \"C\"; expected \"A\"\nf()\nf(c)\nf(c, a)\nf(c, b, b, a, b)\n[builtins fixtures/list.pyi]\n\n[case testCallVarargsFunctionWithIterable]\nfrom typing import Iterable\nit1: Iterable[int]\nit2: Iterable[str]\ndef f(*x: int) -> None: pass\nf(*it1)\nf(*it2) # E: Argument 1 to \"f\" has incompatible type \"*Iterable[str]\"; expected \"int\"\n[builtins fixtures/for.pyi]\n\n[case testCallVarargsFunctionWithTwoTupleStarArgs]\nfrom typing import TypeVar, Tuple\n\nT1 = TypeVar('T1')\nT2 = TypeVar('T2')\nT3 = TypeVar('T3')\nT4 = TypeVar('T4')\n\ndef f(a: T1, b: T2, c: T3, d: T4) -> Tuple[T1, T2, T3, T4]: ...\nx: Tuple[int, str]\ny: Tuple[float, bool]\nreveal_type(f(*x, *y)) # N: Revealed type is \"Tuple[builtins.int, builtins.str, builtins.float, builtins.bool]\"\n[builtins fixtures/list.pyi]\n\n[case testCallVarargsFunctionWithIterableAndPositional]\n\nfrom typing import Iterable\nit1: Iterable[int]\ndef f(*x: int) -> None: pass\nf(*it1, 1, 2)\nf(*it1, 1, *it1, 2)\nf(*it1, '') # E: Argument 2 to \"f\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/for.pyi]\n\n[case testCallVarargsFunctionWithTupleAndPositional]\n\ndef f(*x: int) -> None: pass\nit1 = (1, 2)\nit2 = ('',)\nf(*it1, 1, 2)\nf(*it1, 1, *it1, 2)\nf(*it1, 1, *it2, 2)  # E: Argument 3 to \"f\" has incompatible type \"*Tuple[str]\"; expected \"int\"\nf(*it1, '') # E: Argument 2 to \"f\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/for.pyi]\n\n\n-- Calling varargs function + type inference\n-- -----------------------------------------\n\n\n[case testTypeInferenceWithCalleeVarArgs]\nfrom typing import TypeVar\nT = TypeVar('T')\n\ndef f( *a: T) -> T:\n    pass\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\na: A\nb: B\nc: C\no: object\n\nif int():\n    a = f(o) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nif int():\n    b = f(b, a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = f(a, b) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    o = f()\nif int():\n    a = f(a)\nif int():\n    a = f(b)\nif int():\n    a = f(a, b, a)\nif int():\n    o = f(a, b, o)\nif int():\n    c = f(c)\n[builtins fixtures/list.pyi]\n\n[case testTypeInferenceWithCalleeVarArgsAndDefaultArgs]\n# flags: --no-strict-optional\nfrom typing import TypeVar\nT = TypeVar('T')\na: A\no: object\n\ndef f(a: T, b: T = None, *c: T) -> T:\n    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 = f(a, o) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nif int():\n    a = f(a, a, o) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nif int():\n    a = f(a, a, a, o) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n\nif int():\n    a = f(a)\nif int():\n    a = f(a, a)\nif int():\n    a = f(a, a, a)\n[builtins fixtures/list.pyi]\n\n\n-- Calling normal function with varargs\n-- ------------------------------------\n\n\n[case testCallingWithListVarArgs]\nfrom typing import List, Any, cast\n\ndef f(a: 'A', b: 'B') -> None:\n    pass\n\nclass A: pass\nclass B: pass\n\naa: List[A]\nab: List[B]\na: A\nb: B\n\nf(*aa)  # E: Argument 1 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nf(a, *ab) # Ok\nf(a, b)\n(cast(Any, f))(*aa)     # IDEA: Move to check-dynamic?\n(cast(Any, f))(a, *ab)  # IDEA: Move to check-dynamic?\n[builtins fixtures/list.pyi]\n[case testCallingWithTupleVarArgs]\ndef f(a: 'A', b: 'B', c: 'C') -> None: pass\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass CC(C): pass\n\na: A\nb: B\nc: C\ncc: CC\n\nf(*(a, b, b)) # E: Argument 1 to \"f\" has incompatible type \"*Tuple[A, B, B]\"; expected \"C\"\nf(*(b, b, c)) # E: Argument 1 to \"f\" has incompatible type \"*Tuple[B, B, C]\"; expected \"A\"\nf(a, *(b, b)) # E: Argument 2 to \"f\" has incompatible type \"*Tuple[B, B]\"; expected \"C\"\nf(b, *(b, c)) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(*(a, b))    # E: Missing positional arguments \"b\", \"c\" in call to \"f\"\nf(*(a, b, c, c)) # E: Too many arguments for \"f\"\nf(a, *(b, c, c)) # E: Too many arguments for \"f\"\nf(*(a, b, c))\nf(a, *(b, c))\nf(a, b, *(c,))\nf(a, *(b, cc))\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidVarArg]\ndef f(a: 'A') -> None:\n    pass\n\nclass A: pass\n\na = A()\n\nf(*None)  # E: Expected iterable as variadic argument\nf(*a)    # E: Expected iterable as variadic argument\nf(*(a,))\n\nf(*4)  # E: Expected iterable as variadic argument\nf(a, *4)  # E: Expected iterable as variadic argument\n[builtins fixtures/tuple.pyi]\n\n\n-- Calling varargs function with varargs\n-- -------------------------------------\n\n\n[case testCallingVarArgsFunctionWithListVarArgs]\nfrom typing import List\n\ndef f(a: 'A', *b: 'B') -> None: pass\ndef g(a: 'A', *b: 'A') -> None: pass\nclass A: pass\nclass B: pass\n\naa: List[A]\nab: List[B]\na: A\nb: B\nf(*aa)           # E: Argument 1 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nf(a, *aa)        # E: Argument 2 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nf(b, *ab)        # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(a, a, *ab)     # E: Argument 2 to \"f\" has incompatible type \"A\"; expected \"B\"\nf(a, b, *aa)     # E: Argument 3 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nf(b, b, *ab)     # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\ng(*ab)           # E: Argument 1 to \"g\" has incompatible type \"*List[B]\"; expected \"A\"\nf(a, *ab)\nf(a, b, *ab)\nf(a, b, b, *ab)\ng(*aa)\n[builtins fixtures/list.pyi]\n[case testCallingVarArgsFunctionWithTupleVarArgs]\ndef f(a: 'A', *b: 'B') -> None:\n    pass\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass CC(C): pass\n\na: A\nb: B\nc: C\ncc: CC\n\nf(*(b, b, b))   # E: Argument 1 to \"f\" has incompatible type \"*Tuple[B, B, B]\"; expected \"A\"\nf(*(a, a, b))   # E: Argument 1 to \"f\" has incompatible type \"*Tuple[A, A, B]\"; expected \"B\"\nf(*(a, b, a))   # E: Argument 1 to \"f\" has incompatible type \"*Tuple[A, B, A]\"; expected \"B\"\nf(a, *(a, b))   # E: Argument 2 to \"f\" has incompatible type \"*Tuple[A, B]\"; expected \"B\"\nf(b, *(b, b))   # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(b, b, *(b,))  # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(a, a, *(b,))  # E: Argument 2 to \"f\" has incompatible type \"A\"; expected \"B\"\nf(a, b, *(a,))  # E: Argument 3 to \"f\" has incompatible type \"*Tuple[A]\"; expected \"B\"\nf(*())          # E: Too few arguments for \"f\"\nf(*(a, b, b))\nf(a, *(b, b))\nf(a, b, *(b,))\n[builtins fixtures/list.pyi]\n\n\n-- Varargs special cases\n-- ---------------------\n\n\n[case testDynamicVarArg]\nfrom typing import Any\ndef f(a: 'A') -> None: pass\ndef g(a: 'A', *b: 'A') -> None: pass\nclass A: pass\n\nd: Any\na: A\nf(a, a, *d) # E: Too many arguments for \"f\"\nf(a, *d)    # Ok\nf(*d)       # Ok\n\ng(*d)\ng(a, *d)\ng(a, a, *d)\n[builtins fixtures/list.pyi]\n\n[case testListVarArgsAndSubtyping]\nfrom typing import List\ndef f( *a: 'A') -> None:\n    pass\n\ndef g( *a: 'B') -> None:\n    pass\n\nclass A: pass\nclass B(A): pass\n\naa: List[A]\nab: List[B]\n\ng(*aa) # E: Argument 1 to \"g\" has incompatible type \"*List[A]\"; expected \"B\"\nf(*aa)\nf(*ab)\ng(*ab)\n[builtins fixtures/list.pyi]\n\n[case testCallerVarArgsAndDefaultArgs]\n# flags: --implicit-optional --no-strict-optional\n\ndef f(a: 'A', b: 'B' = None, *c: 'B') -> None:\n    pass\n\nclass A: pass\nclass B: pass\n\na, b = A(), B() # type: (A, B)\nf(*())        # E: Too few arguments for \"f\"\nf(a, *[a])    # E: Argument 2 to \"f\" has incompatible type \"*List[A]\"; expected \"Optional[B]\" \\\n              # E: Argument 2 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nf(a, b, *[a]) # E: Argument 3 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nf(*(a, a, b)) # E: Argument 1 to \"f\" has incompatible type \"*Tuple[A, A, B]\"; expected \"Optional[B]\"\nf(*(a,))\nf(*(a, b))\nf(*(a, b, b, b))\nf(a, *[])\nf(a, *[b])\nf(a, *[b, b])\n[builtins fixtures/list.pyi]\n\n[case testVarArgsAfterKeywordArgInCall1]\n# see: mypy issue #2729\ndef f(x: int, y: str) -> None: pass\nf(x=1, *[2])\n[builtins fixtures/list.pyi]\n[out]\nmain:3: error: \"f\" gets multiple values for keyword argument \"x\"\nmain:3: error: Argument 1 to \"f\" has incompatible type \"*List[int]\"; expected \"str\"\n\n[case testVarArgsAfterKeywordArgInCall2]\n# see: mypy issue #2729\ndef f(x: int, y: str) -> None: pass\nf(y='x', *[1])\n[builtins fixtures/list.pyi]\n[out]\nmain:3: error: \"f\" gets multiple values for keyword argument \"y\"\nmain:3: error: Argument 1 to \"f\" has incompatible type \"*List[int]\"; expected \"str\"\n\n[case testVarArgsAfterKeywordArgInCall3]\ndef f(x: int, y: str) -> None: pass\nf(y='x', *(1,))\n[builtins fixtures/list.pyi]\n\n[case testVarArgsAfterKeywordArgInCall4]\ndef f(x: int, *, y: str) -> None: pass\nf(y='x', *[1])\n[builtins fixtures/list.pyi]\n\n[case testVarArgsAfterKeywordArgInCall5]\ndef f(x: int, *, y: str) -> None: pass\nf(y='x', *(1,))\n[builtins fixtures/list.pyi]\n\n[case testVarArgsEmptyList]\nfrom typing import List\n\ndef foo() -> None:\n    pass\n\nlst: List[int] = []\nfoo(*lst)\n[builtins fixtures/list.pyi]\n\n[case testVarArgsEmptyTuple]\ndef foo() -> None:\n    pass\n\nfoo(*())\n[builtins fixtures/tuple.pyi]\n\n-- Overloads + varargs\n-- -------------------\n\n\n[case testIntersectionTypesAndVarArgs]\n# flags: --no-strict-optional\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na, b = A(), B() # type: (A, B)\n\nif int():\n    b = f()        # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = f(a)       # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = f(a, b)    # 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    a = f(b, b)    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\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(*())     # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = f(*(a,))   # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = f(*(a, b)) # 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    a = f(*(b, 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\na = f()\na = f(a)\na = f(a, b)\nb = f(b)\nb = f(b, b)\na = f(a, *[b])\na = f(*())\na = f(*(a,))\na = f(*(a, b))\nb = f(*(b,))\nb = f(*(b, b))\nb = f(*[b])\n\nclass A: pass\nclass B: pass\n\n@overload\ndef f(a: A = None, *b: B) -> A: pass\n\n@overload\ndef f(a: B, *b: B) -> B: pass\n[builtins fixtures/list.pyi]\n\n\n-- Caller varargs + type inference\n-- -------------------------------\n\n\n[case testCallerVarArgsListWithTypeInference]\nfrom typing import List, TypeVar, Tuple\nS = TypeVar('S')\nT = TypeVar('T')\n\ndef f(a: S, *b: T) -> Tuple[S, T]:\n    pass\n\nclass A: pass\nclass B: pass\n\na: A\nb: B\naa: List[A]\n\nif int():\n    a, b = f(*aa)    # E: Argument 1 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nif int():\n    b, b = f(*aa)    # E: Argument 1 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nif int():\n    a, a = f(b, *aa) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nif int():\n    b, b = f(b, *aa) # E: Argument 2 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nif int():\n    b, b = f(b, b, *aa) # E: Argument 3 to \"f\" has incompatible type \"*List[A]\"; expected \"B\"\nif int():\n    a, b = f(a, *a)  # E: Expected iterable as variadic argument\nif int():\n    a, b = f(*a)     # E: Expected iterable as variadic argument\n\nif int():\n    a, a = f(*aa)\nif int():\n    b, a = f(b, *aa)\nif int():\n    b, a = f(b, a, *aa)\n[builtins fixtures/list.pyi]\n\n[case testCallerVarArgsTupleWithTypeInference]\nfrom typing import TypeVar, Tuple\nS = TypeVar('S')\nT = TypeVar('T')\n\ndef f(a: S, b: T) -> Tuple[S, T]: pass\n\nclass A: pass\nclass B: pass\n\na: A\nb: B\n\nif int():\n    a, a = f(*(a, b))   # E: Argument 1 to \"f\" has incompatible type \"*Tuple[A, B]\"; expected \"A\"\nif int():\n    b, b = f(a, *(b,))  # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"B\"\nif int():\n    a, a = f(*(a, b))   # E: Argument 1 to \"f\" has incompatible type \"*Tuple[A, B]\"; expected \"A\"\nif int():\n    b, b = f(a, *(b,))  # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"B\"\nif int():\n    a, b = f(*(a, b, b)) # E: Too many arguments for \"f\"\nif int():\n    a, b = f(*(a, b))\nif int():\n    a, b = f(a, *(b,))\n[builtins fixtures/list.pyi]\n\n[case testCallerVarargsAndComplexTypeInference]\nfrom typing import List, TypeVar, Generic, Tuple\nT = TypeVar('T')\nS = TypeVar('S')\na: A\nb: B\nao: List[object]\naa: List[A]\nab: List[B]\n\nclass G(Generic[T]):\n    def f(self, *a: S) -> Tuple[List[S], List[T]]:\n        pass\n\nclass A: pass\nclass B: pass\n\nif int():\n    a, aa = G().f(*[a]) # E: Incompatible types in assignment (expression has type \"List[A]\", variable has type \"A\")\nif int():\n    aa, a = G().f(*[a]) # E: Incompatible types in assignment (expression has type \"List[Never]\", variable has type \"A\")\nif int():\n    ab, aa = G().f(*[a]) # E: Argument 1 to \"f\" of \"G\" has incompatible type \"*List[A]\"; expected \"B\"\nif int():\n    ao, ao = G().f(*[a])\nif int():\n    aa, aa = G().f(*[a])\n[builtins fixtures/list.pyi]\n\n[case testCallerTupleVarArgsAndGenericCalleeVarArg]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef f(*args: T) -> T: ...\nreveal_type(f(*(1, None)))  # N: Revealed type is \"Union[Literal[1]?, None]\"\nreveal_type(f(1, *(None, 1)))  # N: Revealed type is \"Union[Literal[1]?, None]\"\nreveal_type(f(1, *(1, None)))  # N: Revealed type is \"Union[builtins.int, None]\"\n[builtins fixtures/tuple.pyi]\n\n\n-- Comment signatures\n-- ------------------\n\n\n[case testVarArgsAndCommentSignature]\nimport typing\ndef f(*x): # type: (*int) -> None\n    pass\nf(1)\nf(1, 2)\nf('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\nf(1, '') # E: Argument 2 to \"f\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n\n-- Subtyping\n-- ---------\n\n\n[case testVarArgsFunctionSubtyping]\nfrom typing import Callable\nx: Callable[[int], None]\ndef f(*x: int) -> None: pass\ndef g(*x: str) -> None: pass\nx = f\nx = g # E: Incompatible types in assignment (expression has type \"Callable[[VarArg(str)], None]\", variable has type \"Callable[[int], None]\")\n[builtins fixtures/list.pyi]\n[out]\n\n\n-- Decorated method where self is implied by *args\n-- -----------------------------------------------\n\n[case testVarArgsCallableSelf]\nfrom typing import Callable\ndef cm(func) -> Callable[..., None]: pass\nclass C:\n    @cm\n    def foo(self) -> None: pass\nC().foo()\nC().foo(1)  # The decorator's return type says this should be okay\n\n[case testInvariantDictArgNote]\nfrom typing import Dict, Sequence\ndef f(x: Dict[str, Sequence[int]]) -> None: pass\ndef g(x: Dict[str, float]) -> None: pass\ndef h(x: Dict[str, int]) -> None: pass\na = {'a': [1, 2]}\nb = {'b': ['c', 'd']}\nc = {'c': 1.0}\nd = {'d': 1}\nf(a) # E: Argument 1 to \"f\" has incompatible type \"Dict[str, List[int]]\"; expected \"Dict[str, Sequence[int]]\" \\\n     # N: \"dict\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance \\\n     # N: Consider using \"Mapping\" instead, which is covariant in the value type\nf(b) # E: Argument 1 to \"f\" has incompatible type \"Dict[str, List[str]]\"; expected \"Dict[str, Sequence[int]]\"\ng(c)\ng(d) # E: Argument 1 to \"g\" has incompatible type \"Dict[str, int]\"; expected \"Dict[str, float]\" \\\n     # N: \"dict\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance \\\n     # N: Consider using \"Mapping\" instead, which is covariant in the value type\nh(c) # E: Argument 1 to \"h\" has incompatible type \"Dict[str, float]\"; expected \"Dict[str, int]\"\nh(d)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testInvariantListArgNote]\nfrom typing import List, Union\ndef f(numbers: List[Union[int, float]]) -> None: pass\na = [1, 2]\nf(a) # E: Argument 1 to \"f\" has incompatible type \"List[int]\"; expected \"List[Union[int, float]]\" \\\n     # N: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance \\\n     # N: Consider using \"Sequence\" instead, which is covariant\nx = [1]\ny = ['a']\nif int():\n    x = y # E: Incompatible types in assignment (expression has type \"List[str]\", variable has type \"List[int]\")\n[builtins fixtures/list.pyi]\n\n[case testInvariantTypeConfusingNames]\nfrom typing import TypeVar\nclass Listener: pass\nclass DictReader: pass\ndef f(x: Listener) -> None: pass\ndef g(y: DictReader) -> None: pass\na = [1, 2]\nb = {'b': 1}\nf(a) # E: Argument 1 to \"f\" has incompatible type \"List[int]\"; expected \"Listener\"\ng(b) # E: Argument 1 to \"g\" has incompatible type \"Dict[str, int]\"; expected \"DictReader\"\n[builtins fixtures/dict.pyi]\n\n[case testInvariantTypeConfusingNames2]\nfrom typing import Iterable, Generic, TypeVar, List\n\nT = TypeVar('T')\n\nclass I(Iterable[T]):\n    ...\n\nclass Bad(Generic[T]):\n    ...\n\ndef bar(*args: float) -> float:\n    ...\n\ngood1: Iterable[float]\ngood2: List[float]\ngood3: I[float]\nbad1: I[str]\nbad2: Bad[float]\nbar(*good1)\nbar(*good2)\nbar(*good3)\nbar(*bad1)  # E: Argument 1 to \"bar\" has incompatible type \"*I[str]\"; expected \"float\"\nbar(*bad2)  # E: Expected iterable as variadic argument\n[builtins fixtures/dict.pyi]\n\n-- Keyword arguments unpacking\n\n[case testUnpackKwargsReveal]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\ndef foo(arg: bool, **kwargs: Unpack[Person]) -> None: ...\n\nreveal_type(foo)  # N: Revealed type is \"def (arg: builtins.bool, **kwargs: Unpack[TypedDict('__main__.Person', {'name': builtins.str, 'age': builtins.int})])\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackOutsideOfKwargs]\nfrom typing_extensions import Unpack, TypedDict\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(x: Unpack[Person]) -> None:  # E: Unpack is only valid in a variadic position\n    ...\ndef bar(x: int, *args: Unpack[Person]) -> None:  # E: \"Person\" cannot be unpacked (must be tuple or TypeVarTuple)\n    ...\ndef baz(**kwargs: Unpack[Person]) -> None:  # OK\n    ...\n[builtins fixtures/dict.pyi]\n\n[case testUnpackWithoutTypedDict]\nfrom typing_extensions import Unpack\n\ndef foo(**kwargs: Unpack[dict]) -> None:  # E: Unpack item in ** argument must be a TypedDict\n    ...\n[builtins fixtures/dict.pyi]\n\n[case testUnpackWithDuplicateKeywords]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\ndef foo(name: str, **kwargs: Unpack[Person]) -> None:  # E: Overlap between argument names and ** TypedDict items: \"name\"\n    ...\n[builtins fixtures/dict.pyi]\n\n[case testUnpackWithDuplicateKeywordKwargs]\nfrom typing_extensions import Unpack, TypedDict\nfrom typing import Dict, List\n\nclass Spec(TypedDict):\n    args: List[int]\n    kwargs: Dict[int, int]\ndef foo(**kwargs: Unpack[Spec]) -> None:  # Allowed\n    ...\nfoo(args=[1], kwargs={\"2\": 3})  # E: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"int\": \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsNonIdentifier]\nfrom typing_extensions import Unpack, TypedDict\n\nWeird = TypedDict(\"Weird\", {\"@\": int})\n\ndef foo(**kwargs: Unpack[Weird]) -> None:\n    reveal_type(kwargs[\"@\"])  # N: Revealed type is \"builtins.int\"\nfoo(**{\"@\": 42})\nfoo(**{\"no\": \"way\"})  # E: Argument 1 to \"foo\" has incompatible type \"**Dict[str, str]\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsEmpty]\nfrom typing_extensions import Unpack, TypedDict\n\nEmpty = TypedDict(\"Empty\", {})\n\ndef foo(**kwargs: Unpack[Empty]) -> None:  # N: \"foo\" defined here\n    reveal_type(kwargs)  # N: Revealed type is \"TypedDict('__main__.Empty', {})\"\nfoo()\nfoo(x=1)  # E: Unexpected keyword argument \"x\" for \"foo\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackTypedDictTotality]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Circle(TypedDict, total=True):\n    radius: int\n    color: str\n    x: int\n    y: int\n\ndef foo(**kwargs: Unpack[Circle]):\n    ...\nfoo(x=0, y=0, color='orange')  # E: Missing named argument \"radius\" for \"foo\"\n\nclass Square(TypedDict, total=False):\n    side: int\n    color: str\n\ndef bar(**kwargs: Unpack[Square]):\n    ...\nbar(side=12)\n[builtins fixtures/dict.pyi]\n\n[case testUnpackUnexpectedKeyword]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict, total=False):\n    name: str\n    age: int\n\ndef foo(**kwargs: Unpack[Person]) -> None:  # N: \"foo\" defined here\n    ...\nfoo(name='John', age=42, department='Sales')  # E: Unexpected keyword argument \"department\" for \"foo\"\nfoo(name='Jennifer', age=38)\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKeywordTypes]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(**kwargs: Unpack[Person]):\n    ...\nfoo(name='John', age='42')  # E: Argument \"age\" to \"foo\" has incompatible type \"str\"; expected \"int\"\nfoo(name='Jennifer', age=38)\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKeywordTypesTypedDict]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\nclass LegacyPerson(TypedDict):\n    name: str\n    age: str\n\ndef foo(**kwargs: Unpack[Person]) -> None:\n    ...\nlp = LegacyPerson(name=\"test\", age=\"42\")\nfoo(**lp)  # E: Argument \"age\" to \"foo\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctionBodyWithUnpackedKwargs]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(**kwargs: Unpack[Person]) -> int:\n    name: str = kwargs['name']\n    age: str = kwargs['age']  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    department: str = kwargs['department']  # E: TypedDict \"Person\" has no key \"department\"\n    return kwargs['age']\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsOverrides]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\nclass Base:\n    def foo(self, **kwargs: Unpack[Person]) -> None: ...\nclass SubGood(Base):\n    def foo(self, *, name: str, age: int, extra: bool = False) -> None: ...\nclass SubBad(Base):\n    def foo(self, *, name: str, age: str) -> None: ...  # E: Argument 2 of \"foo\" is incompatible with supertype \"Base\"; supertype defines the argument type as \"int\" \\\n    # N: This violates the Liskov substitution principle \\\n    # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#incompatible-overrides\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsOverridesTypedDict]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\nclass PersonExtra(Person, total=False):\n    extra: bool\n\nclass Unrelated(TypedDict):\n    baz: int\n\nclass Base:\n    def foo(self, **kwargs: Unpack[Person]) -> None: ...\nclass SubGood(Base):\n    def foo(self, **kwargs: Unpack[PersonExtra]) -> None: ...\nclass SubBad(Base):\n    def foo(self, **kwargs: Unpack[Unrelated]) -> None: ...  # E: Signature of \"foo\" incompatible with supertype \"Base\" \\\n    # N:      Superclass: \\\n    # N:          def foo(*, name: str, age: int) -> None \\\n    # N:      Subclass: \\\n    # N:          def foo(self, *, baz: int) -> None\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsGeneric]\nfrom typing import Generic, TypeVar\nfrom typing_extensions import Unpack, TypedDict\n\nT = TypeVar(\"T\")\nclass Person(TypedDict, Generic[T]):\n    name: str\n    value: T\n\ndef foo(**kwargs: Unpack[Person[T]]) -> T: ...\nreveal_type(foo(name=\"test\", value=42))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsInference]\nfrom typing import Generic, TypeVar, Protocol\nfrom typing_extensions import Unpack, TypedDict\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\nclass CBPerson(Protocol[T_contra]):\n    def __call__(self, **kwargs: Unpack[Person[T_contra]]) -> None: ...\n\nT = TypeVar(\"T\")\nclass Person(TypedDict, Generic[T]):\n    name: str\n    value: T\n\ndef test(cb: CBPerson[T]) -> T: ...\n\ndef foo(*, name: str, value: int) -> None: ...\nreveal_type(test(foo))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsOverload]\nfrom typing import Any, overload\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\nclass Fruit(TypedDict):\n    sort: str\n    taste: int\n\n@overload\ndef foo(**kwargs: Unpack[Person]) -> int: ...\n@overload\ndef foo(**kwargs: Unpack[Fruit]) -> str: ...\ndef foo(**kwargs: Any) -> Any:\n    ...\n\nreveal_type(foo(sort=\"test\", taste=999))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsJoin]\nfrom typing_extensions import Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(*, name: str, age: int) -> None: ...\ndef bar(**kwargs: Unpack[Person]) -> None: ...\n\nreveal_type([foo, bar])  # N: Revealed type is \"builtins.list[def (*, name: builtins.str, age: builtins.int)]\"\nreveal_type([bar, foo])  # N: Revealed type is \"builtins.list[def (*, name: builtins.str, age: builtins.int)]\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackKwargsParamSpec]\nfrom typing import Callable, Any, TypeVar, List\nfrom typing_extensions import ParamSpec, Unpack, TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\nP = ParamSpec('P')\nT = TypeVar('T')\n\ndef dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...\n\n@dec\ndef g(**kwargs: Unpack[Person]) -> int: ...\n\nreveal_type(g)  # N: Revealed type is \"def (*, name: builtins.str, age: builtins.int) -> builtins.list[builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testUnpackGenericTypedDictImplicitAnyEnabled]\nfrom typing import Generic, TypeVar\nfrom typing_extensions import Unpack, TypedDict\n\nT = TypeVar(\"T\")\nclass TD(TypedDict, Generic[T]):\n    key: str\n    value: T\n\ndef foo(**kwds: Unpack[TD]) -> None: ...  # Same as `TD[Any]`\nfoo(key=\"yes\", value=42)\nfoo(key=\"yes\", value=\"ok\")\n[builtins fixtures/dict.pyi]\n\n[case testUnpackGenericTypedDictImplicitAnyDisabled]\n# flags: --disallow-any-generics\nfrom typing import Generic, TypeVar\nfrom typing_extensions import Unpack, TypedDict\n\nT = TypeVar(\"T\")\nclass TD(TypedDict, Generic[T]):\n    key: str\n    value: T\n\ndef foo(**kwds: Unpack[TD]) -> None: ...  # E: Missing type parameters for generic type \"TD\"\nfoo(key=\"yes\", value=42)\nfoo(key=\"yes\", value=\"ok\")\n[builtins fixtures/dict.pyi]\n\n[case testUnpackNoCrashOnEmpty]\nfrom typing_extensions import Unpack\n\nclass C:\n    def __init__(self, **kwds: Unpack) -> None: ...  # E: Unpack[...] requires exactly one type argument\nclass D:\n    def __init__(self, **kwds: Unpack[int, str]) -> None: ...  # E: Unpack[...] requires exactly one type argument\n[builtins fixtures/dict.pyi]\n\n[case testUnpackInCallableType]\nfrom typing import Callable\nfrom typing_extensions import Unpack, TypedDict\n\nclass TD(TypedDict):\n    key: str\n    value: str\n\nfoo: Callable[[Unpack[TD]], None]\nfoo(key=\"yes\", value=42)  # E: Argument \"value\" has incompatible type \"int\"; expected \"str\"\nfoo(key=\"yes\", value=\"ok\")\n\nbad: Callable[[*TD], None]  # E: \"TD\" cannot be unpacked (must be tuple or TypeVarTuple)\n[builtins fixtures/dict.pyi]\n"
  },
  {
    "path": "test-data/unit/check-warnings.test",
    "content": "-- Test cases for warning generation.\n\n-- Redundant casts\n-- ---------------\n\n[case testRedundantCast]\n# flags: --warn-redundant-casts\nfrom typing import cast\na = 1\nb = cast(str, a)\nc = cast(int, a)\n[out]\nmain:5: error: Redundant cast to \"int\"\n\n[case testRedundantCastWithIsinstance]\n# flags: --warn-redundant-casts\nfrom typing import cast, Union\nx: Union[int, str]\nif isinstance(x, str):\n    cast(str, x)\n[builtins fixtures/isinstance.pyi]\n[out]\nmain:5: error: Redundant cast to \"str\"\n\n[case testCastToSuperclassNotRedundant]\n# flags: --warn-redundant-casts\nfrom typing import cast, TypeVar, List\nT = TypeVar('T')\ndef add(xs: List[T], ys: List[T]) -> List[T]: pass\nclass A: pass\nclass B(A): pass\na = A()\nb = B()\n# Without the cast, the following line would fail to type check.\nc = add([cast(A, b)], [a])\n[builtins fixtures/list.pyi]\n\n[case testCastToAnyTypeNotRedundant]\n# flags: --warn-redundant-casts\nfrom typing import cast, Any\na: Any\nb = cast(Any, a)\n[builtins fixtures/list.pyi]\n\n-- Unused 'type: ignore' comments\n-- ------------------------------\n\n[case testUnusedTypeIgnore]\n# flags: --warn-unused-ignores\na = 1\nif int():\n    a = 'a' # type: ignore\nif int():\n    a = 2 # type: ignore # E: Unused \"type: ignore\" comment\nif int():\n    a = 'b' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testUnusedTypeIgnoreImport]\n# flags: --warn-unused-ignores\nimport banana # type: ignore\nimport m # type: ignore\nfrom m import * # type: ignore\n[file m.py]\npass\n[out]\nmain:3: error: Unused \"type: ignore\" comment\nmain:4: error: Unused \"type: ignore\" comment\n\n\n-- No return\n-- ---------\n\n[case testNoReturn]\n# flags: --warn-no-return\ndef f() -> int:\n    pass\n\ndef g() -> int:\n    if bool():\n        return 1\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: Missing return statement\n\n[case testNoReturnWhile]\n# flags: --warn-no-return\ndef h() -> int:\n    while True:\n        if bool():\n            return 1\n\ndef i() -> int:\n    while 1:\n        if bool():\n            return 1\n        if bool():\n            break\n\ndef j() -> int:\n    while 1:\n        if bool():\n            return 1\n        if bool():\n            continue\n[builtins fixtures/list.pyi]\n[out]\nmain:7: error: Missing return statement\n\n[case testNoReturnExcept]\n# flags: --warn-no-return\ndef f() -> int:\n    try:\n        return 1\n    except:\n        pass\ndef g() -> int:\n    try:\n        pass\n    except:\n        return 1\n    else:\n        return 1\ndef h() -> int:\n    try:\n        pass\n    except:\n        pass\n    else:\n        pass\n    finally:\n        return 1\n[builtins fixtures/exception.pyi]\n[out]\nmain:2: error: Missing return statement\n\n[case testNoReturnEmptyBodyWithDocstring]\ndef f() -> int:\n    \"\"\"Return the number of peppers.\"\"\"\n    # This might be an @abstractmethod, for example\n    pass\n[out]\n\n[case testNoReturnExplicitAny]\n# flags: --warn-no-return\nfrom typing import Any\nfrom unknown import Mystery  # type: ignore[import]\nfrom basedtyping import Untyped\n\ndef maybe() -> bool: ...\n\ndef implicit(x: Any):\n    if maybe():\n        return x\n\ndef explicit(x: Any) -> Any:  # E: Missing return statement\n    if maybe():\n        return x\n\ndef explicit_with_none(x: Any) -> Any:\n    if maybe():\n        return x\n    return None\n\ndef explicit_with_just_return(x: Any) -> Any:\n    if maybe():\n        return x\n    return\n\ndef mystery(x: Any) -> Mystery:\n    if maybe():\n        return x\n\ndef untyped(x: Any) -> Untyped:\n    if maybe():\n        return x\n\n-- Returning Any\n-- -------------\n\n[case testReturnAnyFromTypedFunction]\n# flags: --warn-return-any\nfrom typing import Any\ndef g() -> Any: pass\ndef f() -> int: return g()\n[out]\nmain:4: error: Returning Any from function declared to return \"int\"\n\n[case testReturnAnyForNotImplementedInBinaryMagicMethods]\n# flags: --warn-return-any\nclass A:\n    def __eq__(self, other: object) -> bool: return NotImplemented\n[builtins fixtures/notimplemented.pyi]\n[out]\n\n[case testReturnAnyForNotImplementedInNormalMethods]\n# flags: --warn-return-any\nclass A:\n    def some(self) -> bool: return NotImplemented\n[builtins fixtures/notimplemented.pyi]\n[out]\nmain:3: error: Returning Any from function declared to return \"bool\"\n\n[case testReturnAnyFromTypedFunctionWithSpecificFormatting]\n# flags: --warn-return-any\nfrom typing import Any, Tuple\ntyp = Tuple[int, int, int, int, int, int, int, int, int, int, int, int, int,\n            int, int, int, int, int, int, int, int, int, int, int, int, int,\n            int, int, int, int, int, int, int, int, int, int, int, int, int,\n            int, int, int, int, int, int, int, int, int, int, int, int, int,\n            int, int, int, int, int, int, int, int, int, int, int, int, int,\n            int, int, int, int, int, int, int, int, int, int, int, int, int,\n            int, int, int, int, int, int, int, int, int, int, int, int, int]\ndef g() -> Any: pass\ndef f() -> typ: return g()\n[builtins fixtures/tuple.pyi]\n[out]\nmain:11: error: Returning Any from function declared to return \"Tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int]\"\n\n[case testReturnAnySilencedFromTypedFunction]\n# flags: --warn-return-any\nfrom typing import Any\ndef g() -> Any: pass\ndef f() -> int:\n    result = g() # type: int\n    return result\n[out]\n\n[case testReturnAnyFromUntypedFunction]\n# flags: --warn-return-any\nfrom typing import Any\ndef g() -> Any: pass\ndef f(): return g()\n[out]\n\n[case testReturnAnyFromAnyTypedFunction]\n# flags: --warn-return-any\nfrom typing import Any\ndef g() -> Any: pass\ndef f() -> Any: return g()\n[out]\n\n[case testOKReturnAnyIfProperSubtype]\n# flags: --warn-return-any\nfrom typing import Any, Optional\n\nclass Test(object):\n\n    def __init__(self) -> None:\n        self.attr = \"foo\"  # type: Any\n\n    def foo(self, do_it: bool) -> Optional[Any]:\n        if do_it:\n            return self.attr  # Should not warn here\n        else:\n            return None\n[builtins fixtures/list.pyi]\n[out]\n\n[case testReturnAnyDeferred]\n# flags: --warn-return-any\ndef foo(a1: A) -> int:\n    if a1._x:\n        return 1\n    n = 1\n    return n\n\nclass A:\n    def __init__(self, x: int) -> None:\n        self._x = x\n"
  },
  {
    "path": "test-data/unit/cmdline-based-baseline.test",
    "content": "-- Tests for baseline\n-- ------------------------------\n-- See cmdline.test for specifics\n-- ----------------------------------------\n\n[case testWriteBaseline]\n# cmd: mypy --write-baseline --baseline-file a/b --error-summary pkg\n[file pkg/a.py]\na\n[out]\npkg/a.py:1:1: error: Name \"a\" is not defined  [name-defined]\nFound 1 error (1 new error) in 1 file (checked 1 source file)\nBaseline successfully written to a/b\n== Return code: 0\n\n\n-- TODO merge this with the first one?\n[case testWriteBaseline2-skip_path_normalization]\n# cmd: mypy --write-baseline --baseline-file a/b pkg\n[file pkg/a.py]\na\n[outfile a/b]\n{\n  \"files\": {\n    \"pkg/a.py\": [\n      {\n        \"code\": \"name-defined\",\n        \"column\": 0,\n        \"message\": \"Name \\\"a\\\" is not defined\",\n        \"offset\": 1,\n        \"src\": \"a\",\n        \"target\": \"a\"\n      }\n    ]\n  },\n  \"format\": \"1.7\",\n  \"targets\": [\n    \"file:pkg\"\n  ]\n}\n\n\n[case testRewriteBaseline]\n# cmd: mypy --write-baseline --error-summary pkg\n[file pkg/a.py]\n1 + \"\"\n\"\" + 1\n[file .mypy/baseline.json]\n{\"files\": {\"pkg/a.py\": [{\"code\": \"operator\", \"offset\": 2, \"message\": \"Unsupported operand types for + (\\\"str\\\" and \\\"int\\\")\", \"src\": \"\\\"\\\" + 1\"}]},\n\"format\": \"1.7\",\n\"targets\": [\"file:pkg\"]\n}\n[out]\npkg/a.py:1:5: error: Unsupported operand types for + (\"int\" and \"str\")  [operator]\nFound 2 errors (1 new error) in 1 file (checked 1 source file)\nBaseline successfully written to .mypy/baseline.json\n== Return code: 0\n-- TODO merge this with the first one?\n\n\n[case testRewriteBaseline2-skip_path_normalization]\n# cmd: mypy --write-baseline --error-summary pkg\n[file pkg/a.py]\n1 + \"\"\n\"\" + 1\n[file .mypy/baseline.json]\n{\"pkg/a.py\": [{\"code\": \"operator\", \"offset\": 2, \"message\": \"Unsupported operand types for + (\\\"str\\\" and \\\"int\\\")\", \"src\": \"\"}]}\n[outfile .mypy/baseline.json]\n{\n  \"files\": {\n    \"pkg/a.py\": [\n      {\n        \"code\": \"operator\",\n        \"column\": 4,\n        \"message\": \"Unsupported operand types for + (\\\"int\\\" and \\\"str\\\")\",\n        \"offset\": 1,\n        \"src\": \"1 + \\\"\\\"\",\n        \"target\": \"a\"\n      },\n      {\n        \"code\": \"operator\",\n        \"column\": 5,\n        \"message\": \"Unsupported operand types for + (\\\"str\\\" and \\\"int\\\")\",\n        \"offset\": 1,\n        \"src\": \"\\\"\\\" + 1\",\n        \"target\": \"a\"\n      }\n    ]\n  },\n  \"format\": \"1.7\",\n  \"targets\": [\n    \"file:pkg\"\n  ]\n}\n\n\n[case testRewriteEmpty]\n# cmd: mypy --write-baseline --error-summary pkg\n[file pkg/a.py]\n1 + 1\n\"\" + \"\"\n[file .mypy/baseline.json]\n{\"files\": {\"pkg/a.py\": [{\"code\": \"operator\", \"offset\": 2, \"message\": \"Unsupported operand types for + (\\\"str\\\" and \\\"int\\\")\", \"src\": \"\"}]},\n\"format\": \"1.7\",\n\"targets\": [\"file:pkg\"]\n}\n[out]\nNo errors, baseline file removed\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testRewriteNoChange]\n# cmd: mypy --write-baseline --error-summary pkg\n[file pkg/a.py]\na\n[file .mypy/baseline.json]\n{\n\"targets\": [\"file:pkg\"],\n\"files\": {\"pkg/a.py\": [{\"code\": \"name-defined\", \"column\": 0, \"offset\": 1, \"message\": \"Name \\\"a\\\" is not defined\", \"target\": \"pkg.a\", \"src\": \"a\"}]},\n\"format\": \"1.7\"\n}\n[out]\nFound 1 error (0 new errors) in 1 file (checked 1 source file)\nBaseline successfully written to .mypy/baseline.json\n== Return code: 0\n\n\n[case testAutoBaselineRemoves]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\n1 + 1\n[file .mypy/baseline.json]\n{\"targets\": [\"file:pkg\"],\n\"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"offset\": 2, \"code\": \"name-defined\", \"message\": \"Name \\\"a\\\" is not defined\", \"src\": \"\"}]\n}}\n[out]\nNo errors, baseline file removed\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testAutoBaselineDoesntActivateWithErrors]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\na\nb\n[file .mypy/baseline.json]\n{\"targets\": [\"file:pkg\"], \"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"offset\": 2, \"code\": \"name-defined\", \"message\": \"Name \\\"a\\\" is not defined\", \"src\": \"a\"}]}\n}\n[out]\npkg/a.py:2:1: error: Name \"b\" is not defined  [name-defined]\nFound 1 error in 1 file (checked 1 source file)\n\n\n[case testAutoBaselineUpdates]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\na\n[file .mypy/baseline.json]\n{\n\"targets\": [\"file:pkg\"],\n\"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"offset\": 2, \"code\": \"name-defined\", \"message\": \"Name \\\"a\\\" is not defined\", \"src\": \"a\"}]}\n}\n[out]\nBaseline successfully updated at .mypy/baseline.json\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testAutoBaselineDoesntMessageWhenSame-skip_path_normalization]\n# cmd: mypy pkg\n[file pkg/a.py]\na\n[file .mypy/baseline.json]\n{\"targets\": [\"file:pkg\"],\n\"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"code\": \"name-defined\", \"column\": 0, \"offset\": 1, \"message\": \"Name \\\"a\\\" is not defined\", \"target\": \"a\", \"src\": \"a\"}]}\n}\n[outfile .mypy/baseline.json]\n{\"targets\": [\"file:pkg\"],\n\"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"code\": \"name-defined\", \"column\": 0, \"offset\": 1, \"message\": \"Name \\\"a\\\" is not defined\", \"target\": \"a\", \"src\": \"a\"}]}\n}\n\n\n[case testAutoBaselineDoesntMessageWhenSame2]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\na\n[file .mypy/baseline.json]\n{\"targets\": [\"file:pkg\"],\n\"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"code\": \"name-defined\", \"column\": 0, \"offset\": 1, \"message\": \"Name \\\"a\\\" is not defined\", \"target\": \"a\", \"src\": \"a\"}]}\n}\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testInvalidFormat]\n# cmd: mypy --error-summary --baseline-file a/b pkg\n[file pkg/a.py]\na\n[file a/b]\n{\"__baseline_metadata__\": {\"targets\": [\"file:pkg\"]}}\n[out]\nerror: Baseline file 'a/b' has an invalid data format.\nIt should be regenerated with `--write-baseline`.\n== Return code: 2\n\n\n[case testAutoBaselineDifferentTargets]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\na\n[file .mypy/baseline.json]\n{\n\"targets\": [\"file:pkg/a.py\"],\n\"format\": \"1.7\",\n\"files\": {\"pkg/a.py\": [{\"offset\": 2, \"code\": \"name-defined\", \"message\": \"Name \\\"a\\\" is not defined\", \"src\": \"a\"}]}\n}\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testNoAutoBaseline]\n# cmd: mypy --no-auto-baseline --error-summary pkg\n[file pkg/a.py]\na\n[file .mypy/baseline.json]\n{\"files\": {\"pkg/a.py\": [{\"offset\": 2, \"code\": \"name-defined\", \"message\": \"Name \\\"a\\\" is not defined\", \"src\": \"a\"}]}, \"format\": \"1.7\",\n\"targets\": [\"file:pkg\"]\n}\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testNotFound]\n# cmd: mypy --baseline-file a/b --error-summary pkg\n[file pkg/a.py]\n[out]\nerror: Baseline file not found at a/b\n== Return code: 2\n\n\n[case testInvalidJSON]\n# cmd: mypy --baseline-file a/b --error-summary pkg\n[file pkg/a.py]\n[file a/b]\nhi\n[out]\nerror: Invalid JSON in baseline file a/b\n== Return code: 2\n\n\n[case testBaselineFilter]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\n1 + \"\"\n\"\" + 1\n[file .mypy/baseline.json]\n{\"files\": {\"pkg/a.py\": [{\"code\": \"operator\", \"offset\": 2, \"message\": \"Unsupported operand types for + (\\\"str\\\" and \\\"int\\\")\", \"src\": \"\\\"\\\" + 1\"}]}, \"format\": \"1.7\",\n\"targets\": [\"file:pkg\"]}\n[out]\npkg/a.py:1:5: error: Unsupported operand types for + (\"int\" and \"str\")  [operator]\nFound 1 error in 1 file (checked 1 source file)\n\n\n[case testBlockers]\n# cmd: mypy --write-baseline --error-summary main\n[file main]\n 1\n[out]\nmain:1:2: error: unexpected indent  [syntax]\nFound 1 error in 1 file (errors prevented further checking)\n== Return code: 2\n\n\n[case testBaselineFilterLinkedNotes]\n# cmd: mypy --error-summary pkg\n[file pkg/a.py]\n(a, 1 + \"\")  # type: ignore[name-defined]\n[file .mypy/baseline.json]\n{\n  \"files\": {\n    \"pkg/a.py\": [\n      {\"code\": \"name-defined\", \"column\": 0, \"message\": \"Name \\\"a\\\" is not defined\", \"offset\": 1, \"src\": \"(a, 1 + \\\"\\\")  # type: ignore[name-defined]\"},\n      {\"code\": \"operator\", \"column\": 0, \"message\": \"Unsupported operand types for + (\\\"int\\\" and \\\"str\\\")\", \"offset\": 0, \"src\": \"(a, 1 + \\\"\\\")  # type: ignore[name-defined]\"}\n    ]\n  },\n  \"format\": \"1.7\",\n  \"targets\": [ \"file:pkg\" ]\n}\n[out]\nBaseline successfully updated at .mypy/baseline.json\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testRevealType]\n# cmd: mypy --error-summary pkg\n[file pkg/main.py]\na: int\nreveal_type(a)\n[file .mypy/baseline.json]\n{\"files\": {\"pkg/main.py\": [{\"offset\": 1, \"code\": \"misc\", \"message\": \"test\", \"src\": \"\"}]}, \"format\": \"1.7\", \"targets\": [\"file:pkg\"]}\n[out]\npkg/main.py:2:13: note: Revealed type is \"int\"\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testRevealLocals]\n# cmd: mypy --error-summary pkg\n[file pkg/main.py]\ndef foo() -> None:\n    a: int\n    reveal_locals()\n[file .mypy/baseline.json]\n{\"files\": {\"main.py\": [{\"offset\": 1, \"code\": \"misc\", \"message\": \"test\", \"src\": \"\"}]}, \"format\": \"1.7\", \"targets\": [\"file:pkg\"]}\n[out]\npkg/main.py: note: In function \"foo\":\npkg/main.py:3:5: note: Revealed local types are:\npkg/main.py:3:5: note:     a: int\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testOldBaselineFormat]\n# cmd: mypy --error-summary pkg\n[file pkg/main.py]\na: int = ''\nb: str = 1\n[file .mypy/baseline.json]\n{\n  \"files\": {\n    \"pkg/main.py\": [{\"offset\": 1, \"code\": \"assignment\", \"message\": \"Incompatible types in assignment (expression has type \\\"str\\\", variable has type \\\"int\\\")\"}]\n  },\n  \"format\": \"1.3\",\n  \"targets\": [\"file:pkg/main.py\"]\n}\n[out]\nerror: Baseline file '.mypy/baseline.json' was generated with an old version of basedmypy.\nIt should be regenerated with `--write-baseline`.\n== Return code: 2\n\n\n[case testOldBaselineFormat1_2]\n# cmd: mypy --error-summary pkg\n[file pkg/main.py]\na: int = ''\nb: str = 1\n[file .mypy/baseline.json]\n{\"__baseline_metadata__\": {\"format\": \"1.2\"}}\n[out]\nerror: Baseline file '.mypy/baseline.json' was generated with an old version of basedmypy.\nIt should be regenerated with `--write-baseline`.\n== Return code: 2\n\n\n[case testInvalidBaselineFormat]\n# cmd: mypy --error-summary pkg\n[file pkg/main.py]\na: int = ''\nb: str = 1\n[file .mypy/baseline.json]\n{}\n[out]\nerror: Baseline file '.mypy/baseline.json' has an invalid data format.\nIt should be regenerated with `--write-baseline`.\n== Return code: 2\n\n\n[case testBaselineWithPrettyAndDuplicates]\n# cmd: mypy --error-summary --pretty --show-error-context pkg\n[file pkg/main.py]\ndef foo(a=b):\n    pass\nfoo()\n[file .mypy/baseline.json]\n{\n  \"files\": {\n    \"pkg/main.py\": [\n        {\n            \"code\": \"no-untyped-def\",\n            \"column\": 0,\n            \"message\": \"Function is missing a type annotation for one or more arguments\",\n            \"offset\": 1,\n            \"src\": \"def foo(a=b):\",\n            \"target\": \"test.foo\"\n        },\n        {\n            \"code\": \"name-defined\",\n            \"column\": 10,\n            \"message\": \"Name \\\"b\\\" is not defined\",\n            \"offset\": 0,\n            \"src\": \"def foo(a=b):\",\n            \"target\": \"test\"\n        },\n        {\n            \"code\": \"no-untyped-call\",\n            \"column\": 0,\n            \"message\": \"Call to incomplete function \\\"foo\\\" in typed context\",\n            \"offset\": 2,\n            \"src\": \"foo()\",\n            \"target\": \"test\"\n        },\n        {\n            \"code\": \"no-untyped-call\",\n            \"column\": 0,\n            \"message\": \"Type is \\\"def (a: Untyped =) -> None\\\"\",\n            \"offset\": 0,\n            \"src\": \"foo()\",\n            \"target\": \"test\"\n        }\n    ]\n  },\n  \"format\": \"1.7\",\n  \"targets\": [\n    \"package:pkg\"\n  ]\n}\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n\n[case testBaselineWithPrettyAndDuplicatesOutFile-skip_path_normalization]\n# cmd: mypy --error-summary --pretty --show-error-context pkg\n[file pkg/main.py]\ndef foo(a=b):\n    pass\nfoo()\n[file .mypy/baseline.json]\n{\n    \"files\": {\n        \"pkg/main.py\": [\n            {\n                \"code\": \"no-untyped-def\",\n                \"column\": 0,\n                \"message\": \"Function is missing a type annotation for one or more arguments\",\n                \"offset\": 1,\n                \"src\": \"def foo(a=b):\",\n                \"target\": \"test.foo\"\n            },\n            {\n                \"code\": \"name-defined\",\n                \"column\": 10,\n                \"message\": \"Name \\\"b\\\" is not defined\",\n                \"offset\": 0,\n                \"src\": \"def foo(a=b):\",\n                \"target\": \"test\"\n            },\n            {\n                \"code\": \"no-untyped-call\",\n                \"column\": 0,\n                \"message\": \"Call to incomplete function \\\"foo\\\" in typed context\",\n                \"offset\": 2,\n                \"src\": \"foo()\",\n                \"target\": \"test\"\n            },\n            {\n                \"code\": \"no-untyped-call\",\n                \"column\": 0,\n                \"message\": \"Type is \\\"def (a: Untyped =) -> None\\\"\",\n                \"offset\": 0,\n                \"src\": \"foo()\",\n                \"target\": \"test\"\n            }\n        ]\n    },\n    \"format\": \"1.7\",\n    \"targets\": [\n        \"package:pkg\"\n    ]\n}\n[outfile .mypy/baseline.json]\n{\n    \"files\": {\n        \"pkg/main.py\": [\n            {\n                \"code\": \"no-untyped-def\",\n                \"column\": 0,\n                \"message\": \"Function is missing a type annotation for one or more arguments\",\n                \"offset\": 1,\n                \"src\": \"def foo(a=b):\",\n                \"target\": \"test.foo\"\n            },\n            {\n                \"code\": \"name-defined\",\n                \"column\": 10,\n                \"message\": \"Name \\\"b\\\" is not defined\",\n                \"offset\": 0,\n                \"src\": \"def foo(a=b):\",\n                \"target\": \"test\"\n            },\n            {\n                \"code\": \"no-untyped-call\",\n                \"column\": 0,\n                \"message\": \"Call to incomplete function \\\"foo\\\" in typed context\",\n                \"offset\": 2,\n                \"src\": \"foo()\",\n                \"target\": \"test\"\n            },\n            {\n                \"code\": \"no-untyped-call\",\n                \"column\": 0,\n                \"message\": \"Type is \\\"def (a: Untyped =) -> None\\\"\",\n                \"offset\": 0,\n                \"src\": \"foo()\",\n                \"target\": \"test\"\n            }\n        ]\n    },\n    \"format\": \"1.7\",\n    \"targets\": [\n        \"package:pkg\"\n    ]\n}\n\n[case testSrcOtherFile]\n# cmd: mypy --write-baseline a.py --show-error-context\n[file a.py]\nfrom b import f\nf(a=1)\n[file b.py]\n# need\n# empty lines\n# here\ndef f(): ...\n[out]\na.py:2:1: error: Unexpected keyword argument \"a\" for \"f\"  [call-arg]\nb.py:4:1: note: \"f\" defined here\nBaseline successfully written to .mypy/baseline.json\n== Return code: 0\n\n[case testSrcOtherFile2]\n# cmd: mypy a.py --show-error-context\n[file a.py]\nfrom b import f\nf(a=1)\n[file b.py]\n# need\n# empty lines\n# here\ndef f(): ...\n[file .mypy/baseline.json]\n{\n    \"files\": {\n        \"a.py\": [\n            {\n                \"code\": \"no-untyped-def\",\n                \"column\": 0,\n                \"message\": \"Function is missing a type annotation for one or more arguments\",\n                \"offset\": 1,\n                \"src\": \"def foo(a=b):\",\n                \"target\": \"test.foo\"\n            }\n        ]\n    },\n    \"format\": \"1.7\",\n    \"targets\": [\n        \"file:a.py\"\n    ]\n}\n[out]\na.py:2:1: error: Unexpected keyword argument \"a\" for \"f\"  [call-arg]\nb.py:4:1: note: \"f\" defined here\n\n\n[case testErrorLink]\n# cmd: mypy a.py --show-error-code-links\n# We are testing that error links don't show if the error is baselined\n[file a.py]\na\n[file .mypy/baseline.json]\n{\n    \"files\": {\n        \"a.py\": [\n            {\n                \"code\": \"name-defined\",\n                \"column\": 0,\n                \"message\": \"Name \\\"a\\\" is not defined\",\n                \"offset\": 1,\n                \"src\": \"a\",\n                \"target\": \"a\"\n            }\n        ]\n    },\n    \"format\": \"1.7\",\n    \"targets\": [\n        \"file:a.py\"\n    ]\n}\n\n[case testBaselineCache]\n# cmd: mypy --python-version 3.13 _program.py\n# preload-cache:\n# this is a pragma to preload the cache - to test that when it's run from a warm cache it still works\na\n[file .mypy/baseline.json]\n{\n    \"files\": {\n        \"_program.py\": [\n            {\n                \"code\": \"name-defined\",\n                \"column\": 0,\n                \"message\": \"Name \\\"a\\\" is not defined\",\n                \"offset\": 3,\n                \"src\": \"a\",\n                \"target\": \"_program\"\n            }\n        ]\n    },\n    \"format\": \"1.7\",\n    \"targets\": [\"file:_program.py\"]\n}\n[outfile-re .mypy_cache/3.13/_program.data.json]\n.+\n[outfile-re .mypy_cache/3.13/_program.meta.json]\n.+\n"
  },
  {
    "path": "test-data/unit/cmdline-based-regex.test",
    "content": "-- These are cmdline tests because the implementation is very closely tied to the stubs\n\n[case testRegexReFunctions]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\n\ns: str\nif m := re.match(\"()?()\", s):\n    reveal_type(m[0])  # N: Revealed type is \"str\"\n    reveal_type(m[1])  # N: Revealed type is \"str | None\"\n    reveal_type(m[2])  # N: Revealed type is \"str\"\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\nif m := re.search(\"()?()\", s):\n    reveal_type(m[0])  # N: Revealed type is \"str\"\n    reveal_type(m[1])  # N: Revealed type is \"str | None\"\n    reveal_type(m[2])  # N: Revealed type is \"str\"\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\nif m := re.fullmatch(\"()?()\", s):\n    reveal_type(m[0])  # N: Revealed type is \"str\"\n    reveal_type(m[1])  # N: Revealed type is \"str | None\"\n    reveal_type(m[2])  # N: Revealed type is \"str\"\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\nfor m in re.finditer(\"()?()\", s):\n    reveal_type(m[0])  # N: Revealed type is \"str\"\n    reveal_type(m[1])  # N: Revealed type is \"str | None\"\n    reveal_type(m[2])  # N: Revealed type is \"str\"\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\nif m := re.search(\"\", s):\n    reveal_type(m.groups())  # N: Revealed type is \"()\"\n[out]\n== Return code: 0\n\n\n[case testRegexLiteral]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nfrom typing_extensions import Literal\nimport re\n\ns: str\nr: Literal[\"()?()\"]\nif it := re.search(r, s):\n    reveal_type(it[0])  # N: Revealed type is \"str\"\n    reveal_type(it[1])  # N: Revealed type is \"str | None\"\n    reveal_type(it[2])  # N: Revealed type is \"str\"\n    reveal_type(it.groups())  # N: Revealed type is \"(str | None, str)\"\n[out]\n== Return code: 0\n\n\n[case testRegexPattern]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\ns: str\np = re.compile(\"()?()\")\nif m := p.match(s):\n    reveal_type(m[0])  # N: Revealed type is \"str\"\n    reveal_type(m[1])  # N: Revealed type is \"str | None\"\n    reveal_type(m[2])  # N: Revealed type is \"str\"\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\nif m := p.search(s):\n    reveal_type(m[0])  # N: Revealed type is \"str\"\n    reveal_type(m[1])  # N: Revealed type is \"str | None\"\n    reveal_type(m[2])  # N: Revealed type is \"str\"\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\nif f := p.fullmatch(s):\n    reveal_type(f[0])  # N: Revealed type is \"str\"\n    reveal_type(f[1])  # N: Revealed type is \"str | None\"\n    reveal_type(f[2])  # N: Revealed type is \"str\"\n    reveal_type(f.groups())  # N: Revealed type is \"(str | None, str)\"\nfor f in p.finditer(s):\n    reveal_type(f[0])  # N: Revealed type is \"str\"\n    reveal_type(f[1])  # N: Revealed type is \"str | None\"\n    reveal_type(f[2])  # N: Revealed type is \"str\"\n    reveal_type(f.groups())  # N: Revealed type is \"(str | None, str)\"\n[out]\n== Return code: 0\n\n\n[case testRegexInvalidPattern]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nre.compile(\"(\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.search(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.match(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.fullmatch(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.finditer(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.split(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.search(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\nre.findall(\"(\", \"\")  # E: missing ), unterminated subpattern at position 0  [regex]\n\n\n[case testRegexBytes]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nif m := re.match(b\"()?()\", b\"\"):\n    reveal_type(m[0])  # N: Revealed type is \"bytes\"\n    reveal_type(m[1])  # N: Revealed type is \"bytes | None\"\n    reveal_type(m[2])  # N: Revealed type is \"bytes\"\n    reveal_type(m.groups())  # N: Revealed type is \"(bytes | None, bytes)\"\n[out]\n== Return code: 0\n\n\n[case testRegexFindall]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nreveal_type(re.findall('abc', \"abc\"))  # N: Revealed type is \"list[str]\"\nreveal_type(re.findall('(a)bc', \"abc\"))  # N: Revealed type is \"list[str]\"\nreveal_type(re.findall('(a)(b)c', \"abc\"))  # N: Revealed type is \"list[(str, str)]\"\nreveal_type(re.findall('(a)(b)(c)', \"abc\"))  # N: Revealed type is \"list[(str, str, str)]\"\nreveal_type(re.findall('(a)(b)?(c)', \"ac\"))  # N: Revealed type is \"list[(str, str, str)]\"\nreveal_type(re.findall(b\"\", b\"\"))  # N: Revealed type is \"list[bytes]\"\n[out]\n== Return code: 0\n\n\n\n[case testRegexSplit]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nreveal_type(re.split('abc', \"abc\"))  # N: Revealed type is \"list[str]\"\nreveal_type(re.split('(a)bc', \"abc\"))  # N: Revealed type is \"list[str]\"\nreveal_type(re.split('(a)(b)c', \"abc\"))  # N: Revealed type is \"list[str]\"\nreveal_type(re.split('(a)(b)(c)', \"abc\"))  # N: Revealed type is \"list[str]\"\nreveal_type(re.split('(a)(b)?(c)', \"ac\"))  # N: Revealed type is \"list[str | None]\"\n[out]\n== Return code: 0\n\n\n[case testRegexMatchGroup]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\n\nif m := re.match(\"()?()\", \"\"):\n    reveal_type(m.group(0))  # N: Revealed type is \"str\"\n    reveal_type(m.group(1))  # N: Revealed type is \"str | None\"\n    reveal_type(m.group(2))  # N: Revealed type is \"str\"\n    reveal_type(m.group(3))  # E: No such group: 3  [regex] \\\n                             # N: Revealed type is \"Any (from error)\"\n\n\n[case testNamedGroup]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\n\nif m := re.match(\"(?P<a>)\", \"\"):\n    reveal_type(m.group(\"a\"))  # N: Revealed type is \"str\"\n    reveal_type(m.group(\"b\"))  # E: No such group: 'b'  [regex] \\\n                               # N: Revealed type is \"Any (from error)\"\n\n\n[case testFinalAnnotated]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nfrom typing import Final\nimport re\n\np1: re.Pattern[str] = re.compile(\"()\")\nif m := p1.match(\"\"):\n    reveal_type(m[1])  # N: Revealed type is \"str\"\n\np2: Final[re.Pattern[str]] = re.compile(\"()\")\nif m := p2.match(\"\"):\n    reveal_type(m[1])  # N: Revealed type is \"str\"\n[out]\n== Return code: 0\n\n\n[case testDontMutate]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\n\nm = re.match(r\"()?()\", \"\")\nm = re.match(r\"()\", \"\")\nif m:\n    reveal_type(m.groups())  # N: Revealed type is \"(str,)\"\n[out]\n== Return code: 0\n\n\n[case testDontMutatePattern]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\np1 = re.compile(\"()?()\")\ns: str\np2 = re.compile(s)\nif m := p2.match(\"\"):\n    reveal_type(m.groups())  # N: Revealed type is \"tuple[str | None, ...]\"\nif m := p1.match(\"\"):\n    reveal_type(m.groups())  # N: Revealed type is \"(str | None, str)\"\n[out]\n== Return code: 0\n\n\n[case testRegexUnknown]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nm: re.Match[str]\nreveal_type(m.groups())  # N: Revealed type is \"tuple[str | None, ...]\"\nreveal_type(m.group(0))  # N: Revealed type is \"str\"\nreveal_type(m.group(1))  # N: Revealed type is \"str | None\"\n[out]\n== Return code: 0\n\n[case testRegexSub]\n# cmd: mypy main.py --hide-column-numbers --hide-error-context\n[file main.py]\nimport re\n\nr = re.sub(\n    \"()?()\",\n    lambda m: str(reveal_type(m.groups())),  # N: Revealed type is \"(str | None, str)\"\n    \"\",\n)\nreveal_type(r)   # N: Revealed type is \"str\"\nr = re.sub(\n    b\"()?()\",\n    lambda m: bytes(reveal_type(m.groups())[1]),  # N: Revealed type is \"(bytes | None, bytes)\"\n    b\"\",\n)\nreveal_type(r)   # N: Revealed type is \"bytes\"\nr = re.subn(\n    \"()?()\",\n    lambda m: str(reveal_type(m.groups())),  # N: Revealed type is \"(str | None, str)\"\n    \"\",\n)\nreveal_type(r)   # N: Revealed type is \"(str, int)\"\n\nr = re.compile(\"()?()\").sub(\n    lambda m: str(reveal_type(m.groups())),  # N: Revealed type is \"(str | None, str)\"\n    \"\",\n)\nreveal_type(r)   # N: Revealed type is \"str\"\nr = re.compile(\"()?()\").subn(\n    lambda m: str(reveal_type(m.groups())),  # N: Revealed type is \"(str | None, str)\"\n    \"\",\n)\nreveal_type(r)   # N: Revealed type is \"(str, int)\"\n[out]\n== Return code: 0\n\n\n[case testRegexGroupDict]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nif m := re.match(\"(?P<a>a)(?P<b>b)?\", \"a\"):\n    d = reveal_type(m.groupdict())  # N: Revealed type is \"TypedDict({'a': str, 'b': str | None})\"\n    d['a'] = \"\"\n    reveal_type(m.groupdict(1))  # N: Revealed type is \"TypedDict({'a': str, 'b': str | int})\"\n[out]\n== Return code: 0\n\n\n[case testRegexVerbose]\n# cmd: mypy main.py --hide-column-numbers\n[file main.py]\nimport re\nfrom re import X\nif m := re.match(\"()#()\", \"\", X):\n    reveal_type(m.groups())   # N: Revealed type is \"(str,)\"\nif m := re.match(\"()#()\", \"\", re.X):\n    reveal_type(m.groups())   # N: Revealed type is \"(str,)\"\nif m := re.match(\"()#()\", \"\", re.VERBOSE):\n    reveal_type(m.groups())   # N: Revealed type is \"(str,)\"\nif m := re.match(\"()#()\", \"\", flags=re.X):\n    reveal_type(m.groups())   # N: Revealed type is \"(str,)\"\nif m := re.match(\"()#()\", \"\", flags=re.X | re.DOTALL):\n    reveal_type(m.groups())   # N: Revealed type is \"(str,)\"\nif m := re.match(\"()#()\", \"\", flags=re.X | re.DOTALL | re.ASCII):\n    reveal_type(m.groups())   # N: Revealed type is \"(str,)\"\nif m := re.match(\"()#()\", \"\", flags=re.VERBOSE & re.DOTALL):\n    reveal_type(m.groups())   # N: Revealed type is \"tuple[str | None, ...]\"\nif m := re.match(\"()#()\", \"\", 1):\n    reveal_type(m.groups())   # N: Revealed type is \"tuple[str | None, ...]\"\nif m := re.match(\"()#()\", \"\", flags=1):\n    reveal_type(m.groups())   # N: Revealed type is \"tuple[str | None, ...]\"\n[out]\n== Return code: 0\n"
  },
  {
    "path": "test-data/unit/cmdline-based.test",
    "content": "[case testIgnoreMissingPyTyped]\n# cmd: mypy main.py\n[file main.py]\nfrom a import x\nfrom b import y\n[file mypy.ini]\n\\[mypy]\n\\[mypy-a]\nignore_missing_py_typed = true\n[file pypath/a/__init__.py]\nx = 0\n[file pypath/b/__init__.py]\ny = 0\n[out]\nmain.py:2:1: error: Skipping analyzing \"b\": module is installed, but missing library stubs or py.typed marker. To work around this error, see the 'ignore_missing_py_typed' option  [import-untyped]\nmain.py:2:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n\n[case testIgnoreMissingPyTypedDontClobberStubs]\n# cmd: mypy --ignore-missing-py-typed main.py\n[file main.py]\nfrom a import x\nreveal_type(x)\n[file pypath/a/__init__.py]\nx = 0\n[file pypath/a-stubs/__init__.pyi]\nx: str\n[out]\nmain.py:2:13: note: Revealed type is \"str\"\n== Return code: 0\n\n\n[case testIgnoreMissingPyTypedWithPyTyped]\n# cmd: mypy --ignore-missing-py-typed main.py\n[file main.py]\nfrom a import x\nreveal_type(x)\n[file pypath/a/__init__.py]\nx = 0\n[file pypath/a/py.typed]\n[out]\nmain.py:2:13: note: Revealed type is \"int\"\n== Return code: 0\n\n\n[case testIdeCodes]\n# cmd: mypy --ide main.py\n[file main.py]\n1 + \"\"\n1 + \"\"\n[out]\nmain.py:1:5:1:6: error: Unsupported operand types for + (\"int\" and \"str\")  [operator]\nmain.py:1:5:1:6: note: See https://kotlinisland.github.io/basedmypy/_refs.html#code-operator for more info\nmain.py:2:5:2:6: error: Unsupported operand types for + (\"int\" and \"str\")  [operator]\nmain.py:2:5:2:6: note: See https://kotlinisland.github.io/basedmypy/_refs.html#code-operator for more info\n"
  },
  {
    "path": "test-data/unit/cmdline.pyproject.test",
    "content": "-- Tests for command line parsing\n-- ------------------------------\n--\n-- The initial line specifies the command line, in the format\n--\n--   # cmd: mypy <options>\n--\n-- Note that # flags: --some-flag IS NOT SUPPORTED.\n-- Use # cmd: mypy --some-flag ...\n--\n-- '== Return code: <value>' is added to the output when the process return code\n-- is \"nonobvious\" -- that is, when it is something other than 0 if there are no\n-- messages and 1 if there are.\n\n-- Directories/packages on the command line\n-- ----------------------------------------\n\n[case testNonArrayOverridesPyprojectTOML]\n# cmd: mypy x.py\n[file pyproject.toml]\n\\[tool.mypy]\n\\[tool.mypy.overrides]\nmodule = \"x\"\ndisallow_untyped_defs = false\n[file x.py]\ndef f(a):\n    pass\ndef g(a: int) -> int:\n    return f(a)\n[out]\npyproject.toml: tool.mypy.overrides sections must be an array. Please make sure you are using double brackets like so: [[tool.mypy.overrides]]\n== Return code: 0\n\n[case testNoModuleInOverridePyprojectTOML]\n# cmd: mypy x.py\n[file pyproject.toml]\n\\[tool.mypy]\n\\[[tool.mypy.overrides]]\ndisallow_untyped_defs = false\n[file x.py]\ndef f(a):\n    pass\ndef g(a: int) -> int:\n    return f(a)\n[out]\npyproject.toml: toml config file contains a [[tool.mypy.overrides]] section, but no module to override was specified.\n== Return code: 0\n\n[case testInvalidModuleInOverridePyprojectTOML]\n# cmd: mypy x.py\n[file pyproject.toml]\n\\[tool.mypy]\n\\[[tool.mypy.overrides]]\nmodule = 0\ndisallow_untyped_defs = false\n[file x.py]\ndef f(a):\n    pass\ndef g(a: int) -> int:\n    return f(a)\n[out]\npyproject.toml: toml config file contains a [[tool.mypy.overrides]] section with a module value that is not a string or a list of strings\n== Return code: 0\n\n[case testConflictingModuleInOverridesPyprojectTOML]\n# cmd: mypy x.py\n[file pyproject.toml]\n\\[tool.mypy]\n\\[[tool.mypy.overrides]]\nmodule = 'x'\ndisallow_untyped_defs = false\n\\[[tool.mypy.overrides]]\nmodule = ['x']\ndisallow_untyped_defs = true\n[file x.py]\ndef f(a):\n    pass\ndef g(a: int) -> int:\n    return f(a)\n[out]\npyproject.toml: toml config file contains [[tool.mypy.overrides]] sections with conflicting values. Module 'x' has two different values for 'disallow_untyped_defs'\n== Return code: 0\n\n[case testMultilineLiteralExcludePyprojectTOML]\n# cmd: mypy x\n[file pyproject.toml]\n\\[tool.mypy]\nexclude = '''(?x)(\n    (^|/)[^/]*skipme_\\.py$\n    |(^|/)_skipme[^/]*\\.py$\n)'''\n[file x/__init__.py]\ni: int = 0\n[file x/_skipme_please.py]\nThis isn't even syntactically valid!\n[file x/please_skipme_.py]\nNeither is this!\n\n[case testMultilineBasicExcludePyprojectTOML]\n# cmd: mypy x\n[file pyproject.toml]\n\\[tool.mypy]\nexclude = \"\"\"(?x)(\n    (^|/)[^/]*skipme_\\\\.py$\n    |(^|/)_skipme[^/]*\\\\.py$\n)\"\"\"\n[file x/__init__.py]\ni: int = 0\n[file x/_skipme_please.py]\nThis isn't even syntactically valid!\n[file x/please_skipme_.py]\nNeither is this!\n\n[case testSequenceExcludePyprojectTOML]\n# cmd: mypy x\n[file pyproject.toml]\n\\[tool.mypy]\nexclude = [\n    '(^|/)[^/]*skipme_\\.py$',  # literal (no escaping)\n    \"(^|/)_skipme[^/]*\\\\.py$\",  # basic (backslash needs escaping)\n]\n[file x/__init__.py]\ni: int = 0\n[file x/_skipme_please.py]\nThis isn't even syntactically valid!\n[file x/please_skipme_.py]\nNeither is this!\n\n[case testPyprojectTOMLUnicode]\n# cmd: mypy x.py\n[file pyproject.toml]\n\\[project]\ndescription = \"Factory ⸻ A code generator 🏭\"\n\\[tool.mypy]\n[file x.py]\n\n[case testSearchRecursively]\n# cmd: mypy x.py\n[file ../pyproject.toml]\n\\[tool.mypy]\n\\[tool.mypy.overrides]\nmodule = \"x\"\ndisallow_untyped_defs = false\n[file x.py]\npass\n[out]\n../pyproject.toml: tool.mypy.overrides sections must be an array. Please make sure you are using double brackets like so: [[tool.mypy.overrides]]\n== Return code: 0\n\n[case testSearchRecursivelyStopsGit]\n# cmd: mypy x.py\n[file .git/test]\n[file ../pyproject.toml]\n\\[tool.mypy]\n\\[tool.mypy.overrides]\nmodule = \"x\"\ndisallow_untyped_defs = false\n[file x.py]\ni: int = 0\n\n[case testSearchRecursivelyStopsHg]\n# cmd: mypy x.py\n[file .hg/test]\n[file ../pyproject.toml]\n\\[tool.mypy]\n\\[tool.mypy.overrides]\nmodule = \"x\"\ndisallow_untyped_defs = false\n[file x.py]\ni: int = 0\n"
  },
  {
    "path": "test-data/unit/cmdline.test",
    "content": "-- Tests for command line parsing\n-- ------------------------------\n--\n-- The initial line specifies the command line, in the format\n--\n--   # cmd: mypy <options>\n--\n-- Note that # flags: --some-flag IS NOT SUPPORTED.\n-- Use # cmd: mypy --some-flag ...\n--\n-- '== Return code: <value>' is added to the output when the process return code\n-- is \"nonobvious\" -- that is, when it is something other than 0 if there are no\n-- messages and 1 if there are.\n\n-- Directories/packages on the command line\n-- ----------------------------------------\n\n[case testCmdlinePackage]\n# cmd: mypy pkg\n[file pkg/__init__.py]\n[file pkg/a.py]\nundef\n[file pkg/subpkg/__init__.py]\n[file pkg/subpkg/a.py]\nundef\nimport pkg.subpkg.a\n[out]\npkg/a.py:1: error: Name \"undef\" is not defined\npkg/subpkg/a.py:1: error: Name \"undef\" is not defined\n\n[case testCmdlinePackageSlash]\n# cmd: mypy pkg/\n[file pkg/__init__.py]\n[file pkg/a.py]\nundef\n[file pkg/subpkg/__init__.py]\n[file pkg/subpkg/a.py]\nundef\nimport pkg.subpkg.a\n[out]\npkg/a.py:1: error: Name \"undef\" is not defined\npkg/subpkg/a.py:1: error: Name \"undef\" is not defined\n\n[case testCmdlineNonPackage]\n# cmd: mypy dir\n[file dir/a.py]\nundef\n[file dir/subdir/b.py]\nundef\n[out]\ndir/a.py:1: error: Name \"undef\" is not defined\ndir/subdir/b.py:1: error: Name \"undef\" is not defined\n\n[case testCmdlineNonPackageDuplicate]\n# cmd: mypy dir\n[file dir/a.py]\nundef\n[file dir/subdir/a.py]\nundef\n[out]\ndir/a.py: error: Duplicate module named \"a\" (also at \"dir/subdir/a.py\")\ndir/a.py: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#mapping-file-paths-to-modules for more info\ndir/a.py: note: Common resolutions include: a) using `--exclude` to avoid checking one of them, b) adding `__init__.py` somewhere, c) using `--explicit-package-bases` or adjusting MYPYPATH\n== Return code: 2\n\n[case testCmdlineNonPackageSlash]\n# cmd: mypy dir/\n[file dir/a.py]\nundef\nimport b\n[file dir/subdir/b.py]\nundef\nimport a\n[out]\ndir/a.py:1: error: Name \"undef\" is not defined\ndir/subdir/b.py:1: error: Name \"undef\" is not defined\n\n[case testCmdlinePackageContainingSubdir]\n# cmd: mypy pkg\n[file pkg/__init__.py]\n[file pkg/a.py]\nundef\nimport pkg.a\n[file pkg/subdir/a.py]\nundef\nimport pkg.a\n[out]\npkg/a.py:1: error: Name \"undef\" is not defined\npkg/subdir/a.py:1: error: Name \"undef\" is not defined\n\n[case testCmdlineNonPackageContainingPackage]\n# cmd: mypy dir\n[file dir/a.py]\nundef\nimport subpkg.a\n[file dir/subpkg/__init__.py]\n[file dir/subpkg/a.py]\nundef\n[out]\ndir/subpkg/a.py:1: error: Name \"undef\" is not defined\ndir/a.py:1: error: Name \"undef\" is not defined\n\n[case testCmdlineInvalidPackageName]\n# cmd: mypy dir/sub.pkg/a.py\n[file dir/sub.pkg/__init__.py]\n[file dir/sub.pkg/a.py]\nundef\n[out]\nsub.pkg is not a valid Python package name\n== Return code: 2\n\n[case testBadFileEncoding]\n# cmd: mypy a.py\n[file a.py]\n# coding: uft-8\n[out]\nmypy: can't decode file 'a.py': unknown encoding: uft-8\n== Return code: 2\n\n-- '\n[case testCannotIgnoreDuplicateModule]\n# cmd: mypy one/mod/__init__.py two/mod/__init__.py\n[file one/mod/__init__.py]\n# type: ignore\n[file two/mod/__init__.py]\n# type: ignore\n[out]\ntwo/mod/__init__.py: error: Duplicate module named \"mod\" (also at \"one/mod/__init__.py\")\ntwo/mod/__init__.py: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#mapping-file-paths-to-modules for more info\ntwo/mod/__init__.py: note: Common resolutions include: a) using `--exclude` to avoid checking one of them, b) adding `__init__.py` somewhere, c) using `--explicit-package-bases` or adjusting MYPYPATH\n== Return code: 2\n\n-- Note that we use `----`, because this is how `--` is escaped while `--` is a comment starter.\n[case testFlagsFile]\n# cmd: mypy @flagsfile\n[file flagsfile]\n----always-true=FLAG\nmain.py\n[file main.py]\nx: int\nFLAG = False\nif not FLAG:\n    x = \"unreachable\"\n\n[case testConfigFile]\n# cmd: mypy main.py\n[file mypy.ini]\n\\[mypy]\nalways_true = FLAG\n[file main.py]\nx: int\nFLAG = False\nif not FLAG:\n    x = \"unreachable\"\n\n[case testAltConfigFile]\n# cmd: mypy --config-file config.ini main.py\n[file config.ini]\n\\[mypy]\nalways_true = FLAG\n[file main.py]\nx: int\nFLAG = False\nif not FLAG:\n    x = \"unreachable\"\n\n[case testPerFileConfigSectionMultipleMatchesDisallowed]\n# cmd: mypy xx.py xy.py yx.py yy.py\n[file mypy.ini]\n\\[mypy]\n\\[mypy-*x*]\ndisallow_untyped_defs = True\n\\[mypy-*y*]\ndisallow_untyped_calls = True\n[file xx.py]\ndef f(a): pass\ndef g(a: int) -> int: return f(a)\n[file xy.py]\ndef f(a): pass\ndef g(a: int) -> int: return f(a)\n[file yx.py]\ndef f(a): pass\ndef g(a: int) -> int: return f(a)\n[file yy.py]\ndef f(a): pass\ndef g(a: int) -> int: return f(a)\n[out]\nmypy.ini: [mypy-*x*]: Patterns must be fully-qualified module names, optionally with '*' in some components (e.g spam.*.eggs.*)\nmypy.ini: [mypy-*y*]: Patterns must be fully-qualified module names, optionally with '*' in some components (e.g spam.*.eggs.*)\n== Return code: 0\n\n[case testMultipleGlobConfigSection]\n# cmd: mypy x.py y.py z.py\n[file mypy.ini]\n\\[mypy]\n\\[mypy-x.*,z.*]\ndisallow_untyped_defs = True\n[file x.py]\ndef f(a): pass\n[file y.py]\ndef f(a): pass\n[file z.py]\ndef f(a): pass\n[out]\nz.py:1: error: Function is missing a type annotation\nx.py:1: error: Function is missing a type annotation\n\n[case testConfigErrorNoSection]\n# cmd: mypy -c pass\n[file mypy.ini]\n[out]\nmypy.ini: No [mypy] section in config file\n== Return code: 0\n\n[case testConfigErrorUnknownFlag]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\nbad = 0\n[out]\nmypy.ini: [mypy]: Unrecognized option: bad = 0\n== Return code: 0\n\n[case testConfigErrorBadFlag]\n# cmd: mypy a.py\n[file mypy.ini]\n\\[mypy]\ndisallow-untyped-defs = True\n[file a.py]\ndef f():\n    pass\n[out]\nmypy.ini: [mypy]: Unrecognized option: disallow-untyped-defs = True\n== Return code: 0\n\n[case testConfigErrorBadBoolean]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\nignore_missing_imports = nah\n[out]\nmypy.ini: [mypy]: ignore_missing_imports: Not a boolean: nah\n== Return code: 0\n\n[case testConfigErrorNotPerFile]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\n\\[mypy-*]\npython_version = 3.11\n[out]\nmypy.ini: [mypy-*]: Per-module sections should only specify per-module flags (python_version)\n== Return code: 0\n\n[case testConfigMypyPath]\n# cmd: mypy file.py\n[file mypy.ini]\n\\[mypy]\nmypy_path =\n    foo_dir:bar_dir\n    , 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[file file.py]\nimport no_stubs\nfrom foo import foo\nfrom bar import bar\nfrom baz import baz\nbaz(bar(foo(42)))\nbaz(bar(foo('oof')))\n[out]\nfile.py:1: error: Cannot find implementation or library stub for module named \"no_stubs\"\nfile.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nfile.py:6: error: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n\n[case testConfigFollowImportsSysPath]\n# cmd: mypy main.py\n[file main.py]\nfrom a import x\nx + 0\nx + ''  # E\nimport a\na.x + 0\na.x + ''  # E\na.y  # E\na + 0  # E\n[file mypy.ini]\n\\[mypy]\nfollow_imports = normal\nno_silence_site_packages = True\n[file pypath/a/__init__.py]\nx = 0\nx += ''  # Error reported here\n[file pypath/a/py.typed]\n[out]\npypath/a/__init__.py:2: error: Unsupported operand types for + (\"int\" and \"str\")\nmain.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\nmain.py:6: error: Unsupported operand types for + (\"int\" and \"str\")\nmain.py:7: error: Module has no attribute \"y\"\nmain.py:8: error: Unsupported operand types for + (Module and \"int\")\n\n[case testConfigFollowImportsInvalid]\n# cmd: mypy main.py\n[file mypy.ini]\n\\[mypy]\nfollow_imports =True\n[file main.py]\n[out]\nmypy.ini: [mypy]: follow_imports: invalid choice 'True' (choose from 'normal', 'silent', 'skip', 'error')\n== Return code: 0\n\n[case testFailedImportOnWrongCWD]\n# cmd: mypy main.py\n# cwd: main/subdir1/subdir2\n[file main/subdir1/subdir2/main.py]\nimport parent\nimport grandparent\nimport missing\n[file main/subdir1/subdir2/__init__.py]\n[file main/subdir1/parent.py]\n[file main/subdir1/__init__.py]\n[file main/grandparent.py]\n[file main/__init__.py]\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"parent\"\nmain.py:1: note: You may be running mypy in a subpackage, mypy should be run on the package root\nmain.py:2: error: Cannot find implementation or library stub for module named \"grandparent\"\nmain.py:3: error: Cannot find implementation or library stub for module named \"missing\"\nmain.py:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testImportInParentButNoInit]\n# cmd: mypy main.py\n# cwd: main/not_a_package\n[file main/not_a_package/main.py]\nimport needs_init\n[file main/needs_init.py]\n[file main/__init__.py]\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"needs_init\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testConfigNoErrorForUnknownXFlagInSubsection]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nx_bad = 0\n[out]\n\n[case testDotInFilenameOKScript]\n# cmd: mypy a.b.py c.d.pyi\n[file a.b.py]\nundef\n[file c.d.pyi]\nwhatever\n[out]\nc.d.pyi:1: error: Name \"whatever\" is not defined\na.b.py:1: error: Name \"undef\" is not defined\n\n[case testDotInFilenameOKFolder]\n# cmd: mypy my.folder\n[file my.folder/tst.py]\nundef\n[out]\nmy.folder/tst.py:1: error: Name \"undef\" is not defined\n\n[case testDotInFilenameNoImport]\n# cmd: mypy main.py\n[file main.py]\nimport a.b\n[file a.b.py]\nwhatever\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"a.b\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain.py:1: error: Cannot find implementation or library stub for module named \"a\"\n\n[case testPythonVersionWrongFormatPyProjectTOML]\n# cmd: mypy -c pass\n[file pyproject.toml]\n\\[tool.mypy]\npython_version = 3.10\n[out]\npyproject.toml: [mypy]: python_version: Python 3.1 is not supported (must be 3.8 or higher). You may need to put quotes around your Python version\n== Return code: 0\n\n[case testPythonVersionTooOld10]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\npython_version = 1.0\n[out]\nmypy.ini: [mypy]: python_version: Python major version '1' out of range (must be 3)\n== Return code: 0\n\n[case testPythonVersionTooOld37]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\npython_version = 3.7\n[out]\nmypy.ini: [mypy]: python_version: Python 3.7 is not supported (must be 3.8 or higher)\n== Return code: 0\n\n[case testPythonVersionTooNew40]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\npython_version = 4.0\n[out]\nmypy.ini: [mypy]: python_version: Python major version '4' out of range (must be 3)\n== Return code: 0\n\n[case testPythonVersionTooDead27]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\npython_version = 2.7\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: Mypy no longer supports checking Python 2 code. Consider pinning to mypy<0.980 if you need to check Python 2 code.\n== Return code: 2\n\n[case testPythonVersionAccepted38]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\npython_version = 3.8\n[out]\n\n[case testPythonVersionAccepted311]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\npython_version = 3.11\n[out]\n\n-- This should be a dumping ground for tests of plugins that are sensitive to\n-- typeshed changes.\n[case testTypeshedSensitivePlugins]\n# cmd: mypy int_pow.py\n\n[file int_pow.py]\na = 1\nb = a + 2\nreveal_type(a**0)\nreveal_type(a**1)\nreveal_type(a**2)\nreveal_type(a**-0)\nreveal_type(a**-1)\nreveal_type(a**(-2))\nreveal_type(a**b)\nreveal_type(a.__pow__(2))\nreveal_type(a.__pow__(a))\n[out]\nint_pow.py:3: note: Revealed type is \"Literal[1]\"\nint_pow.py:4: note: Revealed type is \"builtins.int\"\nint_pow.py:5: note: Revealed type is \"builtins.int\"\nint_pow.py:6: note: Revealed type is \"Literal[1]\"\nint_pow.py:7: note: Revealed type is \"builtins.float\"\nint_pow.py:8: note: Revealed type is \"builtins.float\"\nint_pow.py:9: note: Revealed type is \"Any\"\nint_pow.py:10: note: Revealed type is \"builtins.int\"\nint_pow.py:11: note: Revealed type is \"Any\"\n== Return code: 0\n\n[case testDisallowAnyGenericsBuiltinCollectionsPre39]\n# cmd: mypy m.py\n[file mypy.ini]\n\\[mypy]\npython_version = 3.8\n\\[mypy-m]\ndisallow_any_generics = True\n[file m.py]\ndef j(s: frozenset) -> None: pass\n[out]\nm.py:1: error: Implicit generic \"Any\". Use \"typing.FrozenSet\" and specify generic parameters\n\n[case testDisallowAnyGenericsTypingCollections]\n# cmd: mypy m.py\n[file mypy.ini]\n\\[mypy]\n\\[mypy-m]\ndisallow_any_generics = True\n[file m.py]\nfrom typing import FrozenSet\ndef j(s: FrozenSet) -> None: pass\n[out]\nm.py:2: error: Missing type parameters for generic type \"FrozenSet\"\n\n[case testSectionInheritance]\n# cmd: mypy a\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\ng(None)\n[file mypy.ini]\n\\[mypy]\nallow_any_generics = True\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[out]\na/b/c/d/e/__init__.py:2: error: Missing type parameters for generic type \"List\"\na/b/c/d/e/__init__.py:3: error: Argument 1 to \"g\" has incompatible type \"None\"; expected \"List[Any]\"\n\n[case testMissingFile]\n# cmd: mypy nope.py\n[out]\nmypy: can't read file 'nope.py': No such file or directory\n== Return code: 2\n--'\n\n[case testModulesAndPackages]\n# cmd: mypy --package p.a --package p.b --module c\n[file p/__init__.py]\n[file p/a.py]\ndef foo(x):\n    # type: (int) -> str\n    return \"x\"\nfoo(\"wrong\")\n[file p/b/__init__.py]\nfrom ..a import foo\ndef bar(a):\n    # type: (int) -> str\n    return foo(a)\nbar(\"wrong\")\n[file c.py]\nimport p.b\np.b.bar(\"wrong\")\n[out]\np/a.py:4: error: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\np/b/__init__.py:5: error: Argument 1 to \"bar\" has incompatible type \"str\"; expected \"int\"\nc.py:2: error: Argument 1 to \"bar\" has incompatible type \"str\"; expected \"int\"\n\n[case testSrcPEP420Packages]\n# cmd: mypy -p anamespace --namespace-packages\n[file mypy.ini]\n\\[mypy]\nmypy_path = src\n[file src/setup.cfg]\n[file src/anamespace/foo/__init__.py]\n[file src/anamespace/foo/bar.py]\ndef bar(a: int, b: int) -> str:\n    return a + b\n[out]\nsrc/anamespace/foo/bar.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testNestedPEP420Packages]\n# cmd: mypy -p pkg --namespace-packages\n[file pkg/a1/b/c/d/e.py]\nx = 0  # type: str\n[file pkg/a1/b/f.py]\nfrom pkg.a1.b.c.d.e import x\nx()\n\n[file pkg/a2/__init__.py]\n[file pkg/a2/b/c/d/e.py]\nx = 0  # type: str\n[file pkg/a2/b/f.py]\nfrom pkg.a2.b.c.d.e import x\nx()\n[out]\npkg/a2/b/c/d/e.py:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\npkg/a1/b/c/d/e.py:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\npkg/a2/b/f.py:2: error: \"str\" not callable\npkg/a1/b/f.py:2: error: \"str\" not callable\n\n[case testFollowImportStubs1]\n# cmd: mypy main.py\n[file mypy.ini]\n\\[mypy]\n\\[mypy-math.*]\nfollow_imports = error\nfollow_imports_for_stubs = True\n[file main.py]\nimport math\nmath.frobnicate()\n[out]\nmain.py:1: error: Import of \"math\" ignored\nmain.py:1: note: (Using --follow-imports=error, module not passed on command line)\n\n[case testFollowImportStubs2]\n# cmd: mypy main.py\n[file mypy.ini]\n\\[mypy]\n\\[mypy-math.*]\nfollow_imports = skip\nfollow_imports_for_stubs = True\n[file main.py]\nimport math\nmath.frobnicate()\n\n[case testShadowFile1]\n# cmd: mypy --shadow-file source.py shadow.py source.py\n[file source.py]\ndef foo() -> str:\n    return \"bar\"\n[file shadow.py]\ndef bar() -> str:\n    return 14\n[out]\nsource.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testShadowFile2]\n# cmd: mypy --shadow-file s1.py shad1.py --shadow-file s2.py shad2.py --shadow-file s3.py shad3.py s1.py s2.py s3.py s4.py\n[file s1.py]\ndef foo() -> str:\n    return \"bar\"\n[file shad1.py]\ndef bar() -> str:\n    return 14\n[file s2.py]\ndef baz() -> str:\n    return 14\n[file shad2.py]\ndef baz() -> int:\n    return 14\n[file s3.py]\ndef qux() -> str:\n    return \"bar\"\n[file shad3.py]\ndef foo() -> int:\n    return [42]\n[file s4.py]\ndef foo() -> str:\n    return 9\n[out]\ns4.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\ns3.py:2: error: Incompatible return value type (got \"List[int]\", expected \"int\")\ns1.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testShadowFileWithPretty]\n# cmd: mypy a.py --pretty --shadow-file a.py b.py\n[file a.py]\nb: bytes\n[file b.py]\na: int = \"\"\nb: bytes = 1\n[out]\na.py:1: error: Incompatible types in assignment (expression has type \"str\",\nvariable has type \"int\")\n    a: int = \"\"\n             ^~\na.py:2: error: Incompatible types in assignment (expression has type \"int\",\nvariable has type \"bytes\")\n    b: bytes = 1\n               ^\n\n[case testConfigWarnUnusedSection1]\n# cmd: mypy foo.py quux.py spam/eggs.py\n[file mypy.ini]\n\\[mypy]\nwarn_unused_configs = True\nincremental = False\n\\[mypy-bar]\n\\[mypy-foo]\n\\[mypy-baz.*]\n\\[mypy-quux.*]\n\\[mypy-spam.*]\n\\[mypy-spam.eggs]\n\\[mypy-emarg.*]\n\\[mypy-emarg.hatch]\n-- Currently we don't treat an unstructured pattern like a.*.b as unused\n-- if it matches another section (like a.x.b). This would be reasonable\n-- to change. '\n\\[mypy-a.*.b]\n\\[mypy-a.*.c]\n\\[mypy-a.x.b]\n[file foo.py]\n[file quux.py]\n[file spam/__init__.py]\n[file spam/eggs.py]\n[out]\nWarning: unused section(s) in mypy.ini: [mypy-bar], [mypy-baz.*], [mypy-emarg.*], [mypy-emarg.hatch], [mypy-a.*.c], [mypy-a.x.b]\n== Return code: 0\n\n[case testConfigUnstructuredGlob]\n# cmd: mypy emarg foo\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\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\n[file foo/__init__.py]\n[file foo/lol.py]\nfail\n[out]\nfoo/lol.py:1: error: Name \"fail\" is not defined\nemarg/foo.py:1: error: Name \"fail\" is not defined\nemarg/hatch/villip/mankangulisk.py:1: error: Name \"fail\" is not defined\n\n[case testPackageRootEmpty]\n# cmd: mypy --no-namespace-packages --package-root= a/b/c.py main.py\n[file a/b/c.py]\n[file main.py]\nimport a.b.c\n\n[case testPackageRootEmptyNamespacePackage]\n# cmd: mypy --namespace-packages --package-root= a/b/c.py main.py\n[file a/b/c.py]\n[file main.py]\nimport a.b.c\n\n[case testPackageRootNonEmpty]\n# cmd: mypy --package-root=a/ a/b/c.py main.py\n[file a/b/c.py]\n[file main.py]\nimport b.c\n\n[case testPackageRootMultiple1]\n# cmd: mypy --package-root=. --package-root=a a/b/c.py d.py main.py\n[file a/b/c.py]\n[file d.py]\n[file main.py]\nimport b.c\nimport d\n\n[case testPackageRootMultiple2]\n# cmd: mypy --package-root=a/ --package-root=./ a/b/c.py d.py main.py\n[file a/b/c.py]\n[file d.py]\n[file main.py]\nimport b.c\nimport d\n\n[case testCacheMap]\n-- This just checks that a valid --cache-map triple is accepted.\n-- (Errors are too verbose to check.)\n# cmd: mypy a.py --no-sqlite-cache --cache-map a.py a.meta.json a.data.json\n[file a.py]\n[out]\n\n[case testIniFiles]\n# cmd: mypy\n[file mypy.ini]\n\\[mypy]\nfiles = a.py, b.py\n[file a.py]\nfail\n[file b.py]\nfail\n[out]\nb.py:1: error: Name \"fail\" is not defined\na.py:1: error: Name \"fail\" is not defined\n\n[case testIniFilesGlobbing]\n# cmd: mypy\n[file mypy.ini]\n\\[mypy]\nfiles = **/*.py\n[file a/b.py]\nfail\n[file c.py]\nfail\n[out]\na/b.py:1: error: Name \"fail\" is not defined\nc.py:1: error: Name \"fail\" is not defined\n\n[case testIniFilesCmdlineOverridesConfig]\n# cmd: mypy override.py\n[file mypy.ini]\n\\[mypy]\nfiles = config.py\n[out]\nmypy: can't read file 'override.py': No such file or directory\n== Return code: 2\n\n[case testErrorSummaryOnSuccess]\n# cmd: mypy --error-summary good.py\n[file good.py]\nx = 2 + 2\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n[case testErrorSummaryOnFail]\n# cmd: mypy --error-summary bad.py\n[file bad.py]\n42 + 'no'\n[out]\nbad.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\nFound 1 error in 1 file (checked 1 source file)\n\n[case testErrorSummaryOnFailNotes]\n# cmd: mypy --error-summary bad.py\n[file bad.py]\nfrom typing import List\nx = []  # type: List[float]\ny = []  # type: List[int]\nx = y\n[out]\nbad.py:4: error: Incompatible types in assignment (expression has type \"List[int]\", variable has type \"List[float]\")\nbad.py:4: note: \"list\" is invariant -- see https://kotlinisland.github.io/basedmypy/common_issues.html#variance\nbad.py:4: note: Consider using \"Sequence\" instead, which is covariant\nFound 1 error in 1 file (checked 1 source file)\n\n[case testErrorSummaryOnFailTwoErrors]\n# cmd: mypy --error-summary bad.py foo.py\n[file bad.py]\n42 + 'no'\n42 + 'no'\n[file foo.py]\n[out]\nbad.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\nbad.py:2: error: Unsupported operand types for + (\"int\" and \"str\")\nFound 2 errors in 1 file (checked 2 source files)\n\n[case testErrorSummaryOnFailTwoFiles]\n# cmd: mypy --error-summary bad.py bad2.py\n[file bad.py]\n42 + 'no'\n[file bad2.py]\n42 + 'no'\n[out]\nbad2.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\nbad.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\nFound 2 errors in 2 files (checked 2 source files)\n\n[case testErrorSummaryOnBadUsage]\n# cmd: mypy --error-summary missing.py\n[out]\nmypy: can't read file 'missing.py': No such file or directory\n== Return code: 2\n\n[case testShowSourceCodeSnippetsWrappedFormatting]\n# cmd: mypy --pretty some_file.py\n[file some_file.py]\nfrom typing import Union\n\n42 + 'no way'\n\nclass OneCustomClassName:\n    def some_interesting_method(self, arg: AnotherCustomClassDefinedBelow) -> AnotherCustomClassDefinedBelow:\n        ...\n\nclass AnotherCustomClassDefinedBelow:\n    def another_even_more_interesting_method(self, arg: Union[int, str, float]) -> None:\n        self.very_important_attribute_with_long_name: OneCustomClassName = OneCustomClassName().some_interesting_method(arg)\n[out]\nsome_file.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n    42 + 'no way'\n         ^~~~~~~~\nsome_file.py:11: error: Incompatible types in assignment (expression has type\n\"AnotherCustomClassDefinedBelow\", variable has type \"OneCustomClassName\")\n    ...t_attribute_with_long_name: OneCustomClassName = OneCustomClassName()....\n                                                        ^~~~~~~~~~~~~~~~~~~~~...\nsome_file.py:11: error: Argument 1 to \"some_interesting_method\" of\n\"OneCustomClassName\" has incompatible type \"Union[int, str, float]\"; expected\n\"AnotherCustomClassDefinedBelow\"\n    ...OneCustomClassName = OneCustomClassName().some_interesting_method(arg)\n                                                                         ^~~\n[case testShowSourceCodeSnippetsBlockingError]\n# cmd: mypy --pretty --show-error-codes some_file.py\n[file some_file.py]\nit_looks_like_we_started_typing_something_but_then. = did_not_notice(an_extra_dot)\n[out]\nsome_file.py:1: error: invalid syntax  [syntax]\n    ...ooks_like_we_started_typing_something_but_then. = did_not_notice(an_ex...\n                                                        ^\n== Return code: 2\n\n[case testTabRenderingUponError]\n# cmd: mypy --pretty tabs.py\n[file tabs.py]\ndef test_tabs() -> str:\n\treturn None\ndef test_between(x: str) -> None: ...\ntest_between(1\t+\t1)\n[out]\ntabs.py:2: error: Incompatible return value type (got \"None\", expected \"str\")\n            return None\n                   ^~~~\ntabs.py:4: error: Argument 1 to \"test_between\" has incompatible type \"int\";\nexpected \"str\"\n    test_between(1  +       1)\n                 ^~~~~~~~~~~~\n\n[case testErrorMessageWhenOpenPydFile]\n# cmd: mypy a.pyd\n[file a.pyd]\n# coding: uft-8\n[out]\nmypy: stubgen does not support .pyd files: 'a.pyd'\n== Return code: 2\n\n[case testDuplicateModules]\n# cmd: mypy src\n[file mypy.ini]\n\\[mypy]\nmypy_path = src\n[file src/__init__.py]\n[file src/a.py]\nimport foo.bar\n[file src/foo/__init__.py]\n[file src/foo/bar.py]\n1+'x'\n[out]\nsrc/foo/bar.py: error: Source file found twice under different module names: \"src.foo.bar\" and \"foo.bar\"\nsrc/foo/bar.py: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#mapping-file-paths-to-modules for more info\nsrc/foo/bar.py: note: Common resolutions include: a) adding `__init__.py` somewhere, b) using `--explicit-package-bases` or adjusting MYPYPATH\n== Return code: 2\n\n[case testEnableInvalidErrorCode]\n# cmd: mypy --enable-error-code YOLO test.py\n[file test.py]\nx = 1\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: Invalid error code(s): YOLO\n== Return code: 2\n\n[case testDisableInvalidErrorCode]\n# cmd: mypy --disable-error-code YOLO test.py\n[file test.py]\nx = 1\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: Invalid error code(s): YOLO\n== Return code: 2\n\n[case testEnableAndDisableInvalidErrorCode]\n# cmd: mypy --disable-error-code YOLO --enable-error-code YOLO2 test.py\n[file test.py]\nx = 1\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: Invalid error code(s): YOLO, YOLO2\n== Return code: 2\n\n[case testEnableValidAndInvalidErrorCode]\n# cmd: mypy --enable-error-code attr-defined --enable-error-code YOLO test.py\n[file test.py]\nx = 1\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: Invalid error code(s): YOLO\n== Return code: 2\n\n[case testDisableValidAndInvalidErrorCode]\n# cmd: mypy --disable-error-code attr-defined --disable-error-code YOLO test.py\n[file test.py]\nx = 1\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: Invalid error code(s): YOLO\n== Return code: 2\n\n[case testStubsDirectory]\n# cmd: mypy --error-summary pkg-stubs\n[file pkg-stubs/__init__.pyi]\n[file pkg-stubs/thing.pyi]\nclass Thing: ...\n[out]\nSuccess: no issues found in 2 source files\n== Return code: 0\n\n[case testStubsDirectoryFile]\n# cmd: mypy --error-summary pkg-stubs/thing.pyi\n[file pkg-stubs/__init__.pyi]\n[file pkg-stubs/thing.pyi]\nclass Thing: ...\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n[case testStubsSubDirectory]\n# cmd: mypy --error-summary src/pkg-stubs\n[file src/pkg-stubs/__init__.pyi]\n[file src/pkg-stubs/thing.pyi]\nclass Thing: ...\n[out]\nSuccess: no issues found in 2 source files\n== Return code: 0\n\n[case testStubsSubDirectoryFile]\n# cmd: mypy --error-summary src/pkg-stubs/thing.pyi\n[file src/pkg-stubs/__init__.pyi]\n[file src/pkg-stubs/thing.pyi]\nclass Thing: ...\n[out]\nSuccess: no issues found in 1 source file\n== Return code: 0\n\n[case testBlocker]\n# cmd: mypy pkg --error-summary --disable-error-code syntax\n[file pkg/x.py]\npublic static void main(String[] args)\n[file pkg/y.py]\nx: str = 0\n[out]\npkg/x.py:1: error: invalid syntax\nFound 1 error in 1 file (errors prevented further checking)\n== Return code: 2\n[out version>=3.10]\npkg/x.py:1: error: invalid syntax. Perhaps you forgot a comma?\nFound 1 error in 1 file (errors prevented further checking)\n== Return code: 2\n[out version>=3.10.3]\npkg/x.py:1: error: invalid syntax\nFound 1 error in 1 file (errors prevented further checking)\n== Return code: 2\n\n[case testCmdlinePackageAndFile]\n# cmd: mypy -p pkg file\n[out]\nusage: mypy [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\nmypy: error: May only specify one of: module/package, files, or command.\n== Return code: 2\n\n[case testCmdlinePackageAndIniFiles]\n# cmd: mypy -p pkg\n[file mypy.ini]\n\\[mypy]\nfiles=file\n[file pkg.py]\nx = 0  # type: str\n[file file.py]\ny = 0  # type: str\n[out]\npkg.py:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n\n[case testCmdlineModuleAndIniFiles]\n# cmd: mypy -m pkg\n[file mypy.ini]\n\\[mypy]\nfiles=file\n[file pkg.py]\nx = 0  # type: str\n[file file.py]\ny = 0  # type: str\n[out]\npkg.py:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testCmdlineNonInteractiveWithoutInstallTypes]\n# cmd: mypy --non-interactive -m pkg\n[out]\nerror: --non-interactive is only supported with --install-types\n== Return code: 2\n\n[case testCmdlineNonInteractiveInstallTypesNothingToDo]\n# cmd: mypy --install-types --non-interactive -m pkg\n[file pkg.py]\n1()\n[out]\npkg.py:1: error: \"int\" not callable\n\n[case testCmdlineNonInteractiveInstallTypesNothingToDoNoError]\n# cmd: mypy --install-types --non-interactive -m pkg\n[file pkg.py]\n1 + 2\n[out]\n\n[case testCmdlineNonInteractiveInstallTypesNoSitePackages]\n# cmd: mypy --install-types --non-interactive --no-site-packages -m pkg\n[out]\nerror: --install-types not supported without python executable or site packages\n== Return code: 2\n\n[case testCmdlineInteractiveInstallTypesNothingToDo]\n# cmd: mypy --install-types -m pkg\n[file pkg.py]\n1()\n[out]\npkg.py:1: error: \"int\" not callable\n\n[case testCmdlineExclude]\n# cmd: mypy --exclude abc .\n[file abc/apkg.py]\n1()\n[file b/bpkg.py]\n1()\n[file c/cpkg.py]\n1()\n[out]\nc/cpkg.py:1: error: \"int\" not callable\nb/bpkg.py:1: error: \"int\" not callable\n\n[case testCmdlineMultipleExclude]\n# cmd: mypy --exclude abc --exclude b/ .\n[file abc/apkg.py]\n1()\n[file b/bpkg.py]\n1()\n[file c/cpkg.py]\n1()\n[out]\nc/cpkg.py:1: error: \"int\" not callable\n\n[case testCmdlineCfgExclude]\n# cmd: mypy .\n[file mypy.ini]\n\\[mypy]\nexclude = abc\n[file abc/apkg.py]\n1()\n[file b/bpkg.py]\n1()\n[file c/cpkg.py]\n1()\n[out]\nc/cpkg.py:1: error: \"int\" not callable\nb/bpkg.py:1: error: \"int\" not callable\n\n[case testCmdlineCfgMultipleExclude]\n# cmd: mypy .\n[file mypy.ini]\n\\[mypy]\nexclude = (?x)(\n    ^abc/\n    |^b/\n  )\n[file abc/apkg.py]\n1()\n[file b/bpkg.py]\n1()\n[file c/cpkg.py]\n1()\n[out]\nc/cpkg.py:1: error: \"int\" not callable\n\n[case testCmdlineTimingStats]\n# cmd: mypy --timing-stats timing.txt .\n[file b/__init__.py]\n[file b/c.py]\nclass C: pass\n[outfile-re timing.txt]\n.*\nb \\d+\nb\\.c \\d+\n.*\n\n[case testShadowTypingModuleEarlyLoad]\n# cmd: mypy dir\n[file dir/__init__.py]\nfrom typing import Union\n\ndef foo(a: Union[int, str]) -> str:\n    return str\n[file typing.py]\n# Since this file will be picked by mypy itself, we need it to be a fully-working typing\n# A bare minimum would be NamedTuple and TypedDict, which are used in runtime,\n# everything else technically can be just mocked.\nimport sys\nimport os\ndel sys.modules[\"typing\"]\npath = sys.path\ntry:\n    sys.path.remove(os.getcwd())\nexcept ValueError:\n    sys.path.remove(\"\")  # python 3.6\nfrom typing import *\nsys.path = path\n[out]\nmypy: \"typing.py\" shadows library module \"typing\"\nnote: A user-defined top-level module with name \"typing\" is not supported\n== Return code: 2\n\n[case testCustomTypeshedDirWithRelativePathDoesNotCrash]\n# cmd: mypy --custom-typeshed-dir dir dir/typing.pyi\n[file dir/stdlib/abc.pyi]\n[file dir/stdlib/builtins.pyi]\n[file dir/stdlib/sys.pyi]\n[file dir/stdlib/types.pyi]\n[file dir/stdlib/typing.pyi]\n[file dir/stdlib/typing_extensions.pyi]\n[file dir/stdlib/_typeshed.pyi]\n[file dir/stdlib/_collections_abc.pyi]\n[file dir/stdlib/collections/abc.pyi]\n[file dir/stdlib/collections/__init__.pyi]\n[file dir/stdlib/VERSIONS]\n[out]\nFailed to find builtin module mypy_extensions, perhaps typeshed is broken?\n== Return code: 2\n\n[case testNewTypeInferenceFlagDeprecated]\n# cmd: mypy --new-type-inference a.py\n[file a.py]\npass\n[out]\nWarning: --new-type-inference flag is deprecated; new type inference algorithm is already enabled by default\n== Return code: 0\n\n[case testCustomTypeshedDirFilePassedExplicitly]\n# cmd: mypy --custom-typeshed-dir dir m.py dir/stdlib/foo.pyi\n[file m.py]\n1()\n[file dir/stdlib/abc.pyi]\n1()  # Errors are not reported from typeshed by default\n[file dir/stdlib/builtins.pyi]\nclass object: pass\nclass str(object): pass\nclass int(object): pass\nclass list: pass\nclass dict: pass\n[file dir/stdlib/sys.pyi]\n[file dir/stdlib/types.pyi]\n[file dir/stdlib/typing.pyi]\n[file dir/stdlib/mypy_extensions.pyi]\n[file dir/stdlib/typing_extensions.pyi]\n[file dir/stdlib/_typeshed.pyi]\n[file dir/stdlib/_collections_abc.pyi]\n[file dir/stdlib/collections/abc.pyi]\n[file dir/stdlib/collections/__init__.pyi]\n[file dir/stdlib/foo.pyi]\n1()  # Errors are reported if the file was explicitly passed on the command line\n[file dir/stdlib/VERSIONS]\n[out]\ndir/stdlib/foo.pyi:1: error: \"int\" not callable\nm.py:1: error: \"int\" not callable\n\n[case testFileInPythonPathPassedExplicitly1]\n# cmd: mypy $CWD/pypath/foo.py\n[file pypath/foo.py]\n1()\n[out]\npypath/foo.py:1: error: \"int\" not callable\n\n[case testFileInPythonPathPassedExplicitly2]\n# cmd: mypy pypath/foo.py\n[file pypath/foo.py]\n1()\n[out]\npypath/foo.py:1: error: \"int\" not callable\n\n[case testFileInPythonPathPassedExplicitly3]\n# cmd: mypy -p foo\n# cwd: pypath\n[file pypath/foo/__init__.py]\n1()\n[file pypath/foo/m.py]\n1()\n[out]\nfoo/m.py:1: error: \"int\" not callable\nfoo/__init__.py:1: error: \"int\" not callable\n\n[case testFileInPythonPathPassedExplicitly4]\n# cmd: mypy -m foo\n# cwd: pypath\n[file pypath/foo.py]\n1()\n[out]\nfoo.py:1: error: \"int\" not callable\n\n[case testFileInPythonPathPassedExplicitly5]\n# cmd: mypy -m foo.m\n# cwd: pypath\n[file pypath/foo/__init__.py]\n1()  # TODO: Maybe this should generate errors as well? But how would we decide?\n[file pypath/foo/m.py]\n1()\n[out]\nfoo/m.py:1: error: \"int\" not callable\n\n[case testCmdlineCfgEnableErrorCodeTrailingComma]\n# cmd: mypy .\n[file mypy.ini]\n\\[mypy]\nenable_error_code =\n  truthy-bool,\n  redundant-expr,\n[out]\n\n[case testCmdlineCfgDisableErrorCodeTrailingComma]\n# cmd: mypy .\n[file mypy.ini]\n\\[mypy]\ndisable_error_code =\n  misc,\n  override,\n[out]\n\n[case testCmdlineCfgAlwaysTrueTrailingComma]\n# cmd: mypy .\n[file mypy.ini]\n\\[mypy]\nalways_true =\n  MY_VAR,\n[out]\n\n[case testTypeVarTupleUnpackEnabled]\n# cmd: mypy --enable-incomplete-feature=TypeVarTuple --enable-incomplete-feature=Unpack a.py\n[file a.py]\nfrom typing_extensions import TypeVarTuple\nTs = TypeVarTuple(\"Ts\")\n[out]\nWarning: TypeVarTuple is already enabled by default\nWarning: Unpack is already enabled by default\n== Return code: 0\n"
  },
  {
    "path": "test-data/unit/daemon-based.test",
    "content": "-- End-to-end test cases for the daemon (dmypy).\n-- These are special because they run multiple shell commands.\n\n[case testDaemonBaseline]\n$ dmypy start -- --no-error-summary\nDaemon started\n$ dmypy check test.py\n$ {python} -c \"print('\\n')\" >> test.py\n$ dmypy recheck\n[file .mypy/baseline.json]\n{\n    \"files\": {\n        \"test.py\": [\n            {\n                \"code\": \"name-defined\",\n                \"column\": 0,\n                \"message\": \"Name \\\"a\\\" is not defined\",\n                \"offset\": 1,\n                \"src\": \"a\",\n                \"target\": \"test\"\n            }\n        ]\n    },\n    \"format\": \"1.7\",\n    \"targets\": [\n        \"file:test.py\"\n    ]\n}\n[file test.py]\na\n"
  },
  {
    "path": "test-data/unit/daemon.test",
    "content": "-- End-to-end test cases for the daemon (dmypy).\n-- These are special because they run multiple shell commands.\n\n[case testDaemonStartStop]\n$ dmypy start -- --follow-imports=error\nDaemon started\n$ dmypy stop\nDaemon stopped\n\n[case testDaemonBasic]\n$ dmypy start -- --follow-imports=error\nDaemon started\n$ dmypy check -- foo.py\nSuccess: no issues found in 1 source file\n$ dmypy recheck\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f(): pass\n\n[case testDaemonRun]\n$ dmypy run -- foo.py --follow-imports=error\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f(): pass\n\n[case testDaemonRunIgnoreMissingImports]\n$ dmypy run -- foo.py --follow-imports=error --ignore-missing-imports\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f(): pass\n\n[case testDaemonRunErrorCodes]\n$ dmypy run -- foo.py --follow-imports=error --disable-error-code=type-abstract\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f(): pass\n\n[case testDaemonRunCombinedOptions]\n$ dmypy run -- foo.py --follow-imports=error --ignore-missing-imports --disable-error-code=type-abstract\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f(): pass\n\n[case testDaemonIgnoreConfigFiles]\n$ dmypy start -- --follow-imports=error\nDaemon started\n[file mypy.ini]\n\\[mypy]\nfiles = ./foo.py\n\n[case testDaemonRunMultipleStrict]\n$ dmypy run -- foo.py --strict --follow-imports=error\nDaemon started\nfoo.py:1: error: Function is missing a return type annotation\nfoo.py:1: note: Use \"-> None\" if function does not return a value\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n$ dmypy run -- bar.py --strict --follow-imports=error\nbar.py:1: error: Function is missing a return type annotation\nbar.py:1: note: Use \"-> None\" if function does not return a value\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n$ dmypy run -- foo.py --strict --follow-imports=error\nfoo.py:1: error: Function is missing a return type annotation\nfoo.py:1: note: Use \"-> None\" if function does not return a value\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n[file foo.py]\ndef f(): pass\n[file bar.py]\ndef f(): pass\n\n[case testDaemonRunRestart]\n$ dmypy run -- foo.py --follow-imports=error\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy run -- foo.py --follow-imports=error\nSuccess: no issues found in 1 source file\n$ {python} -c \"print('[mypy]')\" >mypy.ini\n$ {python} -c \"print('disallow_untyped_defs = True')\" >>mypy.ini\n$ dmypy run -- foo.py --follow-imports=error\nRestarting: configuration changed\nDaemon stopped\nDaemon started\nfoo.py:1: error: Function is missing a return type annotation\nfoo.py:1: note: Use \"-> None\" if function does not return a value\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n$ {python} -c \"print('def f() -> None: pass')\" >foo.py\n$ dmypy run -- foo.py --follow-imports=error\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f(): pass\n\n[case testDaemonRunRestartPretty]\n$ dmypy run -- foo.py --follow-imports=error --pretty\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy run -- foo.py --follow-imports=error --pretty\nSuccess: no issues found in 1 source file\n$ {python} -c \"print('[mypy]')\" >mypy.ini\n$ {python} -c \"print('disallow_untyped_defs = True')\" >>mypy.ini\n$ dmypy run -- foo.py --follow-imports=error --pretty\nRestarting: configuration changed\nDaemon stopped\nDaemon started\nfoo.py:1: error: Function is missing a return type annotation\n    def f():\n    ^\nfoo.py:1: note: Use \"-> None\" if function does not return a value\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n$ {python} -c \"print('def f() -> None: pass')\" >foo.py\n$ dmypy run -- foo.py --follow-imports=error --pretty\nSuccess: no issues found in 1 source file\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef f():\n     pass\n\n[case testDaemonRunRestartPluginVersion]\n$ dmypy run -- foo.py --no-error-summary\nDaemon started\n$ {python} -c \"print(' ')\" >> plug.py\n$ dmypy run -- foo.py --no-error-summary\nRestarting: plugins changed\nDaemon stopped\nDaemon started\n$ dmypy stop\nDaemon stopped\n[file mypy.ini]\n\\[mypy]\nfollow_imports = error\nplugins = plug.py\n[file foo.py]\npass\n[file plug.py]\nfrom mypy.plugin import Plugin\nclass Dummy(Plugin): pass\ndef plugin(version): return Dummy\n\n[case testDaemonRunRestartGlobs]\n-- Ensure dmypy is not restarted if the configuration doesn't change and it contains globs\n-- Note: Backslash path separator in output is replaced with forward slash so the same test succeeds on Windows as well\n$ dmypy run -- foo --follow-imports=error\nDaemon started\nfoo/lol.py:1: error: Name \"fail\" is not defined\nFound 1 error in 1 file (checked 3 source files)\n== Return code: 1\n$ dmypy run -- foo --follow-imports=error\nfoo/lol.py:1: error: Name \"fail\" is not defined\nFound 1 error in 1 file (checked 3 source files)\n== Return code: 1\n$ {python} -c \"print('[mypy]')\" >mypy.ini\n$ {python} -c \"print('ignore_errors=True')\" >>mypy.ini\n$ dmypy run -- foo --follow-imports=error\nRestarting: configuration changed\nDaemon stopped\nDaemon started\nSuccess: no issues found in 3 source files\n$ dmypy stop\nDaemon stopped\n[file mypy.ini]\n\\[mypy]\nignore_errors = True\n\\[mypy-*.lol]\nignore_errors = False\n\n[file foo/__init__.py]\n[file foo/lol.py]\nfail\n[file foo/ok.py]\na: int = 1\n\n[case testDaemonStatusKillRestartRecheck]\n$ dmypy status\nNo status file found\n== Return code: 2\n$ dmypy stop\nNo status file found\n== Return code: 2\n$ dmypy kill\nNo status file found\n== Return code: 2\n$ dmypy recheck\nNo status file found\n== Return code: 2\n$ dmypy start --  --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy status\nDaemon is up and running\n$ dmypy start\nDaemon is still alive\n== Return code: 2\n$ dmypy restart --  --follow-imports=error --no-error-summary\nDaemon stopped\nDaemon started\n$ dmypy stop\nDaemon stopped\n$ dmypy status\nNo status file found\n== Return code: 2\n$ dmypy restart --  --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy recheck\nCommand 'recheck' is only valid after a 'check' command\n== Return code: 2\n$ dmypy kill\nDaemon killed\n$ dmypy status\nDaemon has died\n== Return code: 2\n\n[case testDaemonRecheck]\n$ dmypy start -- --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy check foo.py bar.py\n$ dmypy recheck\n$ dmypy recheck --update foo.py --remove bar.py sir_not_appearing_in_this_film.py\nfoo.py:1: error: Import of \"bar\" ignored  [misc]\nfoo.py:1: note: (Using --follow-imports=error, module not passed on command line)\n== Return code: 1\n$ dmypy recheck --update bar.py\n$ dmypy recheck --update sir_not_appearing_in_this_film.py\n$ dmypy recheck --update --remove\n$ dmypy stop\nDaemon stopped\n[file foo.py]\nimport bar\n[file bar.py]\npass\n\n[case testDaemonTimeout]\n$ dmypy start --timeout 1 -- --follow-imports=error\nDaemon started\n$ {python} -c \"import time;time.sleep(1)\"\n$ dmypy status\nNo status file found\n== Return code: 2\n\n[case testDaemonRunNoTarget]\n$ dmypy run -- --follow-imports=error\nDaemon started\nmypy-daemon: error: Missing target module, package, files, or command.\n== Return code: 2\n$ dmypy stop\nDaemon stopped\n\n[case testDaemonRunTwoFilesFullTypeshed]\n$ dmypy run x.py\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy run y.py\nSuccess: no issues found in 1 source file\n$ dmypy run x.py\nSuccess: no issues found in 1 source file\n[file x.py]\n[file y.py]\n\n[case testDaemonCheckTwoFilesFullTypeshed]\n$ dmypy start\nDaemon started\n$ dmypy check foo.py\nfoo.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n$ dmypy check bar.py\nSuccess: no issues found in 1 source file\n$ dmypy check foo.py\nfoo.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\nFound 1 error in 1 file (checked 1 source file)\n== Return code: 1\n[file foo.py]\nfrom bar import add\nx: str = add(\"a\", \"b\")\nx_error: int = add(\"a\", \"b\")\n[file bar.py]\ndef add(a, b) -> str:\n    return a + b\n\n[case testDaemonWarningSuccessExitCode-posix]\n$ dmypy run -- foo.py --follow-imports=error --python-version=3.11\nDaemon started\nfoo.py:2: note: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\nSuccess: no issues found in 1 source file\n$ echo $?\n0\n$ dmypy stop\nDaemon stopped\n[file foo.py]\ndef foo():\n    a: int = 1\n    print(a + \"2\")\n\n-- this is carefully constructed to be able to break if the quickstart system lets\n-- something through incorrectly. in particular, the files need to have the same size\n[case testDaemonQuickstart]\n$ {python} -c \"print('x=1')\" >foo.py\n$ {python} -c \"print('x=1')\" >bar.py\n$ mypy --no-nonlocal-partial-types --cache-fine-grained --follow-imports=error --no-sqlite-cache --python-version=3.11 --no-color-output -- foo.py bar.py\nSuccess: no issues found in 2 source files\n$ {python} -c \"import shutil; shutil.copy('.mypy_cache/3.11/bar.meta.json', 'asdf.json')\"\n-- update bar's timestamp but don't change the file\n$ {python} -c \"import time;time.sleep(1)\"\n$ {python} -c \"print('x=1')\" >bar.py\n$ dmypy run -- foo.py bar.py --follow-imports=error --use-fine-grained-cache --no-sqlite-cache --python-version=3.11\nDaemon started\nSuccess: no issues found in 2 source files\n$ dmypy status --fswatcher-dump-file test.json\nDaemon is up and running\n$ dmypy stop\nDaemon stopped\n-- copy the original bar cache file back so that the mtime mismatches\n$ {python} -c \"import shutil; shutil.copy('asdf.json', '.mypy_cache/3.11/bar.meta.json')\"\n-- sleep guarantees timestamp changes\n$ {python} -c \"import time;time.sleep(1)\"\n$ {python} -c \"print('lol')\" >foo.py\n$ dmypy run --log-file=log -- foo.py bar.py --follow-imports=error --use-fine-grained-cache --no-sqlite-cache --python-version=3.11 --quickstart-file test.json\nDaemon started\nfoo.py:1: error: Name \"lol\" is not defined\nFound 1 error in 1 file (checked 2 source files)\n== Return code: 1\n-- make sure no errors made it to the log file\n$ {python} -c \"import sys; sys.stdout.write(open('log').read())\"\n-- make sure the meta file didn't get updated. we use this as an imperfect proxy for\n-- whether the source file got rehashed, which we don't want it to have been.\n$ {python} -c \"x = open('.mypy_cache/3.11/bar.meta.json').read(); y = open('asdf.json').read(); assert x == y\"\n\n[case testDaemonSuggest]\n$ dmypy start --log-file log.txt -- --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy suggest foo:foo\nCommand 'suggest' is only valid after a 'check' command (that produces no parse errors)\n== Return code: 2\n$ dmypy check foo.py bar.py\n$ dmypy suggest foo.bar\nUnknown function foo.bar\n== Return code: 2\n$ dmypy suggest foo.var\nObject foo.var is not a function\n== Return code: 2\n$ dmypy suggest foo.Foo.var\nUnknown class foo.Foo\n== Return code: 2\n$ dmypy suggest foo.Bar.baz\nUnknown method foo.Bar.baz\n== Return code: 2\n$ dmypy suggest foo.foo.baz\nObject foo.foo is not a class\n== Return code: 2\n$ dmypy suggest --callsites foo.foo\nbar.py:3: (str)\nbar.py:4: (arg=str)\n$ dmypy suggest foo.foo\n(str) -> int\n$ {python} -c \"import shutil; shutil.copy('foo2.py', 'foo.py')\"\n$ dmypy check foo.py bar.py\nbar.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")  [assignment]\n== Return code: 1\n[file foo.py]\ndef foo(arg):\n    return 12\nclass Bar:\n    def bar(self): pass\nvar = 0\n[file foo2.py]\ndef foo(arg: str) -> int:\n    return 12\nclass Bar:\n    def bar(self) -> None: pass\nvar = 0\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    x = foo('abc')  # type: str\n    foo(arg='xyz')\n\n[case testDaemonInspectCheck]\n$ dmypy start\nDaemon started\n$ dmypy check foo.py\nSuccess: no issues found in 1 source file\n$ dmypy check foo.py --export-types\nSuccess: no issues found in 1 source file\n$ dmypy inspect foo.py:1:1\n\"int\"\n[file foo.py]\nx = 1\n\n[case testDaemonInspectRun]\n$ dmypy run -- test1.py\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy run -- test2.py\nSuccess: no issues found in 1 source file\n$ dmypy run --export-types -- test1.py\nSuccess: no issues found in 1 source file\n$ dmypy inspect test1.py:1:1\n\"int\"\n[file test1.py]\na: int\n[file test2.py]\na: str\n\n[case testDaemonGetType]\n$ dmypy start --log-file log.txt -- --follow-imports=error --no-error-summary --python-version 3.8\nDaemon started\n$ dmypy inspect foo:1:2:3:4\nCommand \"inspect\" is only valid after a \"check\" command (that produces no parse errors)\n== Return code: 2\n$ dmypy check foo.py --export-types\nfoo.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\n== Return code: 1\n$ dmypy inspect foo:1\nFormat should be file:line:column[:end_line:end_column]\n== Return code: 2\n$ dmypy inspect foo:1:2:3\nSource file is not a Python file\n== Return code: 2\n$ dmypy inspect foo.py:1:2:a:b\ninvalid literal for int() with base 10: 'a'\n== Return code: 2\n$ dmypy inspect foo.pyc:1:1:2:2\nSource file is not a Python file\n== Return code: 2\n$ dmypy inspect bar/baz.py:1:1:2:2\nUnknown module: bar/baz.py\n== Return code: 1\n$ dmypy inspect foo.py:3:1:1:1\n\"end_line\" must not be before \"line\"\n== Return code: 2\n$ dmypy inspect foo.py:3:3:3:1\n\"end_column\" must be after \"column\"\n== Return code: 2\n$ dmypy inspect foo.py:3:10:3:17\n\"str\"\n$ dmypy inspect foo.py:3:10:3:17 -vv\n\"builtins.str\"\n$ dmypy inspect foo.py:9:9:9:11\n\"int\"\n$ dmypy inspect foo.py:11:1:11:3\n\"Callable[[Optional[int]], None]\"\n$ dmypy inspect foo.py:11:1:13:1\n\"None\"\n$ dmypy inspect foo.py:1:2:3:4\nCan't find expression at span 1:2:3:4\n== Return code: 1\n$ dmypy inspect foo.py:17:5:17:5\nNo known type available for \"NameExpr\" (maybe unreachable or try --force-reload)\n== Return code: 1\n\n[file foo.py]\nfrom typing import Optional\n\nx: int = \"no way\"  # line 3\n\ndef foo(arg: Optional[int] = None) -> None:\n    if arg is None:\n        arg\n    else:\n        arg  # line 9\n\nfoo(\n    # multiline\n)\n\ndef unreachable(x: int) -> None:\n    return\n    x  # line 17\n\n[case testDaemonGetTypeInexact]\n$ dmypy start --log-file log.txt -- --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy check foo.py --export-types\n$ dmypy inspect foo.py:1:a\ninvalid literal for int() with base 10: 'a'\n== Return code: 2\n$ dmypy inspect foo.pyc:1:2\nSource file is not a Python file\n== Return code: 2\n$ dmypy inspect bar/baz.py:1:2\nUnknown module: bar/baz.py\n== Return code: 1\n$ dmypy inspect foo.py:7:5 --include-span\n7:5:7:5 -> \"int\"\n7:5:7:11 -> \"int\"\n7:1:7:12 -> \"None\"\n$ dmypy inspect foo.py:7:5 --include-kind\nNameExpr -> \"int\"\nOpExpr -> \"int\"\nCallExpr -> \"None\"\n$ dmypy inspect foo.py:7:5 --include-span --include-kind\nNameExpr:7:5:7:5 -> \"int\"\nOpExpr:7:5:7:11 -> \"int\"\nCallExpr:7:1:7:12 -> \"None\"\n$ dmypy inspect foo.py:7:5 -vv\n\"builtins.int\"\n\"builtins.int\"\n\"None\"\n$ dmypy inspect foo.py:7:5 -vv --limit=1\n\"builtins.int\"\n$ dmypy inspect foo.py:7:3\n\"Callable[[int], None]\"\n\"None\"\n$ dmypy inspect foo.py:1:2\nCan't find any expressions at position 1:2\n== Return code: 1\n$ dmypy inspect foo.py:11:5 --force-reload\nNo known type available for \"NameExpr\" (maybe unreachable)\nNo known type available for \"OpExpr\" (maybe unreachable)\n== Return code: 1\n\n[file foo.py]\nfrom typing import Optional\n\ndef foo(x: int) -> None: ...\n\na: int\nb: int\nfoo(a and b)  # line 7\n\ndef unreachable(x: int, y: int) -> None:\n    return\n    x and y  # line 11\n\n[case testDaemonGetAttrs]\n$ dmypy start --log-file log.txt -- --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy check foo.py bar.py --export-types\n$ dmypy inspect foo.py:9:1 --show attrs --include-span --include-kind -vv\nNameExpr:9:1:9:1 -> {\"foo.C\": [\"a\", \"x\", \"y\"], \"foo.B\": [\"a\", \"b\"]}\n$ dmypy inspect foo.py:11:10 --show attrs\nNo known type available for \"StrExpr\" (maybe unreachable or try --force-reload)\n== Return code: 1\n$ dmypy inspect foo.py:1:1 --show attrs\nCan't find any expressions at position 1:1\n== Return code: 1\n$ dmypy inspect --show attrs bar.py:10:1\n{\"A\": [\"z\"], \"B\": [\"z\"]}\n$ dmypy inspect --show attrs bar.py:10:1 --union-attrs\n{\"A\": [\"x\", \"z\"], \"B\": [\"y\", \"z\"]}\n\n[file foo.py]\nclass B:\n    def b(self) -> int: return 0\n    a: int\nclass C(B):\n    a: int\n    y: int\n    def x(self) -> int: return 0\n\nv: C  # line 9\nif False:\n    \"unreachable\"\n\n[file bar.py]\nfrom typing import Union\n\nclass A:\n    x: int\n    z: int\nclass B:\n    y: int\n    z: int\nvar: Union[A, B]\nvar  # line 10\n\n[case testDaemonGetDefinition]\n$ dmypy start --log-file log.txt -- --follow-imports=error --no-error-summary\nDaemon started\n$ dmypy check foo.py bar/baz.py bar/__init__.py --export-types\n$ dmypy inspect foo.py:5:1 --show definition\nfoo.py:4:1:y\n$ dmypy inspect foo.py:2:3 --show definition --include-span --include-kind -vv\nMemberExpr:2:1:2:7 -> bar/baz.py:3:5:Alias\n$ dmypy inspect foo.py:3:1 --show definition\nCannot find definition for \"NameExpr\" at 3:1:3:1\n== Return code: 1\n$ dmypy inspect foo.py:4:6 --show definition\nNo name or member expressions at 4:6\n== Return code: 1\n$ dmypy inspect foo.py:7:1:7:6 --show definition\nbar/baz.py:4:5:attr\n$ dmypy inspect foo.py:10:10 --show definition --include-span\n10:1:10:12 -> bar/baz.py:6:1:test\n$ dmypy inspect foo.py:14:6 --show definition --include-span --include-kind\nNameExpr:14:5:14:7 -> foo.py:13:9:arg\nMemberExpr:14:5:14:9 -> bar/baz.py:9:5:x, bar/baz.py:11:5:x\n\n[file foo.py]\nfrom bar.baz import A, B, C\nC.Alias\nx  # type: ignore\ny = 42\ny  # line 5\nz = C()\nz.attr\n\nimport bar\nbar.baz.test()  # line 10\n\nfrom typing import Union\ndef foo(arg: Union[A, B]) -> None:\n    arg.x\n\n[file bar/__init__.py]\n[file bar/baz.py]\nfrom typing import Union\nclass C:\n    Alias = Union[int, str]\n    attr = 42\n\ndef test() -> None: ...  # line 6\n\nclass A:\n    x: int\nclass B:\n    x: int\n\n[case testDaemonInspectSelectCorrectFile]\n$ dmypy run --export-types -- test.py\nDaemon started\nSuccess: no issues found in 1 source file\n$ dmypy inspect demo/test.py:1:1\n\"int\"\n$ dmypy inspect test.py:1:1\n\"str\"\n[file test.py]\nb: str\nfrom demo.test import a\n[file demo/test.py]\na: int\n"
  },
  {
    "path": "test-data/unit/deps-classes.test",
    "content": "-- Test cases for generating fine-grained dependencies for classes.\n--\n-- The dependencies are used for fined-grained incremental checking.\n--\n-- See the comment at the top of deps.test for more documentation.\n\n-- TODO: Move class related test cases from deps.test to here\n\n[case testNamedTuple]\nfrom typing import NamedTuple, Any\nfrom a import A\nN = NamedTuple('N', [('a', 'A')])\n\ndef f(a: Any) -> None:\n    n = N(a)\n    n.a\n[file a.py]\nclass A: pass\n[builtins fixtures/tuple.pyi]\n[out]\n<m.N.__init__> -> m.f\n<m.N.__new__> -> m.f\n<m.N.a> -> m.f\n<m.N> -> m.f\n<a.A> -> <m.N.a>, <m.N>, m\n<a> -> m\n\n[case testNamedTuple2]\nfrom typing import NamedTuple, Any, Tuple\nfrom a import A, B\nN = NamedTuple('N', [('a', 'Tuple[A, B]')])\n\ndef f(a: Any) -> None:\n    n = N(a)\n    n.a\n[file a.py]\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\n<m.N.__init__> -> m.f\n<m.N.__new__> -> m.f\n<m.N.a> -> m.f\n<m.N> -> m.f\n<a.A> -> <m.N.a>, <m.N>, m\n<a.B> -> <m.N.a>, <m.N>, m\n<a> -> m\n\n[case testNamedTuple3]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int)])\nx = N(1)\nM = NamedTuple('M', [('z', 'N')])\ny = M(x)\n[builtins fixtures/tuple.pyi]\n[out]\n<m.M.__init__> -> m\n<m.M.__new__> -> m\n<m.M> -> <m.y>, m\n<m.N.__init__> -> m\n<m.N.__new__> -> m\n<m.N> -> <m.M.z>, <m.M>, <m.x>, <m.y>, m\n<m.x> -> m\n<m.y> -> m\n\n[case testNamedTuple4]\nfrom typing import NamedTuple, Any\nfrom a import A\nclass N(NamedTuple):\n    a: A\n\ndef f(a: Any) -> None:\n    n = N(a)\n    n.a\n[file a.py]\nclass A: pass\n[builtins fixtures/tuple.pyi]\n[out]\n<m.N.__init__> -> m.f\n<m.N.__new__> -> m.f\n<m.N.a> -> m.f\n<m.N> -> m.N, m.f\n<a.A> -> <m.N.a>, <m.N>, m, m.N\n<a> -> m\n\n[case testIfFalseInClassBody]\nclass A:\n    if False:\n        x = None  # type: str\n        x.foo()\n[builtins fixtures/bool.pyi]\n[out]\n<m.A> -> m.A\n\n[case testAlwaysFalseIsinstanceInClassBody]\nclass A:\n    x: int\n    if isinstance(x, str):\n        y: str = None\n        y.foo()\n[builtins fixtures/isinstance.pyi]\n[out]\n<m.A> -> m.A\n\n[case testDoubleAttributeInitializationToNone]\nclass C:\n    def __init__(self) -> None:\n        self.x = None\n        self.x = None\n[out]\n<m.C.x> -> m.C.__init__\n<m.C> -> m.C\n\n[case testClassNestedWithinFunction]\nclass C: pass\n\ndef f() -> None:\n    class S1(C): pass\n\nclass D:\n    def g(self) -> None:\n        class S2(C): pass\n[out]\n-- TODO: Is it okay to have targets like m.S1@4.__init__?\n<m.C.(abstract)> -> <m.S1@4.__init__>, <m.S2@8.__init__>, m.D.g, m.f\n<m.C.__init__> -> <m.S1@4.__init__>, <m.S2@8.__init__>\n<m.C.__new__> -> <m.S1@4.__new__>, <m.S2@8.__new__>\n<m.C> -> m.C, m.D.g, m.f\n<m.D.g> -> m.D.g\n<m.D> -> m.D\n<m.f> -> m.f\n\n[case testClassSuper]\nclass C:\n    def __init__(self, x: int) -> None: pass\n    def foo(self) -> None: pass\n\nclass D(C):\n    def __init__(self, x: int) -> None:\n        super().__init__(x)\n        super().foo()\n[out]\n<m.C.(abstract)> -> <m.D.__init__>, m\n<m.C.__init__> -> <m.D.__init__>, m.D.__init__\n<m.C.__new__> -> <m.D.__new__>\n<m.C.foo> -> <m.D.foo>, m.D.__init__\n<m.C> -> m, m.C, m.D\n<m.D> -> m.D\n\n[case testClassMissingInit]\nclass C:\n    def __init__(self, x: int) -> None: pass\n\nclass D(C):\n    pass\n\ndef foo() -> None:\n    D(6)\n[out]\n<m.C.(abstract)> -> <m.D.__init__>, m\n<m.C.__init__> -> <m.D.__init__>\n<m.C.__new__> -> <m.D.__new__>\n<m.C> -> m, m.C, m.D\n<m.D.__init__> -> m.foo\n<m.D.__new__> -> m.foo\n<m.D> -> m.D, m.foo\n\n[case testClassBasedEnum]\nfrom enum import Enum\nfrom m import B\n\nclass A(Enum):\n    X = B()\n\ndef f(a: A) -> None:\n    pass\ndef g() -> None:\n    A.X\n[file m.py]\nclass B: pass\n[builtins fixtures/enum.pyi]\n[out]\n<m.A.X> -> m.g\n<m.A> -> <m.f>, m.A, m.f, m.g\n<m.B.__init__> -> m\n<m.B.__new__> -> m\n-- The <m.A.X> dependency target is superfluous but benign\n<m.B> -> <m.A.X>, m\n<m> -> m\n\n[case testClassAttribute]\nclass C:\n    x = 0\n\ndef f() -> None:\n    C.x\n\ndef g() -> None:\n    C.x = 1\n[out]\n<m.C.x> -> m.f, m.g\n<m.C> -> m.C, m.f, m.g\n\n[case testStaticAndClassMethods]\nclass C:\n    @staticmethod\n    def foo() -> None:\n        h()\n\n    @classmethod\n    def bar(cls) -> None:\n        h()\n\ndef fstatic() -> None:\n    C.foo()\n\ndef fclass() -> None:\n    C.bar()\n\ncc = C()\n\ndef gstatic() -> None:\n    cc.foo()\n\ndef gclass() -> None:\n    cc.bar()\n\ndef h() -> None: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n<m.C.__init__> -> m\n<m.C.__new__> -> m\n<m.C.bar> -> m, m.fclass, m.gclass\n<m.C.foo> -> m, m.fstatic, m.gstatic\n<m.C> -> <m.cc>, m, m.C, m.fclass, m.fstatic\n<m.cc> -> m, m.gclass, m.gstatic\n<m.h> -> m.C.bar, m.C.foo\n\n[case testClassAttributeWithMetaclass]\nclass M(type):\n    x = 1\nclass C(metaclass=M):\n    pass\ndef f() -> None:\n    C.x\n[out]\n<m.C.x> -> m.f\n<m.C> -> m.C, m.f\n<m.M.x> -> m.f\n<m.M> -> <m.C>, m, m.M\n"
  },
  {
    "path": "test-data/unit/deps-expressions.test",
    "content": "-- Test cases for generating fine-grained dependencies for expressions.\n--\n-- The dependencies are used for fined-grained incremental checking.\n--\n-- See the comment at the top of deps.test for more documentation.\n\n[case testListExpr]\ndef f() -> int: pass\ndef g() -> None:\n    a = [f()]\n[builtins fixtures/list.pyi]\n[out]\n<m.f> -> m.g\n\n[case testDictExpr]\ndef f1() -> int: pass\ndef f2() -> int: pass\ndef g() -> None:\n    a = {f1(): 1, 2: f2()}\n[builtins fixtures/dict.pyi]\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testSetExpr]\ndef f() -> int: pass\ndef g() -> None:\n    a = {f()}\n[builtins fixtures/set.pyi]\n[out]\n<m.f> -> m.g\n\n[case testTupleExpr]\ndef f1() -> int: pass\ndef f2() -> int: pass\ndef g() -> None:\n    a = (f1(), f2())\n[builtins fixtures/tuple.pyi]\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testListComprehension]\nfrom typing import Iterator\n\nclass A:\n    def __iter__(self) -> Iterator[int]: pass\n\ndef f1() -> int: pass\ndef f2() -> int: pass\ndef g() -> None:\n    a = [f1() for x in A() if f2()]\n[builtins fixtures/list.pyi]\n[out]\n<m.A.__init__> -> m.g\n<m.A.__iter__> -> m.g\n<m.A.__new__> -> m.g\n<m.A> -> m.A, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testSetComprehension]\nfrom typing import Set\ndef f1() -> int: pass\ndef f2() -> Set[int]: pass\ndef f3() -> int: pass\ndef g() -> None:\n    a = {f1() for x in f2() if f3()}\n[builtins fixtures/set.pyi]\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testDictComprehension]\nfrom typing import Iterator\n\nclass A:\n    def __iter__(self) -> Iterator[int]: pass\n\ndef f1() -> int: pass\ndef f2() -> int: pass\ndef f3() -> int: pass\ndef g() -> None:\n    a = {f1(): f2() for x in A() if f3()}\n[builtins fixtures/dict.pyi]\n[out]\n<m.A.__init__> -> m.g\n<m.A.__iter__> -> m.g\n<m.A.__new__> -> m.g\n<m.A> -> m.A, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testGeneratorExpr]\nfrom typing import List\ndef f1() -> int: pass\ndef f2() -> List[int]: pass\ndef f3() -> int: pass\ndef g() -> None:\n    a = (f1() for x in f2() if f3())\n[builtins fixtures/list.pyi]\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testConditionalExpr]\ndef f1() -> int: pass\ndef f2() -> int: pass\ndef f3() -> int: pass\ndef g() -> None:\n    a = f1() if f2() else f3()\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testAwaitExpr]\ndef f(): pass\nasync def g() -> None:\n    x = await f()\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n<m.f> -> m.g\n\n[case testStarExpr]\nfrom typing import Iterator\n\nclass A:\n    def __iter__(self) -> Iterator[int]: pass\n\ndef g() -> None:\n    a = [*A()]\n[builtins fixtures/list.pyi]\n[out]\n<m.A.__init__> -> m.g\n<m.A.__iter__> -> <m.A>, m.g\n<m.A.__new__> -> m.g\n<m.A> -> m.A, m.g, typing.Iterable\n\n[case testCast]\nfrom typing import cast\nclass A: pass\ndef f() -> object: pass\ndef g() -> None:\n    x = cast(A, f())\n[out]\n<m.A> -> m.A, m.g\n<m.f> -> m.g\n\n[case testTypeApplication]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Generic[T, S]):\n    def __init__(self, x): pass\nclass B: pass\nclass C: pass\n\ndef f() -> int: pass\n\ndef g() -> None:\n    x = A[B, C](f())\n[out]\n<m.A.__init__> -> m.g\n<m.A.__new__> -> m.g\n<m.A> -> m.A, m.g\n<m.B> -> m.B, m.g\n<m.C> -> m.C, m.g\n<m.S> -> m.A\n<m.T> -> m.A\n<m.f> -> m.g\n\n[case testIndexExpr]\nclass A:\n    def __getitem__(self, x: int) -> int: pass\n\ndef f1() -> A: pass\ndef f2() -> int: pass\n\ndef g(a: A) -> int:\n    return f1()[f2()]\n[out]\n<m.A.__getitem__> -> m.g\n<m.A> -> <m.f1>, <m.g>, m.A, m.f1, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testIndexExpr2]\nclass A:\n    def __getitem__(self, x: int) -> int: pass\n\ndef f1() -> A: pass\ndef f2() -> int: pass\n\ndef g(a: A) -> int:\n    return f1()[f2()]\n[out]\n<m.A.__getitem__> -> m.g\n<m.A> -> <m.f1>, <m.g>, m.A, m.f1, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testIndexExprLvalue]\nclass A:\n    def __setitem__(self, x: int, y: int) -> None: pass\n\ndef f1() -> A: pass\ndef f2() -> int: pass\ndef f3() -> int: pass\n\ndef g(a: A) -> None:\n    f1()[f2()] = f3()\n[out]\n-- __getitem__ dependency is redundant but harmless\n<m.A.__getitem__> -> m.g\n<m.A.__setitem__> -> m.g\n<m.A> -> <m.f1>, <m.g>, m.A, m.f1, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testUnaryExpr]\nclass A:\n    def __neg__(self) -> int: pass\n    def __pos__(self) -> int: pass\n    def __invert__(self) -> int: pass\n\ndef f1() -> A: pass\ndef f2() -> A: pass\ndef f3() -> A: pass\n\ndef g1() -> int:\n    return +f1()\ndef g2() -> int:\n    return -f2()\ndef g3() -> int:\n    return ~f3()\n[out]\n<m.A.__invert__> -> m.g3\n<m.A.__neg__> -> m.g2\n<m.A.__pos__> -> m.g1\n<m.A> -> <m.f1>, <m.f2>, <m.f3>, m.A, m.f1, m.f2, m.f3\n<m.f1> -> m.g1\n<m.f2> -> m.g2\n<m.f3> -> m.g3\n\n[case testOpExpr]\nclass A:\n    def __add__(self, x: 'B') -> int: pass\nclass B: pass\n\ndef f() -> int:\n    a: A\n    b: B\n    return a + b\n[out]\n<m.A.__add__> -> m.f\n<m.A> -> m.A, m.f\n<m.B.__radd__> -> m.f\n<m.B> -> <m.A.__add__>, m.A.__add__, m.B, m.f\n\n[case testComparisonExpr]\nclass A:\n    def __lt__(self, x: 'B') -> int: pass\nclass B: pass\n\ndef f() -> int:\n    return A() < B()\n[out]\n<m.A.__init__> -> m.f\n<m.A.__lt__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.B.__gt__> -> m.f\n<m.B.__init__> -> m.f\n<m.B.__new__> -> m.f\n<m.B> -> <m.A.__lt__>, m.A.__lt__, m.B, m.f\n\n[case testIsOp]\nclass A: pass\nclass B: pass\n\ndef f() -> bool:\n    return A() is B()\n[builtins fixtures/bool.pyi]\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.B.__init__> -> m.f\n<m.B.__new__> -> m.f\n<m.B> -> m.B, m.f\n\n[case testInOp]\nclass A:\n    def __contains__(self, x: B) -> int: pass\nclass B: pass\n\ndef f() -> bool:\n    return B() in A()\n[builtins fixtures/bool.pyi]\n[out]\n<m.A.__contains__> -> m.f\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.B.__init__> -> m.f\n<m.B.__new__> -> m.f\n<m.B> -> <m.A.__contains__>, m.A.__contains__, m.B, m.f\n\n[case testComparisonExprWithMultipleOperands]\nclass A:\n    def __lt__(self, x: 'B') -> int: pass\nclass B: pass\nclass C:\n    def __ge__(self, x: 'B') -> int: pass\n\ndef f() -> int:\n    return A() < B() <= C()\n[out]\n<m.A.__init__> -> m.f\n<m.A.__lt__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.B.__gt__> -> m.f\n<m.B.__init__> -> m.f\n<m.B.__le__> -> m.f\n<m.B.__new__> -> m.f\n<m.B> -> <m.A.__lt__>, <m.C.__ge__>, m.A.__lt__, m.B, m.C.__ge__, m.f\n<m.C.__ge__> -> m.f\n<m.C.__init__> -> m.f\n<m.C.__new__> -> m.f\n<m.C> -> m.C, m.f\n\n[case testOperatorWithTupleOperand]\nfrom typing import Tuple\n\nclass C(Tuple[int, str]):\n    def __and__(self, x: D) -> int: pass\n    def __neg__(self) -> int: pass\nclass D: pass\n\ndef f() -> None:\n    c: C\n    d: D\n    x = c & d\n    y = -c\n[builtins fixtures/tuple.pyi]\n[out]\n<m.C.__and__> -> m.f\n<m.C.__neg__> -> m.f\n<m.C> -> m.C, m.f\n<m.D.__rand__> -> m.f\n<m.D> -> <m.C.__and__>, m.C.__and__, m.D, m.f\n\n[case testUnionTypeOperation]\nfrom typing import Union\n\nclass A:\n    def __add__(self, x: str) -> int: pass\nclass B:\n    def __add__(self, x: str) -> int: pass\n\ndef f(a: Union[A, B]) -> int:\n    return a + ''\n[out]\n<m.A.__add__> -> m.f\n<m.A> -> <m.f>, m.A, m.f\n<m.B.__add__> -> m.f\n<m.B> -> <m.f>, m.B, m.f\n\n[case testSliceExpr]\nclass A:\n    def __getitem__(self, x) -> None: pass\n\ndef f1() -> int: pass\ndef f2() -> int: pass\ndef f3() -> int: pass\ndef f4() -> int: pass\ndef f5() -> int: pass\n\ndef f() -> None:\n    a: A\n    a[f1():f2():f3()]\n    a[f4():]\n    a[::f5()]\n[builtins fixtures/slice.pyi]\n[out]\n<m.A.__getitem__> -> m.f\n<m.A> -> m.A, m.f\n<m.f1> -> m.f\n<m.f2> -> m.f\n<m.f3> -> m.f\n<m.f4> -> m.f\n<m.f5> -> m.f\n\n[case testRevealTypeExpr]\ndef f1() -> int: pass\ndef f() -> None:\n    reveal_type(f1())  # type: ignore\n[out]\n<m.f1> -> m.f\n\n[case testLambdaExpr]\nfrom typing import Callable\n\ndef f1(c: Callable[[int], str]) -> None: pass\ndef f2() -> str: pass\n\ndef g() -> None:\n    f1(lambda x: f2())\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testLiteralDepsExpr]\nfrom typing_extensions import Literal\n\nAlias = Literal[1]\n\na: Alias\nb = a\ndef f(x: Alias) -> None: pass\ndef g() -> Literal[1]:\n    return b\n[builtins fixtures/tuple.pyi]\n[out]\n<m.Alias> -> <m.f>, m, m.f\n<m.a> -> m\n<m.b> -> m, m.g\n"
  },
  {
    "path": "test-data/unit/deps-generics.test",
    "content": "-- Test cases for generating fine-grained dependencies involving generics.\n--\n-- The dependencies are used for fined-grained incremental checking.\n--\n-- See the comment at the top of deps.test for more documentation.\n\n[case testGenericFunction]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\nclass A: pass\n\ndef f(x: T) -> T:\n    y: T\n    z: A\n    return x\n[out]\n<m.A> -> m.A, m.f\n<m.T> -> <m.f>, m.f\n\n[case testGenericClass]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]): pass\nclass B: pass\n\ndef f() -> None:\n    a: A[B]\n[out]\n<m.A> -> m.A, m.f\n<m.B> -> m.B, m.f\n<m.T> -> m.A\n\n[case testGenericClassWithMembers]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    def g(self, a: T) -> None:\n        self.x = a\n    def f(self) -> T:\n        return self.x\n[out]\n<m.A.x> -> m.A.f, m.A.g\n<m.A> -> m.A\n<m.T> -> <m.A.f>, <m.A.g>, <m.A.x>, m.A, m.A.f, m.A.g\n\n[case testGenericClassInit]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    def __init__(self, a: T) -> None:\n        self.x = a\n\nclass B: pass\n\ndef f() -> None:\n    a = A(B())\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A.x> -> m.A.__init__\n<m.A> -> m.A, m.f\n<m.B.__init__> -> m.f\n<m.B.__new__> -> m.f\n<m.B> -> m.B, m.f\n<m.T> -> <m.A.__init__>, <m.A.x>, m.A, m.A.__init__\n\n[case testGenericMethod]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\nclass A:\n    def f(self, x: T) -> T:\n        return x\n[out]\n<m.A> -> m.A\n<m.T> -> <m.A.f>, m.A.f\n\n[case testGenericBaseClass]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]): pass\nclass B(A[C]): pass\nclass C: pass\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A> -> m, m.A, m.B\n<m.B> -> m.B\n<m.C> -> m, m.B, m.C\n<m.T> -> m.A\n\n[case testGenericBaseClass2]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]): pass\nclass B(A[T]): pass\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A> -> m, m.A, m.B\n<m.B> -> m.B\n<m.T> -> m, m.A, m.B\n\n[case testTypeVarBound]\nfrom typing import TypeVar, Tuple\n\nclass A: pass\nclass B: pass\n\nT = TypeVar('T', bound=Tuple[A, B])\n\ndef f(x: T) -> T:\n    return x\n[builtins fixtures/tuple.pyi]\n[out]\n<m.A> -> <m.T>, <m.f>, m, m.A, m.f\n<m.B> -> <m.T>, <m.f>, m, m.B, m.f\n<m.T> -> <m.f>, m.f\n\n[case testTypeVarBoundOperations]\nfrom typing import TypeVar, Tuple\n\nclass A:\n    def f(self) -> None: pass\n    def __add__(self, other: int) -> int: pass\n\nT = TypeVar('T', bound=A)\n\ndef f(x: T) -> None:\n    x.f()\n    x + 1\n[out]\n<m.A.__add__> -> m.f\n<m.A.f> -> m.f\n<m.A> -> <m.T>, <m.f>, m, m.A, m.f\n<m.T> -> <m.f>, m.f\n\n[case testTypeVarValues]\nfrom typing import TypeVar\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nT = TypeVar('T', A, B)\nS = TypeVar('S', C, D)\n\ndef f(x: T, y: S) -> S:\n    pass\n[out]\n<m.A> -> <m.T>, <m.f>, m, m.A, m.f\n<m.B> -> <m.T>, <m.f>, m, m.B, m.f\n<m.C> -> <m.S>, <m.f>, m, m.C, m.f\n<m.D> -> <m.S>, <m.f>, m, m.D, m.f\n<m.S> -> <m.f>, m.f\n<m.T> -> <m.f>, m.f\n\n[case testTypeVarValuesMethod]\nfrom typing import TypeVar, Generic\nclass C: pass\nclass D: pass\nS = TypeVar('S', C, D)\n\nclass G(Generic[S]):\n    def f(self) -> S:\n        pass\n[out]\n<m.C> -> <m.G.f>, <m.S>, m, m.C, m.G.f\n<m.D> -> <m.G.f>, <m.S>, m, m.D, m.G.f\n<m.G> -> m.G\n<m.S> -> <m.G.f>, m.G, m.G.f\n\n[case testTypeVarValuesMethodAttr]\nfrom typing import TypeVar, Generic\nclass A:\n    x: int\nclass B:\n    x: int\nT = TypeVar('T', A, B)\n\nclass G(Generic[T]):\n    def f(self, x: T) -> None:\n        x.x\n[out]\n<m.A.x> -> m.G.f\n<m.A> -> <m.G.f>, <m.T>, m, m.A, m.G.f\n<m.B.x> -> m.G.f\n<m.B> -> <m.G.f>, <m.T>, m, m.B, m.G.f\n<m.G> -> m.G\n<m.T> -> <m.G.f>, m.G, m.G.f\n"
  },
  {
    "path": "test-data/unit/deps-statements.test",
    "content": "-- Test cases for generating fine-grained dependencies for statements.\n--\n-- The dependencies are used for fined-grained incremental checking.\n--\n-- See the comment at the top of deps.test for more documentation.\n\n[case testIfStmt]\ndef f1() -> int: pass\ndef f2() -> None: pass\ndef f3() -> int: pass\ndef f4() -> None: pass\ndef f5() -> None: pass\n\ndef g() -> None:\n    if f1():\n        f2()\n    elif f3():\n        f4()\n    else:\n        f5()\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n<m.f4> -> m.g\n<m.f5> -> m.g\n\n[case testWhileStmt]\ndef f1() -> int: pass\ndef f2() -> None: pass\ndef f3() -> None: pass\n\ndef g() -> None:\n    while f1():\n        f2()\n    else:\n        f3()\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testAssertStmt]\ndef f1() -> int: pass\ndef f2() -> str: pass\ndef f3() -> int: pass\n\ndef g() -> None:\n    assert f1(), f2()\n    assert f3()\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testRaiseStmt]\ndef f1() -> BaseException: pass\ndef f2() -> BaseException: pass\n\ndef g1() -> None:\n    raise f1()\n\ndef g2() -> None:\n    raise f1() from f2()\n[builtins fixtures/exception.pyi]\n[out]\n<m.f1> -> m.g1, m.g2\n<m.f2> -> m.g2\n\n[case testTryFinallyStmt]\ndef f1() -> None: pass\ndef f2() -> None: pass\n\ndef g() -> None:\n    try:\n        f1()\n    finally:\n        f2()\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testForStmt]\nfrom typing import Iterator\n\nclass A:\n    def __iter__(self) -> Iterator[int]: pass\n\ndef f1() -> None: pass\ndef f2() -> None: pass\n\ndef g() -> None:\n    a: A\n    for x in a:\n        f1()\n    else:\n        f2()\n[builtins fixtures/list.pyi]\n[out]\n<m.A.__getitem__> -> m.g\n<m.A.__iter__> -> m.g\n<m.A> -> m.A, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testTryExceptStmt]\nclass A(BaseException): pass\nclass B(BaseException):\n    def f(self) -> None: pass\n\ndef f1() -> None: pass\ndef f2() -> None: pass\ndef f3() -> None: pass\n\ndef g() -> None:\n    try:\n        f1()\n    except A:\n        f2()\n    except B as e:\n        e.f()\n    else:\n        f3()\n[builtins fixtures/exception.pyi]\n[out]\n-- The dependencies on the ctor are basically spurious but not a problem\n<m.A.__init__> -> m.g\n<m.A.__new__> -> m.g\n<m.A> -> m.A, m.g\n<m.B.__init__> -> m.g\n<m.B.__new__> -> m.g\n<m.B.f> -> m.g\n<m.B> -> m.B, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n<m.f3> -> m.g\n\n[case testTryExceptStmt2]\nclass A(BaseException): pass\nclass B(BaseException):\n    def f(self) -> None: pass\n\ndef f1() -> None: pass\ndef f2() -> None: pass\n\ndef g() -> None:\n    try:\n        f1()\n    except (A, B):\n        f2()\n[builtins fixtures/exception.pyi]\n[out]\n-- The dependencies on the ctor are basically spurious but not a problem\n<m.A.__init__> -> m.g\n<m.A.__new__> -> m.g\n<m.A> -> m.A, m.g\n<m.B.__init__> -> m.g\n<m.B.__new__> -> m.g\n<m.B> -> m.B, m.g\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testWithStmt]\nfrom typing import Any\nclass A:\n    def __enter__(self) -> 'B': pass\n    def __exit__(self, a, b, c) -> None: pass\n\nclass B:\n    def f(self) -> None: pass\n\ndef g() -> None:\n    a: A\n    with a as x:\n        x.f()\n[out]\n<m.A.__enter__> -> m.g\n<m.A.__exit__> -> m.g\n<m.A> -> m.A, m.g\n<m.B.f> -> m.g\n<m.B> -> <m.A.__enter__>, m.A.__enter__, m.B\n\n[case testWithStmt2]\nfrom typing import Any\nclass A:\n    def __enter__(self) -> 'C': pass\n    def __exit__(self, a, b, c) -> None: pass\nclass B:\n    def __enter__(self) -> 'D': pass\n    def __exit__(self, a, b, c) -> None: pass\n\nclass C: pass\nclass D: pass\n\ndef g() -> None:\n    a: A\n    b: B\n    with a as x, b as y:\n        pass\n[out]\n<m.A.__enter__> -> m.g\n<m.A.__exit__> -> m.g\n<m.A> -> m.A, m.g\n<m.B.__enter__> -> m.g\n<m.B.__exit__> -> m.g\n<m.B> -> m.B, m.g\n<m.C> -> <m.A.__enter__>, m.A.__enter__, m.C\n<m.D> -> <m.B.__enter__>, m.B.__enter__, m.D\n\n[case testWithStmtAnnotation]\nfrom typing import Any\nclass A:\n    def __enter__(self) -> Any: pass\n    def __exit__(self, a, b, c) -> None: pass\n\nclass B: pass\n\ndef f(b: B) -> None: pass\n\ndef g() -> None:\n    a: A\n    with a as x: # type: B\n        f(x)\n[out]\n<m.A.__enter__> -> m.g\n<m.A.__exit__> -> m.g\n<m.A> -> m.A, m.g\n<m.B> -> <m.f>, m.B, m.f, m.g\n<m.f> -> m.g\n\n[case testForStmtAnnotation]\nclass A:\n    def __iter__(self): pass\n\nclass B:\n    def f(self) -> None: pass\n\ndef g() -> None:\n    a: A\n    for x in a: # type: B\n        x.f()\n[builtins fixtures/list.pyi]\n[out]\n<m.A.__getitem__> -> m.g\n<m.A.__iter__> -> m.g\n<m.A> -> m.A, m.g\n<m.B.f> -> m.g\n<m.B> -> m.B, m.g\n\n[case testMultipleAssignment]\nfrom typing import Iterator\nclass A:\n    def __iter__(self) -> Iterator[int]: pass\n\ndef f() -> None:\n    a: A\n    x, y = a\n[out]\n<m.A.__iter__> -> <m.A>, m.f\n<m.A> -> m.A, m.f, typing.Iterable\n\n[case testMultipleLvalues]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.y = 1\n\ndef g() -> None:\n    a: A\n    a.x = a.y = 1\n[out]\n<m.A.x> -> m.A.f, m.g\n<m.A.y> -> m.A.f, m.g\n<m.A> -> m.A, m.g\n\n[case testNestedLvalues]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.y = ''\n\ndef g() -> None:\n    a: A\n    a.x, a.y = 1, ''\n[out]\n<m.A.x> -> m.A.f, m.g\n<m.A.y> -> m.A.f, m.g\n<m.A> -> m.A, m.g\n\n[case testForAndSetItem]\nclass A:\n    def __setitem__(self, x: int, y: int) -> None: pass\n\ndef f(): pass\n\ndef g() -> None:\n    a: A\n    for a[0] in f():\n        pass\n[builtins fixtures/list.pyi]\n[out]\n<m.A.__getitem__> -> m.g\n<m.A.__setitem__> -> m.g\n<m.A> -> m.A, m.g\n<m.f> -> m.g\n\n[case testMultipleAssignmentAndFor]\nfrom typing import Iterator, Iterable\n\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.y = 1\n\nclass B:\n    def __iter__(self) -> Iterator[int]: pass\n\ndef f() -> Iterable[B]: pass\n\ndef g() -> None:\n    a: A\n    for a.x, a.y in f():\n        pass\n[builtins fixtures/list.pyi]\n[out]\n<m.A.x> -> m.A.f, m.g\n<m.A.y> -> m.A.f, m.g\n<m.A> -> m.A, m.g\n<m.B.__getitem__> -> m.g\n<m.B.__iter__> -> <m.B>, m.g\n<m.B> -> <m.f>, m.B, m.f, typing.Iterable\n<m.f> -> m.g\n\n[case testNestedSetItem]\nclass A:\n    def __setitem__(self, x: int, y: int) -> None: pass\nclass B:\n    def __setitem__(self, x: int, y: int) -> None: pass\n\ndef f(): pass\n\ndef g() -> None:\n    a: A\n    b: B\n    a[0], b[0] = f()\n[out]\n<m.A.__getitem__> -> m.g\n<m.A.__setitem__> -> m.g\n<m.A> -> m.A, m.g\n<m.B.__getitem__> -> m.g\n<m.B.__setitem__> -> m.g\n<m.B> -> m.B, m.g\n<m.f> -> m.g\n\n[case testOperatorAssignmentStmt]\nclass A:\n    def __add__(self, other: 'B') -> 'A': pass\n\nclass B: pass\n\ndef f() -> B: pass\n\ndef g() -> None:\n    a: A\n    a += f()\n[out]\n<m.A.__add__> -> m.g\n<m.A.__iadd__> -> m.g\n<m.A> -> <m.A.__add__>, m.A, m.A.__add__, m.g\n<m.B> -> <m.A.__add__>, <m.f>, m.A.__add__, m.B, m.f\n<m.f> -> m.g\n\n[case testOperatorAssignmentStmtSetItem]\nclass A:\n    def __add__(self, other: 'B') -> 'A': pass\n\nclass B: pass\n\nclass C:\n    def __getitem__(self, x: int) -> A: pass\n    def __setitem__(self, x: int, y: A) -> None: pass\n\ndef f() -> int: pass\n\ndef g() -> None:\n    b: B\n    c: C\n    c[f()] += b\n[out]\n<m.A.__add__> -> m.g\n<m.A.__iadd__> -> m.g\n<m.A> -> <m.A.__add__>, <m.C.__getitem__>, <m.C.__setitem__>, m.A, m.A.__add__, m.C.__getitem__, m.C.__setitem__\n<m.B> -> <m.A.__add__>, m.A.__add__, m.B, m.g\n<m.C.__getitem__> -> m.g\n<m.C.__setitem__> -> m.g\n<m.C> -> m.C, m.g\n<m.f> -> m.g\n\n[case testYieldStmt]\nfrom typing import Iterator\n\nclass A: pass\n\ndef f1() -> A: pass\n\ndef g() -> Iterator[A]:\n    yield f1()\n[builtins fixtures/list.pyi]\n[out]\n<m.A> -> <m.f1>, <m.g>, m.A, m.f1, m.g\n<m.f1> -> m.g\n\n[case testDelStmt]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n\ndef f() -> A: pass\n\ndef g() -> None:\n    del f().x\n[out]\n<m.A.x> -> m.A.f, m.g\n<m.A> -> <m.f>, m.A, m.f\n<m.f> -> m.g\n\n[case testDelStmtWithIndexing]\nclass A:\n    def __delitem__(self, x: int) -> None: pass\n\ndef f1() -> A: pass\ndef f2() -> int: pass\n\ndef g() -> None:\n    del f1()[f2()]\n[out]\n<m.A.__delitem__> -> m.g\n-- __getitem__ is redundant but harmless\n<m.A.__getitem__> -> m.g\n<m.A> -> <m.f1>, m.A, m.f1\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testYieldFrom]\nfrom typing import Iterator\nclass A:\n    def __iter__(self) -> Iterator[int]: pass\ndef f() -> Iterator[int]:\n    yield from A()\n[out]\n<m.A.__init__> -> m.f\n<m.A.__iter__> -> <m.A>, m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f, typing.Iterable\n\n[case testFunctionDecorator]\nfrom typing import Callable\ndef dec(f: Callable[[int], int]) -> Callable[[str], str]:\n    pass\n\ndef f() -> int: pass\n\n@dec\ndef g(x: int) -> int:\n    return f()\n[out]\n<m.dec> -> m\n<m.f> -> m.g\n<m.g> -> m\n\n[case testMethodDecorator]\nfrom typing import Callable, Any\ndef dec(f: Callable[[Any, int], int]) -> Callable[[Any, str], str]:\n    pass\n\ndef f() -> int: pass\n\nclass A:\n    @dec\n    def g(self, x: int) -> int:\n        return f()\n[out]\n<m.A.g> -> m\n<m.A> -> m.A\n<m.dec> -> m\n<m.f> -> m.A.g\n\n[case testNestedFunction]\nclass A: pass\n\ndef h() -> None: pass\n\ndef f() -> None:\n    def g(x: A) -> None:\n        h()\n[out]\n<m.A> -> <m.f>, m.A, m.f\n<m.h> -> m.f\n\n[case testPlatformCheck]\nimport a\nimport sys\n\ndef f() -> int:\n    if sys.platform == 'nonexistent':\n        return a.g()\n    else:\n        return 1\n[file a.py]\n[builtins fixtures/ops.pyi]\n[out]\n<a> -> m\n<sys.platform> -> m.f\n<sys> -> m, m.f\n\n[case testOverload]\nfrom typing import overload\n\nclass A: pass\nclass B(A): pass\n\n@overload\ndef f(x: B) -> B: ...\n@overload\ndef f(x: A) -> A: ...\n\ndef f(x: A) -> A:\n    g()\n    return x\n\ndef g() -> None: pass\n[builtins fixtures/isinstancelist.pyi]\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A> -> <m.f>, m, m.A, m.B, m.f\n<m.B> -> <m.f>, m.B, m.f\n<m.g> -> m.f\n\n[case testOverloadedMethod]\nfrom typing import overload\n\nclass A: pass\nclass B(A): pass\n\nclass C:\n    @overload\n    def f(self, x: B) -> B: ...\n    @overload\n    def f(self, x: A) -> A: ...\n\n    def f(self, x: A) -> A:\n        self.g()\n        return x\n\n    def g(self) -> None: pass\n[builtins fixtures/isinstancelist.pyi]\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A> -> <m.C.f>, m, m.A, m.B, m.C.f\n<m.B> -> <m.C.f>, m.B, m.C.f\n<m.C.g> -> m.C.f\n<m.C> -> m.C\n\n[case testConditionalFunctionDefinition]\nimport sys\n\nclass A: pass\nclass B: pass\n\nif sys.platform == 'nonexistent':\n    def f(x: A) -> None:\n        g()\nelse:\n    def f(x: B) -> None:\n        h()\n\ndef g() -> None: pass\ndef h() -> None: pass\n[builtins fixtures/ops.pyi]\n[out]\n<m.A> -> m.A\n<m.B> -> <m.f>, m.B, m.f\n<m.h> -> m.f\n<sys.platform> -> m\n<sys> -> m\n\n[case testConditionalMethodDefinition]\nimport sys\n\nclass A: pass\nclass B: pass\n\nclass C:\n    if sys.platform == 'nonexistent':\n        def f(self, x: A) -> None:\n            self.g()\n    else:\n        def f(self, x: B) -> None:\n            self.h()\n\n    def g(self) -> None: pass\n    def h(self) -> None: pass\n[builtins fixtures/ops.pyi]\n[out]\n<m.A> -> m.A\n<m.B> -> <m.C.f>, m.B, m.C.f\n<m.C.h> -> m.C.f\n<m.C> -> m.C\n<sys.platform> -> m\n<sys> -> m\n\n[case testNewType]\nfrom typing import NewType\nfrom m import C\n\nN = NewType('N', C)\n\ndef f(n: N) -> None:\n    pass\n[file m.py]\nclass C:\n    x: int\n[out]\n<m.N> -> <m.f>, m, m.f\n<m.C.(abstract)> -> <m.N.__init__>, m\n<m.C.__init__> -> <m.N.__init__>\n<m.C.__new__> -> <m.N.__new__>\n<m.C.x> -> <m.N.x>\n<m.C> -> m, m.N\n<m> -> m\n"
  },
  {
    "path": "test-data/unit/deps-types.test",
    "content": "-- Test cases for generating fine-grained dependencies between types.\n--\n-- The dependencies are used for fined-grained incremental checking.\n--\n-- See the comment at the top of deps.test for more documentation.\n\n[case testFilterOutBuiltInTypes]\nclass A: pass\n\ndef f(x: int, y: str, z: A) -> None:\n    pass\n[out]\n<m.A> -> <m.f>, m.A, m.f\n\n[case testTupleType]\nfrom typing import Tuple\n\nclass A: pass\nclass B: pass\n\ndef f(x: Tuple[A, B]) -> None:\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\n<m.A> -> <m.f>, m.A, m.f\n<m.B> -> <m.f>, m.B, m.f\n\n[case testUnionType]\nfrom typing import Union\n\nclass A: pass\nclass B: pass\n\ndef f() -> None:\n    x: Union[int, A, B]\n[out]\n<m.A> -> m.A, m.f\n<m.B> -> m.B, m.f\n\n[case testCallableType]\nfrom typing import Callable\n\nclass A: pass\nclass B: pass\n\ndef f() -> None:\n    x: Callable[[int, A], None]\n    y: Callable[[int, str], B]\n[out]\n<m.A> -> m.A, m.f\n<m.B> -> m.B, m.f\n\n[case testTypeType]\nfrom typing import Type\n\nclass A: pass\n\ndef f() -> None:\n    x: Type[A]\n    y: Type[int]\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n\n[case testTypeTypeAttribute]\nfrom typing import Type\n\nclass A:\n    @staticmethod\n    def f() -> None: pass\n\ndef f(x: Type[A]) -> None:\n    x.f()\n[builtins fixtures/staticmethod.pyi]\n[out]\n<m.A.__init__> -> <m.f>, m.f\n<m.A.__new__> -> <m.f>, m.f\n<m.A.f> -> m, m.f\n<m.A> -> <m.f>, m.A, m.f\n\n[case testComplexNestedType]\nfrom typing import Union, Callable, Type\n\nclass A: pass\nclass B: pass\nclass C: pass\n\ndef f() -> None:\n    x: Union[int, Callable[[Type[A]], B], C]\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.B> -> m.B, m.f\n<m.C> -> m.C, m.f\n\n[case testUnionTypeAttributeAccess]\nfrom typing import Union\n\nclass A:\n    def f(self) -> None:\n        self.x = 0\n\nclass B:\n    def f(self) -> None:\n        self.x = ''\n\ndef f(a: Union[A, B]) -> None:\n    a.x\n    a.f()\n[out]\n<m.A.f> -> m.f\n<m.A.x> -> m.A.f, m.f\n<m.A> -> <m.f>, m.A, m.f\n<m.B.f> -> m.f\n<m.B.x> -> m.B.f, m.f\n<m.B> -> <m.f>, m.B, m.f\n\n[case testTupleTypeAttributeAccess]\nfrom typing import Tuple\n\nclass C(Tuple[int, str]):\n    def f(self) -> None: pass\n\ndef f(c: C) -> None:\n    c.f()\n[builtins fixtures/tuple.pyi]\n[out]\n<m.C.f> -> m.f\n<m.C> -> <m.f>, m.C, m.f\n\n[case testOverloaded]\nfrom typing import overload\n\nclass A: pass\nclass B: pass\n\ndef g() -> None: pass\n\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: B) -> B: pass\n\ndef f(x):\n    g()\n\nff = f\n\ndef h() -> None:\n    f(A())\n    ff(A())\n[out]\n<m.A.__init__> -> m.h\n<m.A.__new__> -> m.h\n<m.A> -> <m.f>, <m.ff>, m.A, m.f, m.h\n<m.B> -> <m.f>, <m.ff>, m.B, m.f\n<m.f> -> m, m.h\n<m.ff> -> m, m.h\n<m.g> -> m.f\n\n[case testMetaclassAttributes]\nfrom mod import C\nfrom typing import Type\ndef f(arg: Type[C]) -> None:\n    arg.x\n[file mod.py]\nclass M(type):\n    x: int\nclass C(metaclass=M):\n    pass\n[out]\n<mod.C.__init__> -> <m.f>, m.f\n<mod.C.__new__> -> <m.f>, m.f\n<mod.C.x> -> m.f\n<mod.C> -> <m.f>, m, m.f\n<mod.M.x> -> m.f\n<mod> -> m\n\n[case testMetaclassAttributesDirect]\nfrom mod import C\ndef f() -> None:\n    C.x\n[file mod.py]\nclass M(type):\n    x: int\nclass C(metaclass=M):\n    pass\n[out]\n<mod.C.x> -> m.f\n<mod.C> -> m, m.f\n<mod.M.x> -> m.f\n<mod> -> m\n\n[case testMetaclassOperators]\nfrom mod import C\nfrom typing import Type\ndef f(arg: Type[C]) -> None:\n    arg + arg\n[file mod.py]\nclass M(type):\n    def __add__(self, other: M) -> M:\n        pass\nclass C(metaclass=M):\n    pass\n[out]\n<mod.C.__init__> -> <m.f>, m.f\n<mod.C.__new__> -> <m.f>, m.f\n<mod.C> -> <m.f>, m, m.f\n<mod.M.__add__> -> m.f\n<mod.M.__radd__> -> m.f\n<mod> -> m\n\n[case testMetaclassOperatorsDirect]\nfrom mod import C\ndef f() -> None:\n    C + C\n[file mod.py]\nclass M(type):\n    def __add__(self, other: M) -> M:\n        pass\nclass C(metaclass=M):\n    pass\n[out]\n<mod.C.__init__> -> m.f\n<mod.C.__new__> -> m.f\n<mod.C> -> m, m.f\n<mod.M.__add__> -> m.f\n<mod.M.__radd__> -> m.f\n<mod> -> m\n\n[case testMetaclassDepsDeclared]\nimport mod\nclass C(metaclass=mod.M):\n    pass\n[file mod.py]\nclass M(type):\n    pass\n[out]\n<m.C> -> m.C\n<mod.M> -> <m.C>, m\n<mod> -> m\n\n[case testMetaclassDepsDeclaredNested]\nimport mod\n\ndef func() -> None:\n    class C(metaclass=mod.M):\n        pass\n[file mod.py]\nclass M(type):\n    pass\n[out]\n<m.func> -> m.func\n<mod.M> -> <m.func>, m.func\n<mod> -> m, m.func\n\n-- Type aliases\n\n[case testAliasDepsNormalMod]\nfrom mod import I\nA = I\nx: A\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m\n<m.x> -> m\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.x>, m\n<mod> -> m\n\n[case testAliasDepsNormalModExtended]\n# __dump_all__\nimport a\nx: a.A\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<m.x> -> m\n<a.A> -> m\n<a> -> m\n<mod.I.__init__> -> a\n<mod.I.__new__> -> a\n<mod.I> -> <m.x>, m, a, mod.I\n<mod> -> a\n\n[case testAliasDepsNormalFunc]\nfrom mod import I\nA = I\ndef f(x: A) -> None:\n    pass\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m.f\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.f>, m, m.f\n<mod> -> m\n\n[case testAliasDepsNormalFuncExtended]\n# __dump_all__\nimport a\ndef f(x: a.A) -> None:\n    pass\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<a.A> -> m.f\n<a> -> m\n<mod.I.__init__> -> a\n<mod.I.__new__> -> a\n<mod.I> -> <m.f>, m.f, a, mod.I\n<mod> -> a\n\n[case testAliasDepsNormalClass]\nfrom a import A\nclass C:\n    x: A\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<m.C> -> m.C\n<a.A> -> m\n<a> -> m\n<mod.I> -> <m.C.x>, m\n\n[case testAliasDepsNormalClassBases]\nfrom a import A\nclass C(A):\n    pass\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<m.C> -> m.C\n<a.A> -> m\n<a> -> m\n<mod.I.(abstract)> -> <m.C.__init__>, m\n<mod.I.__init__> -> <m.C.__init__>\n<mod.I.__new__> -> <m.C.__new__>\n<mod.I> -> m.C\n\n[case testAliasDepsGenericMod]\nfrom mod import I, S, D\nA = D[I, S]\nx: A\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> m\n<m.x> -> m\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.x>, m\n<mod.I> -> <m.x>, m\n<mod.S> -> <m.x>, m\n<mod> -> m\n\n[case testAliasDepsGenericFunc]\nfrom mod import I, S, D\nA = D[S, I]\ndef f(x: A) -> None:\n    pass\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> <m.f>, m.f\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.f>, m, m.f\n<mod.I> -> <m.f>, m, m.f\n<mod.S> -> <m.f>, m, m.f\n<mod> -> m\n\n[case testAliasDepsGenericFuncExtended]\nimport a\ndef f(x: a.A) -> None:\n    pass\n[file a.py]\nfrom mod import I, S, D\nA = D[S, I]\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<a.A> -> <m.f>, m.f\n<a> -> m\n<mod.D> -> <m.f>, m.f\n<mod.I> -> <m.f>, m.f\n<mod.S> -> <m.f>, m.f\n\n[case testAliasDepsGenericClass]\nfrom mod import I, D, S, T\nA = D[S, T]\nclass C:\n    x: A[I]\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> m\n<m.C> -> m.C\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.C.x>, m\n<mod.I> -> <m.C.x>, m\n<mod.S> -> <m.C.x>, m\n<mod.T> -> m\n<mod> -> m\n\n[case testAliasDepsForwardMod]\nfrom mod import I\nx: A\nA = I\n[file mod.py]\nfrom typing import TypeVar, Generic\nclass I: pass\n[out]\n<m.A> -> m\n<m.x> -> m\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.x>, m\n<mod> -> m\n\n[case testAliasDepsForwardFunc]\nfrom mod import I\ndef f(x: A) -> None:\n    pass\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m.f\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.f>, m, m.f\n<mod> -> m\n\n[case testAliasDepsForwardClass]\nfrom mod import I\nclass C:\n    x: A\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m\n<m.C> -> m.C\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.C.x>, m\n<mod> -> m\n\n[case testAliasDepsChainedMod]\nfrom mod import I\nA = I\nB = A\nx: B\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m\n<m.B> -> m\n<m.x> -> m\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.x>, m\n<mod> -> m\n\n[case testAliasDepsChainedFunc]\nfrom mod import I\nA = I\nB = A\ndef f(x: B) -> None:\n    pass\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m\n<m.B> -> m.f\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.f>, m, m.f\n<mod> -> m\n\n[case testAliasDepsChainedFuncExtended]\nimport a\nB = a.A\ndef f(x: B) -> None:\n    pass\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[out]\n<m.B> -> m.f\n<a.A> -> m\n<a> -> m\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.f>, m, m.f\n\n[case testAliasDepsChainedClass]\nfrom mod import I\nA = I\nB = A\nclass C(B):\n    pass\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m\n<m.B> -> m\n<m.C> -> m.C\n<mod.I.(abstract)> -> <m.C.__init__>, m\n<mod.I.__init__> -> <m.C.__init__>, m\n<mod.I.__new__> -> <m.C.__new__>, m\n<mod.I> -> m, m.C\n<mod> -> m\n\n[case testAliasDepsNestedMod]\nfrom mod import I, S, D\nA = D[S, I]\nB = D[S, A]\nx: B\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> <m.x>, m\n<m.B> -> m\n<m.x> -> m\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.x>, m\n<mod.I> -> <m.x>, m\n<mod.S> -> <m.x>, m\n<mod> -> m\n\n[case testAliasDepsNestedModExtended]\n# __dump_all__\nfrom mod import S, D\nimport a\nB = D[S, a.A]\nx: B\n[file a.py]\nfrom mod import I, S, D\nA = D[S, I]\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.B> -> m\n<m.x> -> m\n<a.A> -> <m.x>, m\n<a> -> m\n<mod.D.__init__> -> m, a\n<mod.D.__new__> -> m, a\n<mod.D> -> <m.x>, m, a, mod.D\n<mod.I> -> <m.x>, m, a, mod.I\n<mod.S> -> <m.x>, m, a, mod.S\n<mod.T> -> mod.D\n<mod.U> -> mod.D\n<mod> -> m, a\n\n[case testAliasDepsNestedFunc]\nfrom mod import I, S, D\nA = D[S, I]\nB = D[S, A]\ndef f(x: B) -> None:\n    pass\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> <m.f>, m, m.f\n<m.B> -> <m.f>, m.f\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.f>, m, m.f\n<mod.I> -> <m.f>, m, m.f\n<mod.S> -> <m.f>, m, m.f\n<mod> -> m\n\n[case testAliasDepsNestedFuncExtended]\n# __dump_all__\nfrom mod import S, D\nimport a\nB = D[S, a.A]\ndef f(x: B) -> None:\n    pass\n[file a.py]\nfrom mod import I, S, D\nA = D[S, I]\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.B> -> <m.f>, m.f\n<a.A> -> <m.f>, m, m.f\n<a> -> m\n<mod.D.__init__> -> m, a\n<mod.D.__new__> -> m, a\n<mod.D> -> <m.f>, m, m.f, a, mod.D\n<mod.I> -> <m.f>, m, m.f, a, mod.I\n<mod.S> -> <m.f>, m, m.f, a, mod.S\n<mod.T> -> mod.D\n<mod.U> -> mod.D\n<mod> -> m, a\n\n[case testAliasDepsNestedFuncDirect]\nfrom mod import I, S, D\nA = D[S, I]\nE = D\ndef f(x: E[S, A]) -> None:\n    pass\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> <m.f>, m.f\n<m.E> -> m.f\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.f>, m, m.f\n<mod.I> -> <m.f>, m, m.f\n<mod.S> -> <m.f>, m, m.f\n<mod.T> -> m\n<mod.U> -> m\n<mod> -> m\n\n[case testAliasDepsNestedClass]\nfrom mod import I, S, D\nA = D[S, I]\nB = D[S, A]\nclass C:\n    x: B\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> <m.C.x>, m\n<m.B> -> m\n<m.C> -> m.C\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.C.x>, m\n<mod.I> -> <m.C.x>, m\n<mod.S> -> <m.C.x>, m\n<mod> -> m\n\n[case testAliasDepsCast]\nfrom typing import cast\nfrom mod import I\nA = I\ndef fun() -> None:\n    x = cast(A, 42)\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> m.fun\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> m, m.fun\n<mod> -> m\n\n[case testAliasDepsRuntime]\nfrom mod import I, S, D\nA = I\nx = D[S, A]()\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.A> -> m\n<m.x> -> m\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.x>, m\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.x>, m\n<mod.S> -> <m.x>, m\n<mod> -> m\n\n[case testAliasDepsRuntimeExtended]\n# __dump_all__\nfrom mod import I, S, D\nimport a\nx = D[S, a.A]()\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nclass D(Generic[T, U]): pass\nclass I: pass\nclass S: pass\n[out]\n<m.x> -> m\n<a.A> -> m\n<a> -> m\n<mod.D.__init__> -> m\n<mod.D.__new__> -> m\n<mod.D> -> <m.x>, m, mod.D\n<mod.I.__init__> -> a\n<mod.I.__new__> -> a\n<mod.I> -> <m.x>, m, a, mod.I\n<mod.S> -> <m.x>, m, mod.S\n<mod.T> -> mod.D\n<mod.U> -> mod.D\n<mod> -> m, a\n\n[case testAliasDepsNamedTuple]\nfrom typing import NamedTuple\nfrom mod import I\nA = I\nclass P(NamedTuple):\n    x: A\n[file mod.py]\nclass I: pass\n[builtins fixtures/tuple.pyi]\n[out]\n<m.A> -> m\n<m.P> -> m.P\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.P.x>, <m.P>, m, m.P\n<mod> -> m\n\n[case testAliasDepsNamedTupleFunctional]\n# __dump_all__\nfrom typing import NamedTuple\nimport a\nP = NamedTuple('P', [('x', a.A)])\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[builtins fixtures/tuple.pyi]\n[out]\n<a.A> -> m\n<a> -> m\n<mod.I.__init__> -> a\n<mod.I.__new__> -> a\n<mod.I> -> <m.P.x>, <m.P>, m, a, mod.I\n<mod> -> a\n\n[case testAliasDepsTypedDict]\nfrom mypy_extensions import TypedDict\nfrom mod import I\nA = I\nclass P(TypedDict):\n    x: A\n[file mod.py]\nclass I: pass\n[builtins fixtures/dict.pyi]\n[out]\n<m.A> -> m\n<m.P> -> m.P\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.P>, m\n<mod> -> m\n\n[case testAliasDepsTypedDictFunctional]\n# __dump_all__\nfrom mypy_extensions import TypedDict\nimport a\nP = TypedDict('P', {'x': a.A})\n[file a.py]\nfrom mod import I\nA = I\n[file mod.py]\nclass I: pass\n[builtins fixtures/dict.pyi]\n[out]\n<a.A> -> m\n<a> -> m\n<mod.I.__init__> -> a\n<mod.I.__new__> -> a\n<mod.I> -> <m.P>, a, mod.I\n<mod> -> a\n\n[case testAliasDepsClassInFunction]\nfrom mod import I\nA = I\ndef f() -> None:\n    class C:\n        x: A\n[file mod.py]\nclass I: pass\n[out]\n<m.A> -> m.f\n<m.f> -> m.f\n<mod.I.__init__> -> m\n<mod.I.__new__> -> m\n<mod.I> -> <m.f.x>, m, m.f\n<mod> -> m\n\n[case testAliasDepsFromImportUnqualified]\nfrom a import C\nx: C\ndef f() -> None:\n    C()\nclass A:\n    def meth(self) -> None:\n        def inner() -> C:\n            pass\n[file a.py]\nfrom b import D\nC = D\n[file b.py]\nclass D:\n    pass\n[out]\n<m.A> -> m.A\n<m.x> -> m\n<a.C> -> m, m.A.meth, m.f\n<a> -> m\n<b.D.__init__> -> m.f\n<b.D.__new__> -> m.f\n<b.D> -> <m.A.meth>, <m.x>, m, m.A.meth\n\n[case testFuncBasedEnum]\nfrom enum import Enum\nfrom mod import B\n\nA = Enum('A', [('X', B())])\n\ndef f(a: A) -> None:\n    pass\ndef g() -> None:\n    A.X\n[file mod.py]\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\n<m.A.X> -> m.g\n<m.A> -> <m.f>, m.f, m.g\n<mod.B> -> m\n<mod> -> m\n\n[case testProtocolDepsWildcard]\n# __dump_all__\nimport mod\nx: mod.P\n[file mod.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[out]\n<m.x> -> m\n<mod.P> -> <m.x>, m, mod.P\n<mod.P[wildcard]> -> <mod.P>\n<mod> -> m\n\n[case testProtocolDepsWildcardSupertype]\n# __dump_all__\nimport mod\nx: mod.P\n[file mod.py]\nfrom typing import Protocol\nclass PBase(Protocol):\n    x: int\nclass P(PBase, Protocol):\n    y: int\n[out]\n<m.x> -> m\n<mod.P.y> -> mod\n<mod.P> -> <m.x>, m, mod.P\n<mod.PBase.(abstract)> -> <mod.P.__init__>, mod\n<mod.PBase.__init__> -> <mod.P.__init__>\n<mod.PBase.__new__> -> <mod.P.__new__>\n<mod.PBase.x> -> <mod.P.x>\n<mod.PBase.y> -> <mod.P.y>\n<mod.PBase> -> mod, mod.P, mod.PBase\n<mod.PBase[wildcard]> -> <mod.P>, <mod.PBase>\n<mod.P[wildcard]> -> <mod.P>\n<mod> -> m\n\n[case testProtocolDepsPositive]\n# __dump_all__\nimport mod\nclass C:\n    x: int\nx: mod.P = C()\n[file mod.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[out]\n<m.C.__init__> -> m\n<m.C.__new__> -> m\n<m.C.x> -> <m.C>\n<m.C> -> m, m.C, mod.P\n<m.x> -> m\n<mod.P> -> <m.x>, m, mod.P\n<mod.P[wildcard]> -> <mod.P>\n<mod> -> m\n\n[case testProtocolDepsNegative]\n# __dump_all__\nimport mod\nfrom typing import overload\nclass C:\n    y: int\n@overload\ndef func(x: C) -> int: ...\n@overload\ndef func(x: mod.P) -> str: ...\ndef func(x):\n    pass\n\nfunc(C())\n[file mod.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[out]\n<m.C.__init__> -> m\n<m.C.__new__> -> m\n<m.C.x> -> <m.C>\n<m.C> -> <m.func>, m, m.C, m.func, mod.P\n<m.func> -> m\n<mod.P> -> <m.func>, m.func, mod.P\n<mod.P[wildcard]> -> <mod.P>\n<mod> -> m\n\n[case testProtocolDepsConcreteSuperclass]\n# __dump_all__\nimport mod\nclass B:\n    x: int\nclass C(B):\n    pass\nx: mod.P = C()\n[file mod.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[out]\n<m.B.(abstract)> -> <m.C.__init__>, m\n<m.B.__init__> -> <m.C.__init__>\n<m.B.__new__> -> <m.C.__new__>\n<m.B.x> -> <m.C.x>, <m.C>\n<m.B> -> m, m.B, m.C\n<m.C.__init__> -> m\n<m.C.__new__> -> m\n<m.C.x> -> <m.C>\n<m.C> -> m, m.C, mod.P\n<m.x> -> m\n<mod.P> -> <m.x>, m, mod.P\n<mod.P[wildcard]> -> <mod.P>\n<mod> -> m\n"
  },
  {
    "path": "test-data/unit/deps.test",
    "content": "-- Test cases for generating dependencies between ASTs nodes.\n--\n-- The dependencies are used for fined-grained incremental checking and\n-- the daemon mode.\n--\n-- The output of each test case includes the dependency map for whitelisted\n-- modules (includes the main module and the modules 'pkg' and 'pkg.mod' at\n-- least).\n--\n-- Dependencies are formatted as \"<trigger> -> affected locations\".\n--\n-- Look at the docstring of mypy.server.deps for an explanation of\n-- how fine-grained dependencies are represented.\n\n[case testCallFunction]\ndef f() -> None:\n    g()\ndef g() -> None:\n    pass\n[out]\n<m.g> -> m.f\n\n[case testCallMethod]\ndef f(a: A) -> None:\n    a.g()\nclass A:\n    def g(self) -> None: pass\n[out]\n<m.A.g> -> m.f\n<m.A> -> <m.f>, m.A, m.f\n\n[case testAccessAttribute]\ndef f(a: A) -> None:\n    a.x\nclass A:\n    def g(self) -> None:\n        self.x = 1\n[out]\n<m.A.x> -> m.A.g, m.f\n<m.A> -> <m.f>, m.A, m.f\n\n[case testConstructInstance]\ndef f() -> None:\n    A()\nclass A: pass\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n\n[case testAccessModuleAttribute]\nclass A: pass\nx = A()\ndef f() -> None:\n    x\n[out]\n<m.A.__init__> -> m\n<m.A.__new__> -> m\n<m.A> -> <m.x>, m, m.A\n<m.x> -> m, m.f\n\n[case testAccessModuleAttribute2]\nimport n\ndef f() -> None:\n    n.x\n[file n.py]\nx = 1\n[out]\n<n.x> -> m.f\n<n> -> m, m.f\n\n[case testImport]\nimport n\n[file n.py]\nx = 1\n[out]\n<n> -> m\n\n[case testCallImportedFunction]\nimport n\nn.f()\n[file n.py]\ndef f() -> None: pass\n[out]\n<n.f> -> m\n<n> -> m\n\n[case testImportModuleAs]\nimport n as x\nx.f()\n[file n.py]\ndef f() -> None: pass\n[out]\n<n.f> -> m\n<n> -> m\n\n[case testCallImportedFunctionInFunction]\nimport n\ndef g() -> None:\n    n.f()\n[file n.py]\ndef f() -> None: pass\n[out]\n<n.f> -> m.g\n<n> -> m, m.g\n\n[case testInheritanceSimple]\nclass A:\n    pass\nclass B(A):\n    pass\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A> -> m, m.A, m.B\n<m.B> -> m.B\n\n[case testInheritanceWithMethodAndAttribute]\nclass A:\n    pass\nclass B(A):\n    def f(self) -> None:\n        self.x = 1\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A.f> -> m.B.f\n<m.A.x> -> <m.B.x>\n<m.A> -> m, m.A, m.B\n<m.B.x> -> m.B.f\n<m.B> -> m.B\n\n[case testInheritanceWithMethodAndAttributeAndDeepHierarchy]\nclass A:\n    pass\nclass B(A):\n    pass\nclass C(B):\n    def f(self) -> None:\n        self.x = 1\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, <m.C.__init__>, m\n<m.A.__init__> -> <m.B.__init__>, <m.C.__init__>\n<m.A.__new__> -> <m.B.__new__>, <m.C.__new__>\n<m.A.f> -> m.C.f\n<m.A.x> -> <m.C.x>\n<m.A> -> m, m.A, m.B\n<m.B.(abstract)> -> <m.C.__init__>, m\n<m.B.__init__> -> <m.C.__init__>\n<m.B.__new__> -> <m.C.__new__>\n<m.B.f> -> m.C.f\n<m.B.x> -> <m.C.x>\n<m.B> -> m, m.B, m.C\n<m.C.x> -> m.C.f\n<m.C> -> m.C\n\n[case testInheritAttribute]\nimport n\nclass B(n.A):\n    def f(self) -> None:\n        a = 1\n        a = self.x\n[file n.py]\nclass A:\n    def g(self) -> None:\n        self.x = 1\n[out]\n<m.B.x> -> m.B.f\n<m.B> -> m.B\n<n.A.(abstract)> -> <m.B.__init__>, m\n<n.A.__init__> -> <m.B.__init__>\n<n.A.__new__> -> <m.B.__new__>\n<n.A.f> -> m.B.f\n<n.A.g> -> <m.B.g>\n<n.A.x> -> <m.B.x>\n<n.A> -> m, m.B\n<n> -> m\n\n[case testInheritMethod]\nclass A:\n    def g(self) -> None: pass\nclass B(A):\n    def f(self) -> None:\n        self.g()\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__init__> -> <m.B.__init__>\n<m.A.__new__> -> <m.B.__new__>\n<m.A.f> -> m.B.f\n<m.A.g> -> <m.B.g>\n<m.A> -> m, m.A, m.B\n<m.B.g> -> m.B.f\n<m.B> -> m.B\n\n[case testPackage]\nimport a.b\ndef f() -> None:\n    a.b.g()\n[file a/__init__.py]\n[file a/b.py]\ndef g() -> None: pass\n[out]\n<a.b.g> -> m.f\n<a.b> -> m, m.f\n<a> -> m.f\n\n[case testClassInPackage]\nimport a.b\ndef f(x: a.b.A) -> None:\n    x.g()\n    x.y\n[file a/__init__.py]\n[file a/b.py]\nclass A:\n    def g(self) -> None:\n        self.y = 1\n[out]\n<a.b.A.g> -> m.f\n<a.b.A.y> -> m.f\n<a.b.A> -> <m.f>, m.f\n<a.b> -> m\n\n[case testPackage__init__]\nimport a\ndef f() -> None:\n    a.g()\n[file a/__init__.py]\ndef g() -> None: pass\n[out]\n<a.g> -> m.f\n<a> -> m, m.f\n\n[case testClassInPackage__init__]\nimport a\ndef f(x: a.A) -> None:\n    x.g()\n    x.y\n[file a/__init__.py]\nclass A:\n    def g(self) -> None:\n        self.y = 1\n[out]\n<a.A.g> -> m.f\n<a.A.y> -> m.f\n<a.A> -> <m.f>, m.f\n<a> -> m\n\n[case testConstructor]\nclass A:\n    def __init__(self, x: C) -> None: pass\nclass C: pass\ndef f() -> None:\n    A(C())\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.C.__init__> -> m.f\n<m.C.__new__> -> m.f\n<m.C> -> <m.A.__init__>, m.A.__init__, m.C, m.f\n\n[case testNonTrivialConstructor]\nclass C:\n    def __init__(self) -> None:\n        self.x = 1\n[out]\n<m.C.x> -> m.C.__init__\n<m.C> -> m.C\n\n[case testImportFrom]\nfrom n import f\n\ndef g() -> None:\n    f()\n[file n.py]\ndef f() -> None: pass\n[out]\n<n.f> -> m, m.g\n<n> -> m\n\n[case testImportFromAs]\nfrom n import f as ff\n\ndef g() -> None:\n    ff()\n[file n.py]\ndef f() -> None: pass\n[out]\n<n.f> -> m, m.g\n<n> -> m\n\n[case testNestedClass]\ndef f() -> None:\n    b = A.B()\n    b.f()\nclass A:\n    class B:\n        def f(self) -> None: pass\n[out]\n<m.A.B.__init__> -> m.f\n<m.A.B.__new__> -> m.f\n<m.A.B.f> -> m.f\n<m.A.B> -> m.A.B, m.f\n<m.A> -> m.A, m.f\n\n[case testNestedClassAttribute]\ndef f() -> None:\n    b = A.B()\n    b.x\nclass A:\n    class B:\n        def f(self) -> None:\n            self.x = 1\n[out]\n<m.A.B.__init__> -> m.f\n<m.A.B.__new__> -> m.f\n<m.A.B.x> -> m.A.B.f, m.f\n<m.A.B> -> m.A.B, m.f\n<m.A> -> m.A, m.f\n\n[case testNestedClassInAnnotation]\ndef f(x: A.B) -> None:\n    pass\nclass A:\n    class B: pass\n[out]\n<m.A.B> -> <m.f>, m.A.B, m.f\n<m.A> -> m.A\n\n[case testNestedClassInAnnotation2]\ndef f(x: A.B) -> None:\n    x.f()\nclass A:\n    class B:\n        def f(self) -> None: pass\n[out]\n<m.A.B.f> -> m.f\n<m.A.B> -> <m.f>, m.A.B, m.f\n<m.A> -> m.A\n\n[case NestedFunctionType]\nfrom mod import A, B, C, D\ndef outer() -> None:\n    def inner(x: A, *args: B, **kwds: C) -> D:\n        pass\n[file mod.py]\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\n[builtins fixtures/dict.pyi]\n[out]\n<mod.A> -> <m.outer>, m, m.outer\n<mod.B> -> <m.outer>, m, m.outer\n<mod.C> -> <m.outer>, m, m.outer\n<mod.D> -> <m.outer>, m, m.outer\n<mod> -> m\n\n[case NestedFunctionBody]\nfrom mod import A, B, C\ndef outer() -> None:\n    def inner() -> None:\n        A()\n        x: B\n        y: C\n        y.x\n[file mod.py]\nclass A: pass\nclass B: pass\nclass C:\n    x: int\n[builtins fixtures/dict.pyi]\n[out]\n<mod.A.__init__> -> m.outer\n<mod.A.__new__> -> m.outer\n<mod.A> -> m, m.outer\n<mod.B> -> m, m.outer\n<mod.C.x> -> m.outer\n<mod.C> -> m, m.outer\n<mod> -> m\n\n[case testDefaultArgValue]\ndef f1(x: int) -> int: pass\ndef f2() -> int: pass\ndef g(x: int = f1(f2())) -> None: pass\n[out]\n<m.f1> -> m.g\n<m.f2> -> m.g\n\n[case testIsInstance]\nclass A:\n    def g(self) -> None: pass\n\ndef f(x: object) -> None:\n    if isinstance(x, A):\n        x.g()\ndef ff(x: object) -> None:\n    if isinstance(x, A):\n        pass\n[builtins fixtures/isinstancelist.pyi]\n[out]\n-- The dependencies on the ctor are basically spurious but not a problem\n<m.A.g> -> m.f\n<m.A> -> m.A, m.f, m.ff\n\n[case testUnreachableIsInstance]\nclass A:\n    x: int\n\nclass B:\n    x: str\n\ndef f(x: A) -> None:\n    if isinstance(x, B):\n        x.y\n[builtins fixtures/isinstancelist.pyi]\n[out]\n<m.A> -> <m.f>, m.A, m.f\n<m.B> -> m.B, m.f\n\n[case testIsInstanceAdHocIntersectionDeps]\nclass A:\n    x: int\n\nclass B:\n    y: int\n\ndef f(x: A) -> None:\n    if isinstance(x, B):\n        x.y\n[builtins fixtures/isinstancelist.pyi]\n[out]\n<m.A.__await__> -> <m.A>\n<m.A> -> <m.f>, m.A, m.f, typing.Awaitable\n<m.B> -> m.B, m.f\n\n[case testAttributeWithClassType1]\nfrom n import A\n\nclass B:\n    def h(self, z: A) -> None:\n        self.z = z\n[file n.py]\nclass A: pass\n[out]\n<m.B.z> -> m.B.h\n<m.B> -> m.B\n<n.A> -> <m.B.h>, <m.B.z>, m, m.B.h\n<n> -> m\n\n[case testAttributeWithClassType2]\nfrom m import A\n\nclass B:\n    def f(self) -> None:\n        self.x = A()\n[file m.py]\nclass A: pass\n[out]\n<m.B.x> -> m.B.f\n<m.B> -> m.B\n<m.A.__init__> -> m.B.f\n<m.A.__new__> -> m.B.f\n<m.A> -> <m.B.x>, m, m.B.f\n<m> -> m\n\n[case testAttributeWithClassType3]\nfrom n import A, x\n\nclass B:\n    def g(self) -> None:\n        self.x = x\n[file n.py]\nclass A: pass\n\nx = A()\n[out]\n<m.B.x> -> m.B.g\n<m.B> -> m.B\n<n.A> -> <m.B.x>, m\n<n.x> -> m, m.B.g\n<n> -> m\n\n[case testAttributeWithClassType4]\nfrom n import A\n\nclass B:\n    def g(self) -> None:\n        self.x: A\n[file n.py]\nclass A: pass\n[out]\n<m.B.x> -> m.B.g\n<m.B> -> m.B\n<n.A> -> <m.B.x>, m, m.B.g\n<n> -> m\n\n[case testClassBody]\ndef f() -> int: pass\ndef g() -> int: pass\ndef h() -> int: pass\n\nclass A:\n    h()\n    if f():\n        g()\n[out]\n<m.A> -> m.A\n<m.f> -> m\n<m.g> -> m\n<m.h> -> m\n\n[case testVariableInitializedInClass]\nfrom n import A\n\nclass B:\n    x = None  # type: A\n[file n.py]\nclass A: pass\n[out]\n<m.B> -> m.B\n<n.A> -> <m.B.x>, m\n<n> -> m\n\n[case testVariableAnnotationInClass]\nfrom n import A\n\nclass B:\n    x: A\n\n    def f(self) -> None:\n        y = self.x\n[file n.py]\nclass A: pass\n[out]\n<m.B.x> -> m.B.f\n<m.B> -> m.B\n<n.A> -> <m.B.x>, m\n<n> -> m\n\n[case testGlobalVariableInitialized]\nfrom n import A\n\nx = A()\n[file n.py]\nclass A: pass\n[out]\n<m.x> -> m\n<n.A.__init__> -> m\n<n.A.__new__> -> m\n<n.A> -> <m.x>, m\n<n> -> m\n\n[case testGlobalVariableAnnotation]\nfrom n import A\n\nx: A\n[file n.py]\nclass A: pass\n[out]\n<m.x> -> m\n<n.A> -> <m.x>, m\n<n> -> m\n\n[case testProperty]\nclass B: pass\n\nclass A:\n    @property\n    def x(self) -> B: pass\n\ndef f(a: A) -> None:\n    b = a.x\n[builtins fixtures/property.pyi]\n[out]\n<m.A.x> -> m, m.f\n<m.A> -> <m.f>, m.A, m.f\n<m.B> -> <m.A.x>, m.A.x, m.B\n\n[case testUnreachableAssignment]\nfrom typing import List, Tuple\n\ndef f() -> None: pass\n\nclass C:\n    def __init__(self, x: int) -> None:\n        if isinstance(x, int):\n            self.y = 1\n        else:\n            self.y = f()\n[builtins fixtures/isinstancelist.pyi]\n[out]\n<m.C.y> -> m.C.__init__\n<m.C> -> m.C\n<m.f> -> m.C.__init__\n\n[case testPartialNoneTypeAttributeCrash1]\n# flags: --no-local-partial-types\nclass C: pass\n\nclass A:\n    x = None\n\n    def f(self) -> None:\n        self.x = C()\n[out]\n<m.A.x> -> m.A.f\n<m.A> -> m.A\n<m.C.__init__> -> m.A.f\n<m.C.__new__> -> m.A.f\n<m.C> -> <m.A.x>, m.A.f, m.C\n\n[case testPartialNoneTypeAttributeCrash2]\n# flags: --no-local-partial-types\nclass C: pass\n\nclass A:\n    x = None\n\n    def f(self) -> None:\n        self.x = C()\n[out]\n<m.A.x> -> m.A.f\n<m.A> -> m.A\n<m.C.__init__> -> m.A.f\n<m.C.__new__> -> m.A.f\n<m.C> -> <m.A.x>, m.A.f, m.C\n\n[case testRelativeImport]\nimport pkg  # Magic package name in test runner\n[file pkg/__init__.py]\nfrom . import mod\nfrom .a import x\n[file pkg/mod.py]\nfrom . import a\n[file pkg/a.py]\nx = 1\n[out]\n<pkg.a.x> -> pkg\n<pkg.a> -> pkg, pkg.mod\n<pkg.mod> -> pkg\n<pkg> -> m, pkg, pkg.mod\n\n[case testTypedDict]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\ndef foo(x: Point) -> int:\n    return x['x'] + x['y']\n[builtins fixtures/dict.pyi]\n[out]\n<m.Point.__init__> -> m\n<m.Point.__new__> -> m\n<m.Point> -> <m.foo>, <m.p>, m, m.foo\n<m.p> -> m\n\n[case testTypedDict2]\nfrom mypy_extensions import TypedDict\nclass A: pass\nPoint = TypedDict('Point', {'x': int, 'y': A})\np = Point(dict(x=42, y=A()))\ndef foo(x: Point) -> int:\n    return x['x']\n[builtins fixtures/dict.pyi]\n[out]\n<m.A.__init__> -> m\n<m.A.__new__> -> m\n<m.A> -> <m.Point>, <m.foo>, <m.p>, m, m.A, m.foo\n<m.Point.__init__> -> m\n<m.Point.__new__> -> m\n<m.Point> -> <m.foo>, <m.p>, m, m.foo\n<m.p> -> m\n\n[case testTypedDict3]\nfrom mypy_extensions import TypedDict\nclass A: pass\nclass Point(TypedDict):\n    x: int\n    y: A\np = Point(dict(x=42, y=A()))\ndef foo(x: Point) -> int:\n    return x['x']\n[builtins fixtures/dict.pyi]\n[out]\n<m.A.__init__> -> m\n<m.A.__new__> -> m\n<m.A> -> <m.Point>, <m.foo>, <m.p>, m, m.A, m.foo\n<m.Point.__init__> -> m\n<m.Point.__new__> -> m\n<m.Point> -> <m.foo>, <m.p>, m, m.Point, m.foo\n<m.p> -> m\n\n[case testImportStar]\nfrom a import *\n[file a.py]\nx = 0\n[out]\n<a[wildcard]> -> m\n\n[case testDecoratorDepsMod]\nimport mod\n\n@mod.deca\n@mod.decb(mod.C())\ndef func(x: int) -> int:\n    pass\n[file mod.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[int], int]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\n[out]\n<m.func> -> m\n<mod.C.__init__> -> m\n<mod.C.__new__> -> m\n<mod.C> -> m\n<mod.deca> -> m\n<mod.decb> -> m\n<mod> -> m\n\n[case testDecoratorDepsFunc]\nimport mod\n\ndef outer() -> None:\n    @mod.deca\n    @mod.decb(mod.C())\n    def func(x: int) -> int:\n        pass\n[file mod.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[int], int]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\n[out]\n<mod.C.__init__> -> m.outer\n<mod.C.__new__> -> m.outer\n<mod.C> -> m.outer\n<mod.deca> -> m.outer\n<mod.decb> -> m.outer\n<mod> -> m, m.outer\n\n[case testDecoratorDepsDeepNested]\nimport mod\n\ndef outer() -> None:\n    def inner() -> None:\n        @mod.dec\n        def func(x: int) -> int:\n            pass\n[file mod.py]\nfrom typing import Callable\ndef dec(func: Callable[[int], int]) -> Callable[[str], str]:\n    pass\n[out]\n<mod.dec> -> m.outer\n<mod> -> m, m.outer\n\n[case testDecoratorDepsNestedClass]\nimport mod\n\nclass Outer:\n    class Inner:\n        c = mod.C()\n        @c.dec\n        def func(self, x: int) -> int:\n            pass\n[file mod.py]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., int]) -> Callable[..., str]:\n        pass\n[out]\n<m.Outer.Inner.func> -> m\n<m.Outer.Inner> -> m.Outer.Inner\n<m.Outer> -> m.Outer\n<mod.C.__init__> -> m\n<mod.C.__new__> -> m\n<mod.C.dec> -> m\n<mod.C> -> <m.Outer.Inner.c>, m\n<mod> -> m\n\n[case testDecoratorDepsClassInFunction]\nimport mod\n\ndef outer() -> None:\n    class Inner:\n        c = mod.C()\n        @c.dec\n        def func(self, x: int) -> int:\n            pass\n[file mod.py]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., int]) -> Callable[..., str]:\n        pass\n[out]\n<m.outer> -> m.outer\n<mod.C.__init__> -> m.outer\n<mod.C.__new__> -> m.outer\n<mod.C.dec> -> m.outer\n<mod.C> -> <m.outer.c>, m.outer\n<mod> -> m, m.outer\n\n[case DecoratorDepsMethod]\nimport mod\n\nclass D:\n    @mod.deca\n    @mod.decb(mod.C())\n    def func(self, x: int) -> int:\n        pass\n[file mod.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[..., int]) -> Callable[..., str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\n[out]\n<m.D.func> -> m\n<m.D> -> m.D\n<mod.C.__init__> -> m\n<mod.C.__new__> -> m\n<mod.C> -> m\n<mod.deca> -> m\n<mod.decb> -> m\n<mod> -> m\n\n[case testMissingModuleClass1]\nfrom b import A  # type: ignore\ndef f(x: A) -> None:\n    x.foo()\n[out]\n<m.A> -> <m.f>, m.f\n<b.A> -> m\n<b> -> m\n\n[case testMissingModuleClass2]\nfrom p.b import A  # type: ignore\ndef f(x: A) -> None:\n    x.foo()\n[out]\n<m.A> -> <m.f>, m.f\n<p.b.A> -> m\n<p.b> -> m\n\n[case testIgnoredMissingModuleAttribute]\nimport a\na.x  # type: ignore\n\nimport b.c\nb.c.x  # type: ignore\n\nfrom b import c\nc.y  # type: ignore\n[file a.py]\n[file b/__init__.py]\n[file b/c.py]\n[builtins fixtures/module.pyi]\n[out]\n<a.x> -> m\n<a> -> m\n<b.c.x> -> m\n<b.c.y> -> m\n<b.c> -> m\n<b> -> m\n<types.ModuleType.__await__> -> <types.ModuleType>\n<types.ModuleType> -> typing.Awaitable\n\n[case testIgnoredMissingInstanceAttribute]\nfrom a import C\nC().x  # type: ignore\n[file a.py]\nclass C: pass\n[out]\n<a.C.__await__> -> <a.C>\n<a.C.__init__> -> m\n<a.C.__new__> -> m\n<a.C.x> -> m\n<a.C> -> m, typing.Awaitable\n<a> -> m\n\n[case testIgnoredMissingClassAttribute]\nfrom a import C\nC.x  # type: ignore\n[file a.py]\nclass C: pass\n[out]\n<a.C.x> -> m\n<a.C> -> m\n<a> -> m\n\n[case testDepsFromOverloadMod]\n# __dump_all__\nimport mod\nx = mod.f\n[file mod.py]\nfrom typing import overload, Any\nimport submod\n@overload\ndef f(x: int) -> submod.A: pass\n@overload\ndef f(x: str) -> submod.B: pass\ndef f(x) -> Any:\n    y: submod.C\n    y.x\n    return y\n[file submod.py]\nclass A: pass\nclass B: pass\nclass C:\n    x: D\nclass D: pass\n[out]\n<m.x> -> m\n<mod.f> -> m\n<mod> -> m\n<submod.A> -> <m.x>, <mod.f>, mod.f, submod.A\n<submod.B> -> <m.x>, <mod.f>, mod.f, submod.B\n<submod.C.x> -> mod.f\n<submod.C> -> mod.f, submod.C\n<submod.D> -> <submod.C.x>, submod, submod.D\n<submod> -> mod\n\n[case testDepsFromOverloadFunc]\nimport mod\ndef f() -> None:\n    x = mod.f\n[file mod.py]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\ndef f(x):\n    pass\n[out]\n<mod.f> -> m.f\n<mod> -> m, m.f\n\n[case testDepsToOverloadMod]\nfrom typing import overload, Any\nimport mod\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\ndef f(x: Any) -> Any:\n    mod.g()\n    return mod\n[file mod.py]\ndef g() -> int:\n    pass\n[out]\n<mod.g> -> m.f\n<mod> -> m, m.f\n\n[case testDepsToOverloadFunc]\nfrom typing import overload, Any\nimport mod\ndef outer() -> None:\n    @overload\n    def f(x: int) -> mod.A: pass\n    @overload\n    def f(x: str) -> mod.B: pass\n    def f(x: Any) -> Any:\n        mod.g()\n        return mod\n[file mod.py]\ndef g() -> int:\n    pass\nclass A: pass\nclass B: pass\n[out]\n<mod.A> -> <m.outer>, m.outer\n<mod.B> -> <m.outer>, m.outer\n<mod.g> -> m.outer\n<mod> -> m, m.outer\n\n[case testDepsFromOverloadToOverload]\nfrom typing import overload, Any\nimport mod\ndef outer() -> None:\n    @overload\n    def f(x: int) -> None: pass\n    @overload\n    def f(x: str) -> str: pass\n    def f(x: Any) -> Any:\n        mod.g(str())\n        return mod\n[file mod.py]\nfrom typing import overload\n@overload\ndef g(x: int) -> None: pass\n@overload\ndef g(x: str) -> str: pass\ndef g(x):\n    pass\n[out]\n<mod.g> -> m.outer\n<mod> -> m, m.outer\n\n[case testDepsFromOverloadToOverloadDefaultClass]\nfrom typing import overload, Any\nimport mod\nclass Outer:\n    @overload\n    def f(self, x: int) -> None: pass\n    @overload\n    def f(self, x: str, cb=mod.g) -> str: pass\n    def f(self, *args: Any, **kwargs: Any) -> Any:\n        return args\n[file mod.py]\nfrom typing import overload\n@overload\ndef g(x: int) -> None: pass\n@overload\ndef g(x: str) -> str: pass\ndef g(x):\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n<m.Outer> -> m.Outer\n<mod.g> -> m.Outer.f\n<mod> -> m, m.Outer.f\n\n[case testDepsFromOverloadToOverloadDefaultNested]\nfrom typing import overload, Any\nimport mod\ndef outer() -> None:\n    @overload\n    def f(x: int) -> None: pass\n    @overload\n    def f(x: str, cb=mod.g) -> str: pass\n    def f(*args: Any, **kwargs: Any) -> Any:\n        pass\n[file mod.py]\nfrom typing import overload\n@overload\ndef g(x: int) -> None: pass\n@overload\ndef g(x: str) -> str: pass\ndef g(x):\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n<mod.g> -> m.outer\n<mod> -> m, m.outer\n\n[case testDepsToOverloadGeneric]\n# __dump_all__\nimport mod\nfrom typing import overload, Any\n@overload\ndef f(x: mod.TA) -> mod.TA: pass\n@overload\ndef f(x: mod.TB, y: int) -> mod.TB: pass\ndef f(*args: Any, **kwargs: Any) -> Any:\n    pass\n[file mod.py]\nfrom typing import TypeVar\nimport submod\nTA = TypeVar('TA', submod.A, submod.B)\nTB = TypeVar('TB', bound=submod.C)\n[file submod.py]\nclass A: pass\nclass B: pass\nclass C: pass\n[builtins fixtures/dict.pyi]\n[out]\n<mod.TA> -> <m.f>, m.f\n<mod.TB> -> <m.f>, m.f\n<mod> -> m\n<submod.A> -> <m.f>, <mod.TA>, m.f, mod, submod.A\n<submod.B> -> <m.f>, <mod.TA>, m.f, mod, submod.B\n<submod.C> -> <m.f>, <mod.TB>, m.f, mod, submod.C\n<submod> -> mod\n\n[case testDepsOverloadBothExternalAndImplementationType]\nimport mod\nfrom typing import overload\n@overload\ndef f(x: mod.A) -> mod.A: pass\n@overload\ndef f(x: mod.B) -> mod.B: pass\ndef f(x: mod.Base) -> mod.Base:\n    pass\n[file mod.py]\nclass Base:\n    pass\nclass A(Base):\n    pass\nclass B(Base):\n    pass\n[out]\n<mod.A> -> <m.f>, m.f\n<mod.B> -> <m.f>, m.f\n<mod.Base> -> <m.f>, m.f\n<mod> -> m\n\n[case testCustomIterator]\nclass A:\n    def __iter__(self) -> B: pass\nclass B:\n    def __iter__(self) -> B: pass\n    def __next__(self) -> C: pass\nclass C:\n    pass\ndef f() -> None:\n    for x in A(): pass\n[out]\n<m.A.__getitem__> -> m.f\n<m.A.__init__> -> m.f\n<m.A.__iter__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m.A, m.f\n<m.B.__next__> -> m.f\n<m.B> -> <m.A.__iter__>, <m.B.__iter__>, m.A.__iter__, m.B, m.B.__iter__\n<m.C> -> <m.B.__next__>, m.B.__next__, m.C\n\n[case testDepsLiskovClass]\nfrom mod import A, C\nclass D(C):\n    x: A\n[file mod.py]\nclass C:\n    x: B\nclass B:\n    pass\nclass A(B):\n    pass\n[out]\n<m.D.x> -> m\n<m.D> -> m.D\n<mod.A> -> <m.D.x>, m\n<mod.C.(abstract)> -> <m.D.__init__>, m\n<mod.C.__init__> -> <m.D.__init__>\n<mod.C.__new__> -> <m.D.__new__>\n<mod.C.x> -> <m.D.x>\n<mod.C> -> m, m.D\n<mod> -> m\n\n[case testDepsLiskovMethod]\nfrom mod import A, C\nclass D(C):\n    def __init__(self) -> None:\n        self.x: A\n[file mod.py]\nclass C:\n    def __init__(self) -> None:\n        self.x: B\nclass B:\n    pass\nclass A(B):\n    pass\n[out]\n<m.D.x> -> m.D.__init__\n<m.D> -> m.D\n<mod.A> -> <m.D.x>, m, m.D.__init__\n<mod.C.(abstract)> -> <m.D.__init__>, m\n<mod.C.__init__> -> <m.D.__init__>, m.D.__init__\n<mod.C.__new__> -> <m.D.__new__>\n<mod.C.x> -> <m.D.x>\n<mod.C> -> m, m.D\n<mod> -> m\n\n[case testIndexedStarLvalue]\nfrom typing import List, Tuple\n\nclass B:\n    def __setitem__(self, i: int, v: List[str]) -> None: pass\n\ndef g() -> Tuple[int, str, str]: pass\n\ndef f(b: B) -> None:\n    a, *b[0] = g()\n[builtins fixtures/list.pyi]\n[out]\n<m.B.__getitem__> -> m.f\n<m.B.__setitem__> -> m.f\n<m.B> -> <m.f>, m.B, m.f\n<m.g> -> m.f\n\n[case testLogicalDecorator]\n# flags: --logical-deps\nfrom mod import dec\n@dec\ndef f() -> None:\n    pass\n[file mod.py]\nfrom typing import Callable\ndef dec(f: Callable[[], None]) -> Callable[[], None]:\n    pass\n[out]\n<mod.dec> -> <m.f>, m\n\n[case testLogicalDecoratorWithArgs]\n# flags: --logical-deps\nfrom mod import dec\n@dec(str())\ndef f() -> None:\n    pass\n[file mod.py]\nfrom typing import Callable\ndef dec(arg: str) -> Callable[[Callable[[], None]], Callable[[], None]]:\n    pass\n[out]\n<mod.dec> -> <m.f>, m\n\n[case testLogicalDecoratorMember]\n# flags: --logical-deps\nimport mod\n@mod.dec\ndef f() -> None:\n    pass\n[file mod.py]\nfrom typing import Callable\ndef dec(f: Callable[[], None]) -> Callable[[], None]:\n    pass\n[out]\n<mod.dec> -> <m.f>, m\n<mod> -> m\n\n[case testLogicalDefinition]\n# flags: --logical-deps\nfrom mod import func\nb = func()\n[file mod.py]\ndef func() -> int:\n    pass\n[out]\n<m.b> -> m\n<mod.func> -> <m.b>, m\n\n[case testLogicalDefinitionIrrelevant]\n# flags: --logical-deps\nfrom mod import func\ndef outer() -> None:\n    a = func()\nb: int = func()\nc = int()\nc = func()\n[file mod.py]\ndef func() -> int:\n    pass\n[out]\n<m.b> -> m\n<m.c> -> m\n<mod.func> -> m, m.outer\n\n[case testLogicalDefinitionMember]\n# flags: --logical-deps\nimport mod\nb = mod.func()\n[file mod.py]\ndef func() -> int:\n    pass\n[out]\n<m.b> -> m\n<mod.func> -> <m.b>, m\n<mod> -> m\n\n[case testLogicalDefinitionClass]\n# flags: --logical-deps\nfrom mod import Cls\nb = Cls()\n[file mod.py]\nclass Base:\n    def __init__(self) -> None: pass\nclass Cls(Base): pass\n[out]\n<m.b> -> m\n<mod.Base.__init__> -> <m.b>\n<mod.Cls.__init__> -> m\n<mod.Cls.__new__> -> m\n<mod.Cls> -> <m.b>, m\n\n[case testLogicalBaseAttribute]\n# flags: --logical-deps\nfrom mod import C\nclass D(C):\n    x: int\n[file mod.py]\nclass C:\n    x: int\n    y: int\n[out]\n<m.D.x> -> m\n<m.D> -> m.D\n<mod.C.x> -> <m.D.x>\n<mod.C> -> m, m.D\n\n[case testLogicalIgnoredImport1]\n# flags: --logical-deps --ignore-missing-imports\nimport foo\ndef f() -> None:\n    foo.x\n[out]\n<foo.x> -> m.f\n<foo> -> m, m.f\n\n[case testLogicalIgnoredImport2]\n# flags: --logical-deps --ignore-missing-imports\nimport foo.bar\nimport a.b.c.d\ndef f() -> None:\n    foo.bar.x\n    foo.bar.x.y\n    a.b.c.d.e\n[out]\n<a.b.c.d.e> -> m.f\n<a.b.c.d> -> m, m.f\n<a.b.c> -> m.f\n<a.b> -> m.f\n<a> -> m.f\n<foo.bar.x.y> -> m.f\n<foo.bar.x> -> m.f\n<foo.bar> -> m, m.f\n<foo> -> m.f\n\n[case testLogicalIgnoredFromImport]\n# flags: --logical-deps --ignore-missing-imports\nfrom foo.bar import f, C\ndef g() -> None:\n    f()\n    C.ff()\ndef gg(x: C) -> None:\n    z = x.y\n    z.zz\n[out]\n<foo.bar.C.ff> -> m.g\n<foo.bar.C.y> -> m.gg\n<foo.bar.C> -> <m.gg>, m.g, m.gg\n<foo.bar.f> -> m.g\n\n[case testLogical__init__]\n# flags: --logical-deps\nclass A:\n    def __init__(self) -> None: pass\nclass B(A): pass\nclass C(B): pass\nclass D(A):\n    def __init__(self, x: int) -> None: pass\ndef f() -> None:\n    A()\ndef g() -> None:\n    C()\ndef h() -> None:\n    D(1)\n[out]\n<m.A.__init__> -> m.f\n<m.A.__new__> -> m.f\n<m.A> -> m, m.A, m.B, m.D, m.f\n<m.B> -> m, m.B, m.C\n<m.C.__init__> -> m.g\n<m.C.__new__> -> m.g\n<m.C> -> m.C, m.g\n<m.D.__init__> -> m.h\n<m.D.__new__> -> m.h\n<m.D> -> m.D, m.h\n\n[case testDataclassDepsOldVersion]\nfrom dataclasses import dataclass\n\nZ = int\n\n@dataclass\nclass A:\n    x: Z\n\n@dataclass\nclass B(A):\n    y: int\n[builtins fixtures/dataclasses.pyi]\n\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__dataclass_fields__> -> <m.B.__dataclass_fields__>\n<m.A.__init__> -> <m.B.__init__>, m.B.__init__\n<m.A.__mypy-replace> -> <m.B.__mypy-replace>, m, m.B.__mypy-replace\n<m.A.__new__> -> <m.B.__new__>\n<m.A.x> -> <m.B.x>\n<m.A.y> -> <m.B.y>\n<m.A> -> m, m.A, m.B\n<m.A[wildcard]> -> m\n<m.B.__mypy-replace> -> m\n<m.B.y> -> m\n<m.B> -> m.B\n<m.Z> -> m\n<dataclasses.dataclass> -> m\n<dataclasses> -> m\n\n[case testDataclassDeps]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\nZ = int\n\n@dataclass\nclass A:\n    x: Z\n\n@dataclass\nclass B(A):\n    y: int\n[builtins fixtures/dataclasses.pyi]\n\n[out]\n<m.A.(abstract)> -> <m.B.__init__>, m\n<m.A.__dataclass_fields__> -> <m.B.__dataclass_fields__>\n<m.A.__init__> -> <m.B.__init__>, m.B.__init__\n<m.A.__match_args__> -> <m.B.__match_args__>\n<m.A.__mypy-replace> -> <m.B.__mypy-replace>, m, m.B.__mypy-replace\n<m.A.__new__> -> <m.B.__new__>\n<m.A.x> -> <m.B.x>\n<m.A.y> -> <m.B.y>\n<m.A> -> m, m.A, m.B\n<m.A[wildcard]> -> m\n<m.B.__mypy-replace> -> m\n<m.B.y> -> m\n<m.B> -> m.B\n<m.Z> -> m\n<dataclasses.dataclass> -> m\n<dataclasses> -> m\n\n[case testPEP695TypeAliasDeps]\n# flags: --python-version=3.12\nfrom a import C, E\ntype A = C\ntype A2 = A\ntype A3 = E\n[file a.py]\nclass C: pass\nclass D: pass\ntype E = D\n[out]\n<m.A2> -> m\n<m.A3> -> m\n<m.A> -> m\n<a.C.__init__> -> m\n<a.C.__new__> -> m\n<a.C> -> m\n<a.E> -> m\n<a> -> m\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n"
  },
  {
    "path": "test-data/unit/diff.test",
    "content": "-- Test cases for taking a diff of two module ASTs/symbol tables.\n-- The diffs are used for fined-grained incremental checking.\n\n[case testChangeTypeOfModuleAttribute]\nx = 1\ny = 1\n[file next.py]\nx = ''\ny = 1\n[out]\n__main__.x\n\n[case testChangeSignatureOfModuleFunction]\ndef f(x: int) -> None:\n    pass\ndef g(y: str) -> None:\n    pass\n[file next.py]\ndef f(x: str) -> None:\n    x = ''\ndef g(y: str) -> None:\n    y = ''\n[out]\n__main__.f\n\n[case testAddModuleAttribute]\nx = 1\n[file next.py]\nx = 1\ny = 1\n[out]\n__main__.y\n\n[case testRemoveModuleAttribute]\nx = 1\ny = 1\n[file next.py]\nx = 1\n[out]\n__main__.y\n\n--\n-- Classes\n--\n\n[case testChangeMethodSignature]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[file next.py]\nclass A:\n    def f(self, x: int) -> None: pass\n    def g(self) -> None: pass\n[out]\n__main__.A.f\n\n[case testChangeAttributeType]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.y = 1\n[file next.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.y = ''\n[out]\n__main__.A.y\n\n[case testAddAttribute]\nclass A: pass\n[file next.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n[out]\n__main__.A.f\n__main__.A.x\n\n[case testAddAttribute2]\nclass A:\n    def f(self) -> None: pass\n[file next.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n[out]\n__main__.A.x\n\n[case testRemoveAttribute]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n[file next.py]\nclass A: pass\n[out]\n__main__.A.f\n__main__.A.x\n\n[case testAddMethod]\nclass A:\n    def f(self) -> None: pass\n[file next.py]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[out]\n__main__.A.g\n\n[case testRemoveMethod]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[file next.py]\nclass A:\n    def f(self) -> None: pass\n[out]\n__main__.A.g\n\n[case testAddImport]\nimport nn\n[file next.py]\nimport n\nimport nn\n[file n.py]\nx = 1\n[file nn.py]\ny = 1\n[out]\n__main__.n\n\n[case testRemoveImport]\nimport n\n[file next.py]\n[file n.py]\nx = 1\n[out]\n__main__.n\n\n[case testChangeClassIntoFunction]\nclass A: pass\n[file next.py]\ndef A() -> None: pass\n[out]\n__main__.A\n\n[case testDeleteClass]\nclass A: pass\n[file next.py]\n[out]\n__main__.A\n\n[case testAddBaseClass]\nclass A: pass\n[file next.py]\nclass B: pass\nclass A(B): pass\n[out]\n__main__.A\n__main__.B\n\n[case testChangeBaseClass]\nclass A: pass\nclass B: pass\nclass C(A): pass\n[file next.py]\nclass A: pass\nclass B: pass\nclass C(B): pass\n[out]\n__main__.C\n\n[case testRemoveBaseClass]\nclass A: pass\nclass B(A): pass\n[file next.py]\nclass A: pass\nclass B: pass\n[out]\n__main__.B\n\n[case testRemoveClassFromMiddleOfMro]\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n[file next.py]\nclass A: pass\nclass B: pass\nclass C(B): pass\n[out]\n__main__.B\n__main__.C\n\n[case testDifferenceInConstructor]\nclass A:\n    def __init__(self) -> None: pass\n[file next.py]\nclass A:\n    def __init__(self, x: int) -> None: pass\n[out]\n__main__.A.__init__\n\n[case testChangeSignatureOfMethodInNestedClass]\nclass A:\n    class B:\n        def f(self) -> int: pass\n[file next.py]\nclass A:\n    class B:\n        def f(self) -> str: pass\n[out]\n__main__.A.B.f\n\n[case testChangeTypeOfAttributeInNestedClass]\nclass A:\n    class B:\n        def f(self) -> None:\n            self.x = 1\n[file next.py]\nclass A:\n    class B:\n        def f(self) -> None:\n            self.x = ''\n[out]\n__main__.A.B.x\n\n[case testAddMethodToNestedClass]\nclass A:\n    class B: pass\n[file next.py]\nclass A:\n    class B:\n        def f(self) -> str: pass\n[out]\n__main__.A.B.f\n\n[case testAddNestedClass]\nclass A: pass\n[file next.py]\nclass A:\n    class B:\n        def f(self) -> None: pass\n[out]\n__main__.A.B\n\n[case testRemoveNestedClass]\nclass A:\n    class B:\n        def f(self) -> None: pass\n[file next.py]\nclass A: pass\n[out]\n__main__.A.B\n\n[case testChangeNestedClassToMethod]\nclass A:\n    class B: pass\n[file next.py]\nclass A:\n    def B(self) -> None: pass\n\n[out]\n__main__.A.B\n\n[case testChangeNamedTupleAttribute]\n\nfrom typing import NamedTuple\nclass A:\n    x: str\nN = NamedTuple('N', [('x', int), ('y', str)])\nM = NamedTuple('M', [('x', int), ('y', str)])\n[file next.py]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int), ('y', int)])\nM = NamedTuple('M', [('x', int), ('y', str)])\n[builtins fixtures/tuple.pyi]\n[out]\n__main__.A\n__main__.N\n__main__.N._NT\n__main__.N.__new__\n__main__.N._asdict\n__main__.N._make\n__main__.N._replace\n__main__.N.y\n\n[case testSimpleDecoratedFunction]\nfrom a import dec\n@dec\ndef f() -> None: pass\n@dec\ndef g() -> None: pass\n[file next.py]\nfrom a import dec\n@dec\ndef f(x: int) -> None: pass\n@dec\ndef g() -> None: pass\n[file a.py]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef dec(f: T) -> T:\n    return f\n[out]\n__main__.f\n\n[case testSimpleDecoratedMethod]\nfrom a import dec\nclass A:\n    @dec\n    def f(self) -> None:\n        self.g()\n    @dec\n    def g(self) -> None: pass\n[file next.py]\nfrom a import dec\nclass A:\n    @dec\n    def f(self, x: int) -> None:\n        self.g()\n    @dec\n    def g(self) -> None: pass\n[file a.py]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef dec(f: T) -> T:\n    return f\n[out]\n__main__.A.f\n\n[case testTypeVarBound]\nfrom typing import TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n[file next.py]\nfrom typing import TypeVar\nT = TypeVar('T', bound=int)\nS = TypeVar('S')\n[out]\n__main__.T\n\n[case testTypeVarVariance]\nfrom typing import TypeVar\nA = TypeVar('A', covariant=True)\nB = TypeVar('B', covariant=True)\nC = TypeVar('C', covariant=True)\n[file next.py]\nfrom typing import TypeVar\nA = TypeVar('A', covariant=True)\nB = TypeVar('B', contravariant=True)\nC = TypeVar('C')\n[out]\n__main__.B\n__main__.C\n\n[case testTypeVarValues]\nfrom typing import TypeVar\nA = TypeVar('A', int, str)\nB = TypeVar('B', int, str)\nC = TypeVar('C', int, str)\n[file next.py]\nfrom typing import TypeVar\nA = TypeVar('A', int, str)\nB = TypeVar('B', int, str, object)\nC = TypeVar('C')\n[out]\n__main__.B\n__main__.C\n\n[case testGenericFunction]\nfrom typing import TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\ndef f(x: T) -> T: pass\ndef g(x: S) -> S: pass\n[file next.py]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\nS = TypeVar('S')\ndef f(x: T) -> T: pass\ndef g(x: S) -> S: pass\n[out]\n__main__.T\n__main__.f\n\n[case testGenericTypes]\nfrom typing import List\nx: List[int]\ny: List[int]\n[file next.py]\nfrom typing import List\nx: List[int]\ny: List[str]\n[builtins fixtures/list.pyi]\n[out]\n__main__.y\n\n[case testTypeAliasOfList]\nfrom typing import List\nX = List[int]\nY = List[int]\n[file next.py]\nfrom typing import List\nX = List[str]\nY = List[int]\n[builtins fixtures/list.pyi]\n[out]\n__main__.X\n\n[case testTypeAliasOfCallable]\nfrom typing import Callable\nA = Callable[[int], str]\nB = Callable[[int], str]\nC = Callable[[int], str]\n[file next.py]\nfrom typing import Callable\nA = Callable[[int], str]\nB = Callable[[], str]\nC = Callable[[int], int]\n[out]\n__main__.B\n__main__.C\n\n[case testGenericTypeAlias]\nfrom typing import Callable, TypeVar\nT = TypeVar('T')\nA = Callable[[T], T]\nB = Callable[[T], T]\n[file next.py]\nfrom typing import Callable, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nA = Callable[[T], T]\nB = Callable[[T], S]\n[out]\n__main__.B\n__main__.S\n\n[case testDifferentListTypes]\nfrom typing import List\nA = List\nB = list\nC = List\n[file next.py]\nfrom typing import List\nA = List\nB = list\nC = list\n[builtins fixtures/list.pyi]\n[out]\n__main__.C\n\n[case testDecoratorChangesSignature]\nfrom contextlib import contextmanager\nfrom typing import Iterator, List, Tuple\n\n@contextmanager\ndef f(x: List[Tuple[int]]) -> Iterator[None]:\n    yield\n\n@contextmanager\ndef g(x: str) -> Iterator[None]:\n    yield\n[file next.py]\nfrom contextlib import contextmanager\nfrom typing import Iterator, List, Tuple\n\n@contextmanager\ndef f(x: List[Tuple[int]]) -> Iterator[None]:\n    yield\n\n@contextmanager\ndef g(x: object) -> Iterator[None]:\n    yield\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[out]\n__main__.g\n\n[case testOverloadedMethod]\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self, x: int) -> int: pass\n    @overload\n    def f(self, x: str) -> str: pass\n    def f(self, x): pass\n\n    @overload\n    def g(self, x: int) -> int: pass\n    @overload\n    def g(self, x: str) -> str: pass\n    def g(self, x): pass\n[file next.py]\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self, x: int) -> int: pass\n    @overload\n    def f(self, x: str) -> str: pass\n    def f(self, x): pass\n\n    @overload\n    def g(self, x: int) -> int: pass\n    @overload\n    def g(self, x: object) -> object: pass\n    def g(self, x): pass\n[out]\n__main__.A.g\n\n[case testPropertyWithSetter]\nclass A:\n    @property\n    def x(self) -> int:\n        pass\n\n    @x.setter\n    def x(self, o: int) -> None:\n        pass\n\nclass B:\n    @property\n    def x(self) -> int:\n        pass\n\n    @x.setter\n    def x(self, o: int) -> None:\n        pass\n[file next.py]\nclass A:\n    @property\n    def x(self) -> int:\n        pass\n\n    @x.setter\n    def x(self, o: int) -> None:\n        pass\n\nclass B:\n    @property\n    def x(self) -> str:\n        pass\n\n    @x.setter\n    def x(self, o: str) -> None:\n        pass\n[builtins fixtures/property.pyi]\n[out]\n__main__.B.x\n\n[case testFunctionalEnum]\nfrom enum import Enum, IntEnum\nA = Enum('A', 'x')\nB = Enum('B', 'x')\nC = Enum('C', 'x')\nD = IntEnum('D', 'x')\n[file next.py]\nfrom enum import Enum, IntEnum\nA = Enum('A', 'x')\nB = Enum('B', 'y')\nC = IntEnum('C', 'x')\nD = IntEnum('D', 'x y')\n[builtins fixtures/enum.pyi]\n[out]\n__main__.B.x\n__main__.B.y\n__main__.C\n__main__.D.y\n\n[case testClassBasedEnum]\nfrom enum import Enum\nclass A(Enum):\n    X = 0\n    Y = 1\nclass B(Enum):\n    X = 0\n    Y = 1\nclass C(Enum):\n    X = 0\n    Y = 1\nclass D(Enum):\n    X = 0\n    Y = 1\nclass E(Enum):\n    X = 0\n[file next.py]\nfrom enum import Enum\nclass A(Enum):\n    X = 0\n    Y = 1\nclass B(Enum):\n    X = 0\n    Z = 1\nclass C(Enum):\n    X = 0\n    Y = 1\n    Z = 2\nclass D(Enum):\n    X = 'a'\n    Y = 'b'\nclass F(Enum):\n    X = 0\n[builtins fixtures/enum.pyi]\n[out]\n__main__.B.Y\n__main__.B.Z\n__main__.C.Z\n__main__.D.X\n__main__.D.Y\n__main__.E\n__main__.F\n\n[case testTypedDict]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\n[file next.py]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': str})\np = Point(dict(x=42, y='lurr'))\n[builtins fixtures/dict.pyi]\n[out]\n__main__.Point\n__main__.p\n\n[case testTypedDict2]\nfrom mypy_extensions import TypedDict\nclass Point(TypedDict):\n    x: int\n    y: int\np = Point(dict(x=42, y=1337))\n[file next.py]\nfrom mypy_extensions import TypedDict\nclass Point(TypedDict):\n    x: int\n    y: str\np = Point(dict(x=42, y='lurr'))\n[builtins fixtures/dict.pyi]\n[out]\n__main__.Point\n__main__.p\n\n[case testTypedDict3]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\n[file next.py]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int})\np = Point(dict(x=42))\n[builtins fixtures/dict.pyi]\n[out]\n__main__.Point\n__main__.p\n\n[case testTypedDict4]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\n[file next.py]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int}, total=False)\np = Point(dict(x=42, y=1337))\n[builtins fixtures/dict.pyi]\n[out]\n__main__.Point\n__main__.p\n\n[case testTypeAliasSimple]\nA = int\nB = int\n[file next.py]\nA = str\nB = int\n[out]\n__main__.A\n\n[case testTypeAliasGeneric]\nfrom typing import List\nA = List[int]\nB = List[int]\n[file next.py]\nfrom typing import List\nA = List[str]\nB = List[int]\n[builtins fixtures/list.pyi]\n[out]\n__main__.A\n\n[case testTypeAliasGenToNonGen]\nfrom typing import List\nA = List[str]\nB = List\n[file next.py]\nfrom typing import List\nA = List\nB = List\n[builtins fixtures/list.pyi]\n[out]\n__main__.A\n\n[case testTypeAliasNonGenToGen]\nfrom typing import List\nA = List\nB = List\n[file next.py]\nfrom typing import List\nA = List[str]\nB = List\n[builtins fixtures/list.pyi]\n[out]\n__main__.A\n\n[case testTypeAliasGenericTypeVar]\nfrom typing import TypeVar, Dict\nT = TypeVar('T')\nS = TypeVar('S')\nA = Dict[str, T]\nB = Dict[str, S]\n[file next.py]\nfrom typing import TypeVar, Dict\nclass T: pass\nS = TypeVar('S')\nA = Dict[str, T]\nB = Dict[str, S]\n[builtins fixtures/dict.pyi]\n[out]\n__main__.A\n__main__.T\n\n[case testNewType]\nfrom typing import NewType\nclass C: pass\nclass D: pass\nN1 = NewType('N1', C)\nN2 = NewType('N2', D)\nN3 = NewType('N3', C)\nclass N4(C): pass\n[file next.py]\nfrom typing import NewType\nclass C: pass\nclass D(C): pass\nN1 = NewType('N1', C)\nN2 = NewType('N2', D)\nclass N3(C): pass\nN4 = NewType('N4', C)\n[out]\n__main__.D\n__main__.N2\n__main__.N3\n__main__.N3.__init__\n__main__.N4\n__main__.N4.__init__\n\n[case testChangeGenericBaseClassOnly]\nfrom typing import List\nclass C(List[int]): pass\n[file next.py]\nfrom typing import List\nclass C(List[str]): pass\n[builtins fixtures/list.pyi]\n[out]\n__main__.C\n\n[case testOverloads]\nfrom typing import overload\nclass C: pass\n@overload\ndef a(x: int) -> None: pass\n@overload\ndef a(x: str) -> str: pass\ndef a(x):\n    pass\n@overload\ndef b(x: int) -> None: pass\n@overload\ndef b(x: str) -> str: pass\ndef b(x):\n    pass\n@overload\ndef c(x: int) -> None: pass\n@overload\ndef c(x: str) -> str: pass\ndef c(x):\n    pass\n@overload\ndef d(x: int) -> None: pass\n@overload\ndef d(x: str) -> str: pass\ndef d(x):\n    pass\n[file next.py]\nfrom typing import overload\nclass C: pass\n@overload\ndef a(x: int) -> None: pass\n@overload\ndef a(x: str) -> str: pass\ndef a(x):\n    pass\n@overload\ndef b(x: str) -> str: pass\n@overload\ndef b(x: int) -> None: pass\ndef b(x):\n    pass\n@overload\ndef c(x: int) -> None: pass\n@overload\ndef c(x: str) -> str: pass\n@overload\ndef c(x: C) -> C: pass\ndef c(x):\n    pass\ndef d(x: int) -> None:\n    pass\n@overload\ndef e(x: int) -> None: pass\n@overload\ndef e(x: str) -> str: pass\ndef e(x):\n    pass\n[out]\n__main__.b\n__main__.c\n__main__.d\n__main__.e\n\n[case testOverloadsExternalOnly]\nfrom typing import overload\nclass Base: pass\nclass A(Base): pass\nclass B(Base): pass\nclass C(Base): pass\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: B) -> B: pass\ndef f(x: Base) -> Base:\n    pass\n@overload\ndef g(x: A) -> A: pass\n@overload\ndef g(x: B) -> B: pass\ndef g(x: Base) -> Base:\n    pass\n[file next.py]\nfrom typing import overload\nclass Base: pass\nclass A(Base): pass\nclass B(Base): pass\nclass C(Base): pass\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: B) -> B: pass\ndef f(x: object) -> object:\n    pass\n@overload\ndef g(x: A) -> A: pass\n@overload\ndef g(x: C) -> C: pass\ndef g(x: Base) -> Base:\n    pass\n[out]\n__main__.g\n\n[case testNestedFunctionDoesntMatter]\nclass A: pass\nclass B: pass\ndef outer() -> None:\n    def inner(x: A) -> B:\n        pass\n[file next.py]\nclass A: pass\nclass B: pass\ndef outer() -> None:\n    def inner(y: B) -> A:\n        pass\n[out]\n\n[case testProtocolVsNominal]\nfrom typing import Protocol\nclass A(Protocol):\n    x: int\nclass B(Protocol):\n    x: int\nclass C(Protocol):\n    x: int\nclass D(Protocol):\n    x: int\n[file next.py]\nfrom typing import Protocol\nclass A(Protocol):\n    x: int\nclass B(Protocol):\n    x: str\nclass C(Protocol):\n    x: int\n    y: int\nclass D:\n    x: int\n[out]\n__main__.B.x\n__main__.C.(abstract)\n__main__.C.y\n__main__.D\n__main__.D.(abstract)\n\n[case testProtocolNormalVsGeneric]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\nclass P(Protocol[T]):\n    x: T\nclass P2(Protocol[T]):\n    x: T\n    y: T\n[file next.py]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\nclass P(Protocol):\n    x: int\nclass P2(Protocol[T]):\n    x: T\n[out]\n__main__.P\n__main__.P.x\n__main__.P2.(abstract)\n__main__.P2.y\n\n[case testAddAbstractMethod]\nfrom abc import abstractmethod\nclass A:\n    @abstractmethod\n    def f(self) -> None: pass\n[file next.py]\nfrom abc import abstractmethod\nclass A:\n    @abstractmethod\n    def f(self) -> None: pass\n    @abstractmethod\n    def g(self) -> None: pass\n[out]\n__main__.A.(abstract)\n__main__.A.g\n\n[case testFinalFlagsTriggerVar]\nfrom typing import Final\n\nv: Final = 1\nw: Final = 1\nx: Final = 1\ny: Final[int] = 1\nz: Final[int] = 1\nsame1: Final = 1\nsame2: Final[int] = 1\nclass C:\n    v: Final = 1\n    w: Final = 1\n    x: Final = 1\n    y: Final[int] = 1\n    z: Final[int] = 1\n    same1: Final = 1\n    same2: Final[int] = 1\n    def __init__(self) -> None:\n        self.vi: Final = 1\n        self.wi: Final = 1\n        self.xi: Final = 1\n        self.yi: Final[int] = 1\n        self.zi: Final[int] = 1\n        self.same1_instance: Final = 1\n        self.same2_instance: Final[int] = 1\n\n[file next.py]\nfrom typing import Final\n\nv: Final = 0\nw = 1\nx: Final[int] = 1\ny: int = 1\nz: Final = 1\nsame1: Final = 1\nsame2: Final[int] = 0\nclass C:\n    v: Final = 0\n    w = 1\n    x: Final[int]  = 1\n    y: int = 1\n    z: Final = 1\n    same1: Final = 1\n    same2: Final[int] = 0\n    def __init__(self) -> None:\n        self.vi: Final = 0\n        self.wi = 1\n        self.xi: Final[int] = 1\n        self.yi: int = 1\n        self.zi: Final = 1\n        self.same1_instance: Final = 1\n        self.same2_instance: Final[int] = 0\n[out]\n__main__.C.same2\n__main__.C.same2_instance\n__main__.C.v\n__main__.C.vi\n__main__.C.w\n__main__.C.wi\n__main__.C.y\n__main__.C.yi\n__main__.same2\n__main__.v\n__main__.w\n__main__.y\n\n[case testFinalFlagsTriggerMethod]\nfrom typing import final\n\nclass C:\n    def meth(self) -> int: pass\n    @final\n    def same(self) -> int: pass\n    @classmethod\n    def cmeth(cls) -> int: pass\n\n[file next.py]\nfrom typing import final\n\nclass C:\n    @final\n    def meth(self) -> int: pass\n    @final\n    def same(self) -> int: pass\n    @final\n    @classmethod\n    def cmeth(cls) -> int: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n__main__.C.cmeth\n__main__.C.meth\n\n[case testFinalFlagsTriggerProperty]\nfrom typing import final\n\nclass C:\n    @final\n    @property\n    def p(self) -> int: pass\n    @final\n    @property\n    def same(self) -> str: pass\n\n[file next.py]\nfrom typing import final\n\nclass C:\n    @property\n    def p(self) -> int: pass\n    @final\n    @property\n    def same(self) -> str: pass\n[builtins fixtures/property.pyi]\n[out]\n__main__.C.p\n\n[case testFinalFlagsTriggerMethodOverload]\nfrom typing import final, overload\n\nclass C:\n    @overload\n    def m(self, x: int) -> int: ...\n    @overload\n    def m(self, x: str) -> str: ...\n    @final\n    def m(self, x):\n        pass\n    @overload\n    def same(self, x: int) -> int: ...\n    @overload\n    def same(self, x: str) -> str: ...\n    @final\n    def same(self, x):\n        pass\n\n[file next.py]\nfrom typing import final, overload\n\nclass C:\n    @overload\n    def m(self, x: int) -> int: ...\n    @overload\n    def m(self, x: str) -> str: ...\n    def m(self, x):\n        pass\n    @overload\n    def same(self, x: int) -> int: ...\n    @overload\n    def same(self, x: str) -> str: ...\n    @final\n    def same(self, x):\n        pass\n[out]\n__main__.C.m\n\n[case testDynamicBasePluginDiff]\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]\nclass Diff:\n    x: Column[int]\n[file next.py]\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]\nclass Diff(Base):\n    x: Column[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[out]\n__main__.Diff\n__main__.Diff.x\n\n[case testLiteralTriggersVar]\nfrom typing_extensions import Literal\n\nx: Literal[1] = 1\ny = 1\nz: Literal[1] = 1\nsame: Literal[1] = 1\nclass C:\n    x_class: Literal[1] = 1\n    y_class = 1\n    z_class: Literal[1] = 1\n    same_class: Literal[1] = 1\n    def __init__(self) -> None:\n        self.x_instance: Literal[1] = 1\n        self.y_instance = 1\n        self.z_instance: Literal[1] = 1\n        self.same_instance: Literal[1] = 1\n\n[file next.py]\nfrom typing_extensions import Literal\n\nx = 1\ny: Literal[1] = 1\nz: Literal[2] = 2\nsame: Literal[1] = 1\nclass C:\n    x_class = 1\n    y_class: Literal[1] = 1\n    z_class: Literal[2] = 2\n    same_class: Literal[1] = 1\n    def __init__(self) -> None:\n        self.x_instance = 1\n        self.y_instance: Literal[1] = 1\n        self.z_instance: Literal[2] = 2\n        self.same_instance: Literal[1] = 1\n[builtins fixtures/tuple.pyi]\n[out]\n__main__.C.x_class\n__main__.C.x_instance\n__main__.C.y_class\n__main__.C.y_instance\n__main__.C.z_class\n__main__.C.z_instance\n__main__.x\n__main__.y\n__main__.z\n\n[case testLiteralTriggersFunctions]\nfrom typing_extensions import Literal\n\ndef function_1() -> int: pass\ndef function_2() -> Literal[1]: pass\ndef function_3() -> Literal[1]: pass\n\ndef function_4(x: int) -> None: pass\ndef function_5(x: Literal[1]) -> None: pass\ndef function_6(x: Literal[1]) -> None: pass\n\ndef function_same_1() -> Literal[1]: pass\ndef function_same_2(x: Literal[1]) -> None: pass\n\nclass C:\n    def method_1(self) -> int: pass\n    def method_2(self) -> Literal[1]: pass\n    def method_3(self) -> Literal[1]: pass\n\n    def method_4(self, x: int) -> None: pass\n    def method_5(self, x: Literal[1]) -> None: pass\n    def method_6(self, x: Literal[1]) -> None: pass\n\n    def method_same_1(self) -> Literal[1]: pass\n    def method_same_2(self, x: Literal[1]) -> None: pass\n\n    @classmethod\n    def classmethod_1(cls) -> int: pass\n    @classmethod\n    def classmethod_2(cls) -> Literal[1]: pass\n    @classmethod\n    def classmethod_3(cls) -> Literal[1]: pass\n\n    @classmethod\n    def classmethod_4(cls, x: int) -> None: pass\n    @classmethod\n    def classmethod_5(cls, x: Literal[1]) -> None: pass\n    @classmethod\n    def classmethod_6(cls, x: Literal[1]) -> None: pass\n\n    @classmethod\n    def classmethod_same_1(cls) -> Literal[1]: pass\n    @classmethod\n    def classmethod_same_2(cls, x: Literal[1]) -> None: pass\n\n    @staticmethod\n    def staticmethod_1() -> int: pass\n    @staticmethod\n    def staticmethod_2() -> Literal[1]: pass\n    @staticmethod\n    def staticmethod_3() -> Literal[1]: pass\n\n    @staticmethod\n    def staticmethod_4(x: int) -> None: pass\n    @staticmethod\n    def staticmethod_5(x: Literal[1]) -> None: pass\n    @staticmethod\n    def staticmethod_6(x: Literal[1]) -> None: pass\n\n    @staticmethod\n    def staticmethod_same_1() -> Literal[1]: pass\n    @staticmethod\n    def staticmethod_same_2(x: Literal[1]) -> None: pass\n\n[file next.py]\nfrom typing_extensions import Literal\n\ndef function_1() -> Literal[1]: pass\ndef function_2() -> int: pass\ndef function_3() -> Literal[2]: pass\n\ndef function_4(x: Literal[1]) -> None: pass\ndef function_5(x: int) -> None: pass\ndef function_6(x: Literal[2]) -> None: pass\n\ndef function_same_1() -> Literal[1]: pass\ndef function_same_2(x: Literal[1]) -> None: pass\n\nclass C:\n    def method_1(self) -> Literal[1]: pass\n    def method_2(self) -> int: pass\n    def method_3(self) -> Literal[2]: pass\n\n    def method_4(self, x: Literal[1]) -> None: pass\n    def method_5(self, x: int) -> None: pass\n    def method_6(self, x: Literal[2]) -> None: pass\n\n    def method_same_1(self) -> Literal[1]: pass\n    def method_same_2(self, x: Literal[1]) -> None: pass\n\n    @classmethod\n    def classmethod_1(cls) -> Literal[1]: pass\n    @classmethod\n    def classmethod_2(cls) -> int: pass\n    @classmethod\n    def classmethod_3(cls) -> Literal[2]: pass\n\n    @classmethod\n    def classmethod_4(cls, x: Literal[1]) -> None: pass\n    @classmethod\n    def classmethod_5(cls, x: int) -> None: pass\n    @classmethod\n    def classmethod_6(cls, x: Literal[2]) -> None: pass\n\n    @classmethod\n    def classmethod_same_1(cls) -> Literal[1]: pass\n    @classmethod\n    def classmethod_same_2(cls, x: Literal[1]) -> None: pass\n\n    @staticmethod\n    def staticmethod_1() -> Literal[1]: pass\n    @staticmethod\n    def staticmethod_2() -> int: pass\n    @staticmethod\n    def staticmethod_3() -> Literal[2]: pass\n\n    @staticmethod\n    def staticmethod_4(x: Literal[1]) -> None: pass\n    @staticmethod\n    def staticmethod_5(x: int) -> None: pass\n    @staticmethod\n    def staticmethod_6(x: Literal[2]) -> None: pass\n\n    @staticmethod\n    def staticmethod_same_1() -> Literal[1]: pass\n    @staticmethod\n    def staticmethod_same_2(x: Literal[1]) -> None: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n__main__.C.classmethod_1\n__main__.C.classmethod_2\n__main__.C.classmethod_3\n__main__.C.classmethod_4\n__main__.C.classmethod_5\n__main__.C.classmethod_6\n__main__.C.method_1\n__main__.C.method_2\n__main__.C.method_3\n__main__.C.method_4\n__main__.C.method_5\n__main__.C.method_6\n__main__.C.staticmethod_1\n__main__.C.staticmethod_2\n__main__.C.staticmethod_3\n__main__.C.staticmethod_4\n__main__.C.staticmethod_5\n__main__.C.staticmethod_6\n__main__.function_1\n__main__.function_2\n__main__.function_3\n__main__.function_4\n__main__.function_5\n__main__.function_6\n\n[case testLiteralTriggersProperty]\nfrom typing_extensions import Literal\n\nclass C:\n    @property\n    def p1(self) -> Literal[1]: pass\n\n    @property\n    def p2(self) -> int: pass\n\n    @property\n    def same(self) -> Literal[1]: pass\n\n[file next.py]\nfrom typing_extensions import Literal\n\nclass C:\n    @property\n    def p1(self) -> int: pass\n\n    @property\n    def p2(self) -> Literal[1]: pass\n\n    @property\n    def same(self) -> Literal[1]: pass\n[builtins fixtures/property.pyi]\n[out]\n__main__.C.p1\n__main__.C.p2\n\n[case testLiteralsTriggersOverload]\nfrom typing import overload\nfrom typing_extensions import Literal\n\n@overload\ndef func(x: str) -> str: ...\n@overload\ndef func(x: Literal[1])  -> int: ...\ndef func(x):\n    pass\n\n@overload\ndef func_same(x: str) -> str: ...\n@overload\ndef func_same(x: Literal[1])  -> int: ...\ndef func_same(x):\n    pass\n\nclass C:\n    @overload\n    def method(self, x: str) -> str: ...\n    @overload\n    def method(self, x: Literal[1]) -> int: ...\n    def method(self, x):\n        pass\n\n    @overload\n    def method_same(self, x: str) -> str: ...\n    @overload\n    def method_same(self, x: Literal[1]) -> int: ...\n    def method_same(self, x):\n        pass\n\n[file next.py]\nfrom typing import overload\nfrom typing_extensions import Literal\n\n@overload\ndef func(x: str) -> str: ...\n@overload\ndef func(x: Literal[2])  -> int: ...\ndef func(x):\n    pass\n\n@overload\ndef func_same(x: str) -> str: ...\n@overload\ndef func_same(x: Literal[1])  -> int: ...\ndef func_same(x):\n    pass\n\nclass C:\n    @overload\n    def method(self, x: str) -> str: ...\n    @overload\n    def method(self, x: Literal[2]) -> int: ...\n    def method(self, x):\n        pass\n\n    @overload\n    def method_same(self, x: str) -> str: ...\n    @overload\n    def method_same(self, x: Literal[1]) -> int: ...\n    def method_same(self, x):\n        pass\n[builtins fixtures/tuple.pyi]\n[out]\n__main__.C.method\n__main__.func\n\n[case testUnionOfLiterals]\nfrom typing_extensions import Literal\nx: Literal[1, '2']\n[file next.py]\nfrom typing_extensions import Literal\nx: Literal[1, 2]\n[builtins fixtures/tuple.pyi]\n[out]\n__main__.x\n\n[case testUnionOfCallables]\nfrom typing import Callable, Union\nfrom mypy_extensions import Arg\nx: Union[Callable[[Arg(int, 'x')], None],\n         Callable[[int], None]]\n[file next.py]\nfrom typing import Callable, Union\nfrom mypy_extensions import Arg\nx: Union[Callable[[Arg(int, 'y')], None],\n         Callable[[int], None]]\n[builtins fixtures/tuple.pyi]\n[out]\n__main__.x\n\n[case testChangeParamSpec]\nfrom typing import ParamSpec, TypeVar\nA = ParamSpec('A')\nB = ParamSpec('B')\nC = TypeVar('C')\n[file next.py]\nfrom typing import ParamSpec, TypeVar\nA = ParamSpec('A')\nB = TypeVar('B')\nC = ParamSpec('C')\n[out]\n__main__.B\n__main__.C\n\n[case testEmptyBodySuper]\nfrom abc import abstractmethod\nclass C:\n    @abstractmethod\n    def meth(self) -> int: ...\n[file next.py]\nfrom abc import abstractmethod\nclass C:\n    @abstractmethod\n    def meth(self) -> int: return 0\n[out]\n__main__.C.meth\n\n[case testGenericFunctionWithOptionalReturnType]\nfrom typing import Type, TypeVar\n\nT = TypeVar(\"T\")\n\nclass C:\n    @classmethod\n    def get_by_team_and_id(\n        cls: Type[T],\n        raw_member_id: int,\n        include_removed: bool = False,\n    ) -> T:\n        pass\n\n[file next.py]\nfrom typing import Type, TypeVar, Optional\n\nT = TypeVar(\"T\")\n\nclass C:\n    @classmethod\n    def get_by_team_and_id(\n        cls: Type[T],\n        raw_member_id: int,\n        include_removed: bool = False,\n    ) -> Optional[T]:\n        pass\n\n[builtins fixtures/classmethod.pyi]\n[out]\n__main__.C.get_by_team_and_id\n__main__.Optional\n\n[case testPEP695TypeAlias]\n# flags: --python-version=3.12\nfrom typing_extensions import TypeAlias, TypeAliasType\ntype A = int\ntype B = str\ntype C = int\nD = int\nE: TypeAlias = int\nF = TypeAliasType(\"F\", int)\nG = TypeAliasType(\"G\", int)\ntype H = int\n\n[file next.py]\n# flags: --python-version=3.12\nfrom typing_extensions import TypeAlias, TypeAliasType\ntype A = str\ntype B = str\ntype C[T] = int\ntype D = int\ntype E = int\ntype F = int\ntype G = str\ntype H[T] = int\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\n__main__.A\n__main__.C\n__main__.D\n__main__.G\n__main__.H\n\n[case testPEP695TypeAlias2]\n# flags: --python-version=3.12\ntype A[T: int] = list[T]\ntype B[T: int] = list[T]\ntype C[T: (int, str)] = list[T]\ntype D[T: (int, str)] = list[T]\ntype E[T: int] = list[T]\ntype F[T: (int, str)] = list[T]\n\n[file next.py]\n# flags: --python-version=3.12\ntype A[T] = list[T]\ntype B[T: str] = list[T]\ntype C[T: (int, None)] = list[T]\ntype D[T] = list[T]\ntype E[T: int] = list[T]\ntype F[T: (int, str)] = list[T]\n\n[out]\n__main__.A\n__main__.B\n__main__.C\n__main__.D\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695GenericFunction]\n# flags: --python-version=3.12\ndef f[T](x: T) -> T:\n    return x\ndef g[T](x: T, y: T) -> T:\n    return x\n[file next.py]\n# flags: --python-version=3.12\ndef f[T](x: T) -> T:\n    return x\ndef g[T, S](x: T, y: S) -> S:\n    return y\n[out]\n__main__.g\n\n[case testPEP695GenericClass]\n# flags: --python-version=3.12\nclass C[T]:\n    pass\nclass D[T]:\n    pass\nclass E[T]:\n    pass\nclass F[T]:\n    def f(self, x: object) -> T: ...\n[file next.py]\n# flags: --python-version=3.12\nclass C[T]:\n    pass\nclass D[T: int]:\n    pass\nclass E:\n    pass\nclass F[T]:\n    def f(self, x: T) -> T: ...\n[out]\n__main__.D\n__main__.E\n__main__.F\n__main__.F.f\n"
  },
  {
    "path": "test-data/unit/envvars.test",
    "content": "# Test cases related to environment variables\n[case testEnvvar_MYPY_CONFIG_FILE_DIR]\n# cmd: mypy --config-file=subdir/mypy.ini\n[file bogus.py]\nFOO = 'x'  # type: int\n[file subdir/good.py]\nBAR = 0  # type: int\n[file subdir/mypy.ini]\n\\[mypy]\nfiles=$MYPY_CONFIG_FILE_DIR/good.py\n"
  },
  {
    "path": "test-data/unit/errorstream.test",
    "content": "-- Test cases for incremental error streaming.\n-- Each time errors are reported, '==== Errors flushed ====' is printed.\n\n[case testErrorStream]\nimport b\n[file a.py]\n1 + ''\n[file b.py]\nimport a\n'' / 2\n[out]\n==== Errors flushed ====\na.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n==== Errors flushed ====\nb.py:2: error: Unsupported operand types for / (\"str\" and \"int\")\n\n[case testBlockers]\nimport b\n[file a.py]\n1 + ''\n[file b.py]\nimport a\nbreak\n1 / ''  # won't get reported, after a blocker\n[out]\n==== Errors flushed ====\na.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n==== Errors flushed ====\nb.py:2: error: \"break\" outside loop\n\n[case testCycles]\nimport a\n[file a.py]\nimport b\n1 + ''\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    reveal_type(a.y)\n    return a.y\n1 / ''\nx = 1 + int()\n\n[out]\n==== Errors flushed ====\nb.py:3: note: Revealed type is \"builtins.int\"\nb.py:5: error: Unsupported operand types for / (\"int\" and \"str\")\n==== Errors flushed ====\na.py:2: error: Unsupported operand types for + (\"int\" and \"str\")\na.py:4: note: Revealed type is \"builtins.int\"\n"
  },
  {
    "path": "test-data/unit/fine-grained-attr.test",
    "content": "[case updateMagicField]\nfrom attrs import Attribute\nimport m\n\ndef g() -> Attribute[int]:\n    return m.A.__attrs_attrs__[0]\n\n[file m.py]\nfrom attrs import define\n\n@define\nclass A:\n    a: int\n[file m.py.2]\nfrom attrs import define\n\n@define\nclass A:\n    a: float\n[builtins fixtures/plugin_attrs.pyi]\n[out]\n==\nmain:5: error: Incompatible return value type (got \"Attribute[float]\", expected \"Attribute[int]\")\n\n[case magicAttributeConsistency]\nimport m\n\n[file c.py]\nfrom attrs import define\n\n@define\nclass A:\n    a: float\n    b: int\n[builtins fixtures/plugin_attrs.pyi]\n\n[file m.py]\nfrom c import A\n\nA.__attrs_attrs__.a\n\n[file m.py.2]\nfrom c import A\n\nA.__attrs_attrs__.b\n\n[out]\n==\n\n[case magicAttributeConsistency2-only_when_cache]\n[file c.py]\nimport attrs\n\n@attrs.define\nclass Entry:\n    var: int\n[builtins fixtures/plugin_attrs.pyi]\n\n[file m.py]\nfrom typing import Any, ClassVar, Protocol\nfrom c import Entry\n\nclass AttrsInstance(Protocol):\n    __attrs_attrs__: ClassVar[Any]\n\ndef func(e: AttrsInstance) -> None: ...\nfunc(Entry(2))\n\n[file m.py.2]\nfrom typing import Any, ClassVar, Protocol\nfrom c import Entry\n\nclass AttrsInstance(Protocol):\n    __attrs_attrs__: ClassVar[Any]\n\ndef func(e: AttrsInstance) -> int:\n    return 2  # Change return type to force reanalysis\n\nfunc(Entry(2))\n\n[out]\n==\n"
  },
  {
    "path": "test-data/unit/fine-grained-blockers.test",
    "content": "-- Test cases for fine-grained incremental mode and blocking errors\n--\n-- The comments in fine-grained.test explain how these tests work.\n\n-- TODO:\n-- - blocking error while other existing errors as well (that get preserved)\n-- - differences in other modules + blocking error\n\n[case testParseError]\nimport a\na.f()\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\ndef f(x: int) ->\n[file a.py.3]\ndef f(x: int) -> None: pass\n[file a.py.4]\ndef f() -> None: pass\n[out]\n==\na.py:1: error: invalid syntax\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n[out version>=3.10]\n==\na.py:1: error: expected ':'\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testParseErrorShowSource]\n# flags: --pretty --show-error-codes\nimport a\na.f()\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\ndef f(x: int) ->\n[file a.py.3]\ndef f(x: int) -> None: pass\n[file a.py.4]\ndef f() -> None: pass\n[out]\n==\na.py:1: error: invalid syntax  [syntax]\n    def f(x: int) ->\n                    ^\n==\nmain:3: error: Missing positional argument \"x\" in call to \"f\"  [call-arg]\n    a.f()\n    ^~~~~\n==\n[out version>=3.10]\n==\na.py:1: error: expected ':'  [syntax]\n    def f(x: int) ->\n                   ^\n==\nmain:3: error: Missing positional argument \"x\" in call to \"f\"  [call-arg]\n    a.f()\n    ^~~~~\n==\n\n[case testParseErrorMultipleTimes]\nimport a\na.f()\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\ndef f(x: int) ->\n[file a.py.3]\ndef f(x: int\n      ) -> None\n[file a.py.4]\ndef f(x: int) -> None: pass\n[out]\n==\na.py:1: error: invalid syntax\n==\na.py:2: error: invalid syntax\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n[out version>=3.10]\n==\na.py:1: error: expected ':'\n==\na.py:2: error: expected ':'\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testSemanticAnalysisBlockingError]\nimport a\na.f()\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\ndef f() -> None: pass\nbreak\n[file a.py.3]\ndef f(x: int) -> None: pass\n[out]\n==\na.py:2: error: \"break\" outside loop\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testBlockingErrorWithPreviousError]\nimport a\nimport b\na.f(1)\ndef g() -> None:\n    b.f(1)\n[file a.py]\ndef f() -> None: pass\n[file b.py]\ndef f() -> None: pass\n[file a.py.2]\ndef f() -> None\n[file a.py.3]\ndef f() -> None: pass\n[out]\nmain:3: error: Too many arguments for \"f\"\nmain:5: error: Too many arguments for \"f\"\n==\na.py:1: error: invalid syntax\n==\nmain:3: error: Too many arguments for \"f\"\nmain:5: error: Too many arguments for \"f\"\n[out version>=3.10]\nmain:3: error: Too many arguments for \"f\"\nmain:5: error: Too many arguments for \"f\"\n==\na.py:1: error: expected ':'\n==\nmain:3: error: Too many arguments for \"f\"\nmain:5: error: Too many arguments for \"f\"\n\n[case testUpdateClassReferenceAcrossBlockingError]\nimport a\nc: a.C\n\ndef f() -> None:\n    c.f()\n[file a.py]\nclass C:\n    def f(self) -> None: pass\n[file a.py.2]\nerror error\n[file a.py.3]\nclass C:\n    def f(self, x: int) -> None: pass\n[out]\n==\na.py:1: error: invalid syntax\n==\nmain:5: error: Missing positional argument \"x\" in call to \"f\" of \"C\"\n[out version==3.10.0]\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\nmain:5: error: Missing positional argument \"x\" in call to \"f\" of \"C\"\n\n[case testAddFileWithBlockingError]\nimport a\na.f(1)\n[file a.py.2]\nx x\n[file a.py.3]\ndef f() -> None: pass\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\na.py:1: error: invalid syntax\n==\nmain:2: error: Too many arguments for \"f\"\n[out version==3.10.0]\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\nmain:2: error: Too many arguments for \"f\"\n\n[case testModifyTwoFilesOneWithBlockingError1]\nimport a\n[file a.py]\nimport b\ndef f() -> None: pass\nb.g()\n[file b.py]\nimport a\na.f()\ndef g() -> None: pass\n[file a.py.2]\nimport b  # Dummy edit\ndef f() -> None: pass\nb.g()\n[file b.py.2]\nimport a a  # Syntax error\na.f()\ndef g() -> None: pass\n[file b.py.3]\nimport a\na.f()\ndef g() -> None: pass\n[out]\n==\nb.py:1: error: invalid syntax\n==\n\n[case testModifyTwoFilesOneWithBlockingError2]\nimport a\n[file a.py]\nimport b\ndef f() -> None: pass\nb.g()\n[file b.py]\nimport a\na.f()\ndef g() -> None: pass\n[file a.py.2]\nimport b b\ndef f() -> None: pass\nb.g()\n[file b.py.2]\nimport a  # Dummy edit\na.f()\ndef g() -> None: pass\n[file a.py.3]\nimport b\ndef f() -> None: pass\nb.g()\n[out]\n==\na.py:1: error: invalid syntax\n==\n\n[case testBlockingErrorRemainsUnfixed]\nimport a\n[file a.py]\nimport b\nb.f()\n[file b.py]\ndef f() -> None: pass\n[file a.py.2]\nx x\n[file b.py.3]\ndef f(x: int) -> None: pass\n[file a.py.4]\nimport b\nb.f()\n[out]\n==\na.py:1: error: invalid syntax\n==\na.py:1: error: invalid syntax\n==\na.py:2: error: Missing positional argument \"x\" in call to \"f\"\n[out version==3.10.0]\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\na.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testModifyTwoFilesIntroduceTwoBlockingErrors]\nimport a\n[file a.py]\nimport b\ndef f() -> None: pass\nb.g()\n[file b.py]\nimport a\na.f()\ndef g() -> None: pass\n[file a.py.2]\nimport b b\ndef f() -> None: pass\nb.g()\n[file b.py.2]\nimport a a\na.f()\ndef g() -> None: pass\n[file a.py.3]\nimport b b\ndef f() -> None: pass\nb.g()\n[file b.py.3]\nimport a a\na.f()\ndef g() -> None: pass\n[file a.py.4]\nimport b\ndef f() -> None: pass\nb.g(1)\n[file b.py.4]\nimport a\ndef g() -> None: pass\na.f(1)\n[out]\n==\na.py:1: error: invalid syntax\n==\na.py:1: error: invalid syntax\n==\na.py:3: error: Too many arguments for \"g\"\nb.py:3: error: Too many arguments for \"f\"\n\n[case testDeleteFileWithBlockingError-only_when_nocache]\n-- Different cache/no-cache tests because:\n-- Error message ordering differs\nimport a\nimport b\n[file a.py]\ndef f() -> None: pass\n[file b.py]\nimport a\na.f()\n[file a.py.2]\nx x\n[delete a.py.3]\n[out]\n==\na.py:1: error: invalid syntax\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\n[out version==3.10.0]\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\n\n[case testDeleteFileWithBlockingError2-only_when_cache]\n-- Different cache/no-cache tests because:\n-- Error message ordering differs\nimport a\nimport b\n[file a.py]\ndef f() -> None: pass\n[file b.py]\nimport a\na.f()\n[file a.py.2]\nx x\n[delete a.py.3]\n[out]\n==\na.py:1: error: invalid syntax\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\n[out version==3.10.0]\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\n\n[case testModifyFileWhileBlockingErrorElsewhere]\nimport a\nimport b\n[file a.py]\n[file b.py]\nimport a\n[file a.py.2]\nx x\n[file b.py.3]\nimport a\na.f()\n1()\n[file a.py.4]\n[builtins fixtures/module.pyi]\n[out]\n==\na.py:1: error: invalid syntax\n==\na.py:1: error: invalid syntax\n==\nb.py:2: error: Module has no attribute \"f\"\nb.py:3: error: \"int\" not callable\n[out version==3.10.0]\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\nb.py:2: error: Module has no attribute \"f\"\nb.py:3: error: \"int\" not callable\n\n[case testImportBringsAnotherFileWithBlockingError1]\nimport a\n[file a.py]\n[file a.py.2]\nimport blocker\n1()\n[file a.py.3]\n1()\ndef f() -> None: pass\n[out]\n==\n<ROOT>/test-data/unit/lib-stub/blocker.pyi:2: error: invalid syntax\n==\na.py:1: error: \"int\" not callable\n[out version==3.10.0]\n==\n<ROOT>/test-data/unit/lib-stub/blocker.pyi:2: error: invalid syntax. Perhaps you forgot a comma?\n==\na.py:1: error: \"int\" not callable\n\n[case testImportBringsAnotherFileWithSemanticAnalysisBlockingError]\nimport a\n[file a.py]\n[file a.py.2]\nimport blocker2\n1()\n[file a.py.3]\n1()\n[out]\n==\n<ROOT>/test-data/unit/lib-stub/blocker2.pyi:2: error: \"continue\" outside loop\n==\na.py:1: error: \"int\" not callable\n\n[case testFixingBlockingErrorTriggersDeletion1-only_when_nocache]\n-- Disabled in cache mdode:\n-- Cache mode fails to produce the error in the final step, but this is\n-- a manifestation of a bug that can occur in no-cache mode also.\nimport a\n\ndef g(x: a.A) -> None:\n    x.f()\n[file a.py]\nclass A:\n    def f(self) -> None: pass\n[delete a.py.2]\n[file a.py.3]\nclass A: pass\n[builtins fixtures/module.pyi]\n[out]\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:4: error: \"A\" has no attribute \"f\"\n\n[case testFixingBlockingErrorTriggersDeletion2]\nfrom a import A\n\ndef g(x: A) -> None:\n    x.f()\n[file a.py]\nclass A:\n    def f(self) -> None: pass\n[delete a.py.2]\n[file a.py.3]\n[builtins fixtures/module.pyi]\n[out]\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:1: error: Module \"a\" has no attribute \"A\"\n\n[case testFixingBlockingErrorBringsInAnotherModuleWithBlocker]\nimport a\n[file a.py]\n[file a.py.2]\nx y\n[file a.py.3]\nimport blocker\n1()\n[file a.py.4]\nimport sys\n1()\n[builtins fixtures/tuple.pyi]\n[out]\n==\na.py:1: error: invalid syntax\n==\n<ROOT>/test-data/unit/lib-stub/blocker.pyi:2: error: invalid syntax\n==\na.py:2: error: \"int\" not callable\n[out version==3.10.0]\n==\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\n<ROOT>/test-data/unit/lib-stub/blocker.pyi:2: error: invalid syntax. Perhaps you forgot a comma?\n==\na.py:2: error: \"int\" not callable\n\n[case testInitialBlocker]\n# cmd: mypy a.py b.py\n[file a.py]\n1 1\n[file b.py]\ndef f() -> int:\n    return ''\n[file a.py.2]\nx = 1\n[file b.py.3]\ndef f() -> int:\n    return 0\n[out]\na.py:1: error: invalid syntax\n==\nb.py:2: error: Incompatible return value type (got \"str\", expected \"int\")\n==\n[out version==3.10.0]\na.py:1: error: invalid syntax. Perhaps you forgot a comma?\n==\nb.py:2: error: Incompatible return value type (got \"str\", expected \"int\")\n==\n\n[case testDecodeErrorBlocker1-posix]\nimport a\na.f(1)\n[file a.py]\ndef f(x: int) -> None: ...\n[file a.py.2]\n# coding: ascii\nä = 1\n[file a.py.3]\ndef f(x: str) -> None: ...\n[out]\n==\nmypy: can't decode file 'tmp/a.py': 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testDecodeErrorBlocker2-windows]\nimport a\na.f(1)\n[file a.py]\ndef f(x: int) -> None: ...\n[file a.py.2]\n# coding: ascii\nä = 1\n[file a.py.3]\ndef f(x: str) -> None: ...\n[out]\n==\nmypy: can't decode file 'tmp/a.py': 'ascii' codec can't decode byte 0xc3 in position 17: ordinal not in range(128)\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testDecodeErrorBlockerOnInitialRun-posix]\n# Note that there's no test variant for Windows, since the above Windows test case is good enough.\nimport a\na.f(1)\n[file a.py]\n# coding: ascii\nä = 1\n[file a.py.2]\ndef f(x: str) -> None: ...\n[out]\nmypy: can't decode file 'tmp/a.py': 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)\n==\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n"
  },
  {
    "path": "test-data/unit/fine-grained-cache-incremental.test",
    "content": "-- Test cases for building caches for fine-grained mode using incremental\n-- builds.\n--\n-- These tests are run only with the cache.\n--\n-- '# num_build_steps: N' specifies how many regular build steps (without the daemon)\n-- to do before switching to running using the daemon. Default is 1.\n\n\n-- Add file\n-- --------\n\n\n[case testIncrCacheBasic1]\n# num_build_steps: 2\nimport a\n[file a.py]\nfrom b import x\ndef f() -> int:\n    return 0\n[file b.py]\nx = 1\n[file a.py.2]\nfrom b import x\ndef f() -> int:\n    return 0 + x\n[file b.py.3]\nx = 'hi'\n[out]\n==\n==\na.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testIncrCacheBasic2]\n# num_build_steps: 2\nimport a\n[file a.py]\nfrom b import x\ndef f() -> int:\n    return 0+x\n[file b.py]\nx = 1\n[file b.py.2]\nfrom c import x\n[file c.py.2]\nx = 1\n[file c.py.3]\nx = 'hi'\n[out]\n==\n==\na.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testIncrCacheDoubleChange1]\n# num_build_steps: 2\nimport b\nimport c\n[file a.py]\ndef f(x: int) -> None:\n    pass\n[file b.py]\nfrom a import f\nf(10)\n[file c.py]\nfrom a import f\nf(10)\n\n[file a.py.2]\ndef f(x: int) -> None:\n    pass\n# nothing changed\n\n[file a.py.3]\ndef f(x: str) -> None:\n    pass\n[out]\n==\n==\nc.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\nb.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testIncrCacheProtocol1]\n# num_build_steps: 2\nimport a\n[file a.py]\nimport b\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\ndef f() -> None:\n    def g(x: P) -> None:\n        pass\n    g(b.C())\n[file c.py]\n[file c.py.2]\n# yo\n[file b.py]\nclass C:\n    x: int\n[file b.py.3]\nclass C:\n    x: str\n-- If we did a *full* reload (because the proto cache failed to load),\n-- nothing would show up as stale\n[stale2 b]\n[rechecked2 a, b]\n[out]\n==\n==\na.py:8: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:8: note: Following member(s) of \"C\" have conflicts:\na.py:8: note:     x: expected \"int\", got \"str\"\n\n[case testIncrCacheProtocol2]\n# num_build_steps: 3\nimport a\n[file a.py]\nimport b\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\nclass Q(Protocol):\n    x: int\ndef f() -> None:\n    def g(x: P) -> None:\n        pass\n    g(b.C())\n[file c.py]\n[file c.py.2]\n# uh\n[file c.py.3]\nfrom a import Q\nimport b\ndef f() -> None:\n    def g(x: Q) -> None:\n        pass\n    g(b.C())\n[file b.py]\nclass C:\n    x: int\n[file b.py.4]\nclass C:\n    x: str\n-- If we did a *full* reload (because the proto cache failed to load),\n-- nothing would show up as stale\n[stale3 b]\n[rechecked3 a, b, c]\n[out]\n==\n==\n==\nc.py:6: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"Q\"\nc.py:6: note: Following member(s) of \"C\" have conflicts:\nc.py:6: note:     x: expected \"int\", got \"str\"\na.py:10: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:10: note: Following member(s) of \"C\" have conflicts:\na.py:10: note:     x: expected \"int\", got \"str\"\n\n[case testIncrCacheProtocol3]\n# num_build_steps: 2\nimport a\n[file a.py]\nimport b\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\ndef f() -> None:\n    def g(x: P) -> None:\n        pass\n    g(b.C())\n[file c.py]\n[file c.py.2]\n# yo\n[file b.py]\nclass C:\n    x: int\n[file b.py.3]\nclass C:\n    x: int\n    y: int\n[file b.py.4]\nclass C:\n    x: str\n    y: int\n-- If we did a *full* reload (because the proto cache failed to load),\n-- nothing would show up as stale\n[stale2 b]\n[rechecked2 b]\n[stale3 b]\n[rechecked3 a, b]\n[out]\n==\n==\n==\na.py:8: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:8: note: Following member(s) of \"C\" have conflicts:\na.py:8: note:     x: expected \"int\", got \"str\"\n\n[case testIncrCacheBustedProtocol]\n# flags: --no-sqlite-cache\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\n[file b.py.2]\n# uh\n-- A full reload shows up as nothing getting rechecked by fine-grained mode.\n-- If we did not do a full reload, b would be stale and checked in fine-grained mode\n[stale]\n[rechecked]\n[out]\n==\n\n[case testInvalidateCachePart]\n# flags: --no-sqlite-cache\n# cmd: mypy a1.py a2.py b.py p/__init__.py p/c.py\n[file a1.py]\nimport p\nfrom b import x\nfrom p.c import C\n\n[file a2.py]\nimport p\nfrom b import x\nfrom p.c import C\n\n[file b.py]\nx = 10\n\n[file p/__init__.py]\n[file p/c.py]\nclass C: pass\n\n[delete ../.mypy_cache/3.9/b.meta.json.2]\n[delete ../.mypy_cache/3.9/p/c.meta.json.2]\n\n[out]\n==\n"
  },
  {
    "path": "test-data/unit/fine-grained-cycles.test",
    "content": "-- Test cases for fine-grained incremental checking and import cycles\n--\n-- The comment at the top of fine-grained.test explains how these tests\n-- work.\n\n[case testFunctionSelfReferenceThroughImportCycle]\nimport a\n[file a.py]\nfrom b import f\n[file b.py]\nimport a\n\ndef f() -> None:\n    a.f()\n[file b.py.2]\nimport a\n\ndef f(x: int) -> None:\n    a.f()\n[out]\n==\nb.py:4: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testClassSelfReferenceThroughImportCycle]\nimport a\n[file a.py]\nfrom b import A\n[file b.py]\nimport a\n\nclass A:\n    def g(self) -> None: pass\n\ndef f() -> None:\n    a.A().g()\n[file b.py.2]\nimport a\n\nclass A:\n    def g(self, x: int) -> None: pass\n\ndef f() -> None:\n    a.A().g()\n[out]\n==\nb.py:7: error: Missing positional argument \"x\" in call to \"g\" of \"A\"\n\n[case testAnnotationSelfReferenceThroughImportCycle]\nimport a\n[file a.py]\nfrom b import A\n[file b.py]\nimport a\n\nx: a.A\n\nclass A:\n    def g(self) -> None: pass\n\ndef f() -> None:\n    x.g()\n[file b.py.2]\nimport a\n\nx: a.A\n\nclass A:\n    def g(self, x: int) -> None: pass\n\ndef f() -> None:\n    x.g()\n[out]\n==\nb.py:9: error: Missing positional argument \"x\" in call to \"g\" of \"A\"\n\n[case testModuleSelfReferenceThroughImportCycle]\nimport a\n[file a.py]\nimport b\n[file b.py]\nimport a\n\ndef f() -> None:\n    a.b.f()\n[file b.py.2]\nimport a\n\ndef f(x: int) -> None:\n    a.b.f()\n[out]\n==\nb.py:4: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testVariableSelfReferenceThroughImportCycle]\nimport a\n[file a.py]\nfrom b import x\n[file b.py]\nimport a\n\nx: int\n\ndef f() -> None:\n    a.x = 1\n[file b.py.2]\nimport a\n\nx: str\n\ndef f() -> None:\n    a.x = 1\n[out]\n==\nb.py:6: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testReferenceToTypeThroughCycle]\nimport a\n\n[file a.py]\nfrom b import C\n\ndef f() -> C: pass\n\n[file b.py]\nimport a\n\nclass C:\n    def g(self) -> None: pass\n\ndef h() -> None:\n    c = a.f()\n    c.g()\n\n[file b.py.2]\nimport a\n\nclass C:\n    def g(self, x: int) -> None: pass\n\ndef h() -> None:\n    c = a.f()\n    c.g()\n\n[out]\n==\nb.py:8: error: Missing positional argument \"x\" in call to \"g\" of \"C\"\n\n[case testReferenceToTypeThroughCycleAndDeleteType]\nimport a\n\n[file a.py]\nfrom b import C\n\ndef f() -> C: pass\n\n[file b.py]\nimport a\n\nclass C:\n    def g(self) -> None: pass\n\ndef h() -> None:\n    c = a.f()\n    c.g()\n\n[file b.py.2]\nimport a\n\ndef h() -> None:\n    c = a.f()\n    c.g()\n\n[out]\n==\na.py:1: error: Module \"b\" has no attribute \"C\"\n\n[case testReferenceToTypeThroughCycleAndReplaceWithFunction]\n\nimport a\n\n[file a.py]\nfrom b import C\n\ndef f() -> C: pass\n\n[file b.py]\nimport a\n\nclass C:\n    def g(self) -> None: pass\n\ndef h() -> None:\n    c = a.f()\n    c.g()\n\n[file b.py.2]\nimport a\n\ndef C() -> int: pass\n\ndef h() -> None:\n    c = a.f()\n    c.g()\n\n[out]\n==\na.py:3: error: Function \"b.C\" is not valid as a type\na.py:3: note: Perhaps you need \"Callable[...]\" or a callback protocol?\nb.py:7: error: C? has no attribute \"g\"\n\n-- TODO: More import cycle:\n--\n-- * \"from x import y\" through cycle\n-- * \"from x import *\" through cycle\n-- * \"Cls.module\" though cycle\n-- * TypeVar\n-- * type alias\n-- * all kinds of reference deleted\n-- * all kinds of reference rebound to different kind\n--\n-- etc.\n"
  },
  {
    "path": "test-data/unit/fine-grained-dataclass-transform.test",
    "content": "[case updateDataclassTransformParameterViaDecorator]\n# flags: --python-version 3.11\nfrom m import my_dataclass\n\n@my_dataclass\nclass Foo:\n    x: int\n\nfoo = Foo(1)\nfoo.x = 2\n\n[file m.py]\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=False)\ndef my_dataclass(cls): return cls\n\n[file m.py.2]\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=True)\ndef my_dataclass(cls): return cls\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[out]\n==\nmain:9: error: Property \"x\" defined in \"Foo\" is read-only\n\n[case updateDataclassTransformParameterViaParentClass]\n# flags: --python-version 3.11\nfrom m import Dataclass\n\nclass Foo(Dataclass):\n    x: int\n\nfoo = Foo(1)\nfoo.x = 2\n\n[file m.py]\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=False)\nclass Dataclass: ...\n\n[file m.py.2]\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=True)\nclass Dataclass: ...\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[out]\n==\nmain:8: error: Property \"x\" defined in \"Foo\" is read-only\n\n[case updateBaseClassToUseDataclassTransform]\n# flags: --python-version 3.11\nfrom m import A\n\nclass B(A):\n    y: int\n\nB(x=1, y=2)\n\n[file m.py]\nclass Dataclass: ...\n\nclass A(Dataclass):\n    x: int\n\n[file m.py.2]\nfrom typing import dataclass_transform\n\n@dataclass_transform()\nclass Dataclass: ...\n\nclass A(Dataclass):\n    x: int\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[out]\nmain:7: error: Unexpected keyword argument \"x\" for \"B\"\nbuiltins.pyi:14: note: \"B\" defined here\nmain:7: error: Unexpected keyword argument \"y\" for \"B\"\nbuiltins.pyi:14: note: \"B\" defined here\n==\n\n[case frozenInheritanceViaDefault]\n# flags: --python-version 3.11\nfrom foo import Foo\n\nfoo = Foo(base=0, foo=1)\n\n[file transform.py]\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform(frozen_default=True)\ndef dataclass(cls: Type) -> Type: return cls\n\n[file base.py]\nfrom transform import dataclass\n\n@dataclass\nclass Base:\n    base: int\n\n[file foo.py]\nfrom base import Base\nfrom transform import dataclass\n\n@dataclass\nclass Foo(Base):\n    foo: int\n\n[file foo.py.2]\nfrom base import Base\nfrom transform import dataclass\n\n@dataclass\nclass Foo(Base):\n    foo: int\n    bar: int = 0\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n# If the frozen parameter is being maintained correctly, we *don't* expect to see issues; if it's\n# broken in incremental mode, then we'll see an error about inheriting a non-frozen class from a\n# frozen one.\n#\n# Ideally we'd also add a `foo.foo = 2` to confirm that frozen semantics are actually being\n# enforced, but incremental tests currently can't start with an error, which makes it tricky to\n# write such a test case.\n[out]\n==\n"
  },
  {
    "path": "test-data/unit/fine-grained-dataclass.test",
    "content": "[case testReplace]\n[file model.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Model:\n    x: int = 0\n[file replace.py]\nfrom dataclasses import replace\nfrom model import Model\n\nm = Model()\nreplace(m, x=42)\n\n[file model.py.2]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Model:\n    x: str = 'hello'\n\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nreplace.py:5: error: Argument \"x\" to \"replace\" of \"Model\" has incompatible type \"int\"; expected \"str\"\n"
  },
  {
    "path": "test-data/unit/fine-grained-follow-imports.test",
    "content": "-- Test cases for --follow-imports=normal in fine-grained incremental mode.\n--\n-- Note that the implementation is mostly separate from normal incremental mode.\n\n[case testFollowImportsNormalBasic]\n# flags: --follow-imports=normal\n# cmd: mypy main.py a.py\n\n[file main.py]\nimport a\na.f()\n\n[file a.py]\ndef f() -> None: pass\n\n[file a.py.2]\ndef f(x: str) -> None: pass\n\n[file a.py.3]\ndef f() -> None: pass\n\n[out]\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalAddSuppressed]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\na.f()\n\n[file a.py.2]\ndef f(x: str) -> None: pass\n\n[file a.py.3]\ndef f() -> None: pass\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"a\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalAddSuppressed2]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a  # type: ignore\na.f()\n\n[file a.py.2]\ndef f(x: str) -> None: pass\n\n[file a.py.3]\ndef f() -> None: pass\n\n[out]\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalAddSuppressed3]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\na.b.f()\n\n[file a.py.2]\nimport b\n\n[file b.py.2]\ndef f(x: str) -> None: pass\n\n[file b.py.3]\ndef f() -> None: pass\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"a\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalEditingFileBringNewModule]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\n\n[file main.py.2]\nimport a\na.f()\n\n[file a.py.2]\ndef f(x: str) -> None: pass\n\n[file a.py.3]\ndef f() -> None: pass\n\n[out]\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalEditingFileBringNewModules]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\n\n[file main.py.2]\nimport a\na.b.f()\n\n[file a.py.2]\nimport b\n\n[file b.py.2]\ndef f(x: str) -> None: pass\n\n[file b.py.3]\ndef f() -> None: pass\n\n[out]\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalDuringStartup]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\na.f()\n\n[file a.py]\ndef f() -> None: pass\n\n[file a.py.2]\ndef f(x: str) -> None: pass\n\n[out]\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testFollowImportsNormalDuringStartup2]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\na.f()\n\n[file a.py]\ndef f(x: str) -> None: pass\n\n[file a.py.2]\ndef f() -> None: pass\n\n[out]\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalDuringStartup3]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\na.g()\n\n[file a.py]\nimport b\ng = b.f\n\n[file b.py]\ndef f(x: str) -> None: pass\n\n[file b.py.2]\ndef f() -> None: pass\n\n[file a.py.3]\ng = 0\n\n[out]\nmain.py:2: error: Too few arguments\n==\n==\nmain.py:2: error: \"int\" not callable\n\n[case testFollowImportsNormalDeleteFile1]\n# flags: --follow-imports=normal\n# cmd: mypy main.py a.py\n# cmd2: mypy main.py\n# cmd3: mypy main.py a.py\n\n[file main.py]\nimport a\na.f()\n\n[file a.py]\ndef f() -> None: pass\n\n[delete a.py.2]\n\n[file a.py.3]\ndef f(x: str) -> None: pass\n\n[out]\n==\nmain.py:1: error: Cannot find implementation or library stub for module named \"a\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testFollowImportsNormalDeleteFile2]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\na.f()\n\n[file a.py]\ndef f() -> None: pass\n\n[delete a.py.2]\n\n[file a.py.3]\ndef f(x: str) -> None: pass\n\n[out]\n==\nmain.py:1: error: Cannot find implementation or library stub for module named \"a\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testFollowImportsNormalDeleteFile3]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a  # type: ignore\na.f()\n\n[file a.py]\ndef f() -> None: pass\n\n[delete a.py.2]\n\n[file a.py.3]\ndef f(x: str) -> None: pass\n\n[out]\n==\n==\nmain.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testFollowImportsNormalDeleteFile4]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\n\n[file a.py]\n1()\n\n[file main.py.2]\n# don't import a\n\n[file main.py.3]\nimport a\n\n[out]\na.py:1: error: \"int\" not callable\n==\n==\na.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalDeleteFile5]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\n\n[file a.py]\nimport b\n\n[file b.py]\n1()\n\n[file a.py.2]\n# don't import b\n\n[file a.py.3]\nimport b\n\n[out]\nb.py:1: error: \"int\" not callable\n==\n==\nb.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalDeleteFile6]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\n\n[file a.py]\nimport b\n\n[file b.py]\n1()\n\n[delete a.py.2]\n\n[file a.py.3]\nimport b\n\n[out]\nb.py:1: error: \"int\" not callable\n==\nmain.py:1: error: Cannot find implementation or library stub for module named \"a\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nb.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalDeleteFile7]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\n\n[file a.py]\nimport b\nfrom c import f\n\n[file b.py]\nfrom d import *\n\n[file c.py]\nimport a\ndef f(): pass\n1()\n\n[file d.py]\n1()\n\n[file main.py.2]\n\n[file main.py.3]\nimport d\n\n[out]\nd.py:1: error: \"int\" not callable\nc.py:3: error: \"int\" not callable\n==\n==\nd.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalKeepAliveViaNewFile]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport a\n\n[file a.py]\nimport b\n\n[file b.py]\n1()\n\n[file a.py.2]\nimport c\n\n[file c.py.2]\nimport d\n\n[file d.py.2]\nimport b\n\n[out]\nb.py:1: error: \"int\" not callable\n==\nb.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalPackage-only_when_nocache]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport p.m  # type: ignore\n\np.m.f()\n\n[file p/__init__.py.2]\n\n[file p/m.py.2]\ndef f(x: str) -> None: pass\n\n1()\n\n[file p/m.py.3]\ndef f(x: str) -> None: pass\n\n[delete p.4]\n\n[out]\n==\np/m.py:3: error: \"int\" not callable\nmain.py:3: error: Missing positional argument \"x\" in call to \"f\"\n==\nmain.py:3: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testFollowImportsNormalPackage2-only_when_cache]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport p.m  # type: ignore\n\np.m.f()\n\n[file p/__init__.py.2]\n\n[file p/m.py.2]\ndef f(x: str) -> None: pass\n\n1()\n\n[delete p.3]\n\n[out]\n==\nmain.py:3: error: Missing positional argument \"x\" in call to \"f\"\np/m.py:3: error: \"int\" not callable\n==\n\n[case testFollowImportsNormalPackageInitFile1]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport p1.m\nfrom p2 import m\n\n[file p1/__init__.py.2]\n1()\n\n[file p1/m.py.2]\n\n[file p2/__init__.py.3]\n''()\n\n[file p2/m.py.3]\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"p1.m\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain.py:1: error: Cannot find implementation or library stub for module named \"p1\"\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2\"\n==\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2\"\nmain.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\np1/__init__.py:1: error: \"int\" not callable\n==\np1/__init__.py:1: error: \"int\" not callable\np2/__init__.py:1: error: \"str\" not callable\n\n[case testFollowImportsNormalPackageInitFile2]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nfrom p import m\n\n[file p/__init__.py.2]\n\n[file p/m.py.3]\n''()\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"p\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain.py:1: error: Module \"p\" has no attribute \"m\"\n==\np/m.py:1: error: \"str\" not callable\n\n[case testFollowImportsNormalPackageInitFile3]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport p1.s1.m\nfrom p2.s2 import m\np1.s1.m.f()\nm.f(1)\n\n[file p1/__init__.py.2]\n\n[file p1/s1/__init__.py.2]\n\n[file p1/s1/m.py.2]\ndef f(x: str) -> None: pass\n\n[file p2/__init__.py.3]\n\n[file p2/s2/__init__.py.3]\n\n[file p2/s2/m.py.3]\ndef f() -> None: pass\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"p1.s1.m\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain.py:1: error: Cannot find implementation or library stub for module named \"p1.s1\"\nmain.py:1: error: Cannot find implementation or library stub for module named \"p1\"\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2.s2\"\n==\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2.s2\"\nmain.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain.py:3: error: Missing positional argument \"x\" in call to \"f\"\n==\nmain.py:3: error: Missing positional argument \"x\" in call to \"f\"\nmain.py:4: error: Too many arguments for \"f\"\n\n[case testFollowImportsNormalPackageInitFile4-only_when_cache]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport p1.m  # type: ignore\nfrom p2 import m  # type: ignore\n\n[file p1/__init__.py.2]\n1()\n\n[file p1/m.py.2]\n''()\n\n[file p2/__init__.py.3]\n''()\n\n[file p2/m.py.3]\n\n[out]\n==\np1/__init__.py:1: error: \"int\" not callable\np1/m.py:1: error: \"str\" not callable\n==\np1/__init__.py:1: error: \"int\" not callable\np1/m.py:1: error: \"str\" not callable\np2/__init__.py:1: error: \"str\" not callable\n\n[case testFollowImportsNormalSubmoduleCreatedWithImportInFunction]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\ndef f() -> None:\n    from p import m\n\n[file p/__init__.py.2]\n1()\n\n[file p/m.py.2]\n''()\n\n[out]\nmain.py:2: error: Cannot find implementation or library stub for module named \"p\"\nmain.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\np/__init__.py:1: error: \"int\" not callable\np/m.py:1: error: \"str\" not callable\n\n[case testFollowImportsNormalPackageInitFileStub]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nfrom p import m\n\n[file p/__init__.pyi.2]\n1()\n\n[file p/m.pyi.2]\n''()\n\n[file p/mm.pyi.3]\nx x x\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"p\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\np/__init__.pyi:1: error: \"int\" not callable\np/m.pyi:1: error: \"str\" not callable\n==\np/__init__.pyi:1: error: \"int\" not callable\np/m.pyi:1: error: \"str\" not callable\n\n[case testFollowImportsNormalNamespacePackages]\n# flags: --follow-imports=normal --namespace-packages\n# cmd: mypy main.py\n\n[file main.py]\nimport p1.m1\nimport p2.m2\n\n[file p1/m1.py]\n1()\n\n[file p2/m2.py.2]\n''()\n\n[delete p2/m2.py.3]\n\n[out]\np1/m1.py:1: error: \"int\" not callable\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2.m2\"\nmain.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2\"\n==\np1/m1.py:1: error: \"int\" not callable\np2/m2.py:1: error: \"str\" not callable\n==\np1/m1.py:1: error: \"int\" not callable\nmain.py:2: error: Cannot find implementation or library stub for module named \"p2.m2\"\nmain.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testFollowImportsNormalNewFileOnCommandLine]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n# cmd2: mypy main.py x.py\n\n[file main.py]\n1()\n\n[file x.py.2]\n''()\n\n[out]\nmain.py:1: error: \"int\" not callable\n==\nmain.py:1: error: \"int\" not callable\nx.py:1: error: \"str\" not callable\n\n[case testFollowImportsNormalSearchPathUpdate-only_when_nocache]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n# cmd2: mypy main.py src/foo.py\n\n[file main.py]\n\n[file src/foo.py.2]\nimport bar\n''()\n\n[file src/bar.py.2]\n1()\n\n[out]\n==\nsrc/foo.py:2: error: \"str\" not callable\nsrc/bar.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalSearchPathUpdate2-only_when_cache]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n# cmd2: mypy main.py src/foo.py\n\n[file main.py]\n\n[file src/foo.py.2]\nimport bar\n''()\n\n[file src/bar.py.2]\n1()\n\n[out]\n==\nsrc/foo.py:2: error: \"str\" not callable\nsrc/bar.py:1: error: \"int\" not callable\n\n[case testFollowImportsNormalSuppressedAffectsCachedFile-only_when_cache]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nfrom p import m  # type: ignore\nm.f(1)\n\n[file p/__init__.py]\n\n[file p/m.py.2]\n# This change will trigger a cached file (main.py) through a suppressed\n# submodule, resulting in additional errors in main.py.\ndef f() -> None: pass\n\n[out]\n==\nmain.py:2: error: Too many arguments for \"f\"\n\n[case testFollowImportsNormalMultipleImportedModulesSpecialCase]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport pkg\n\n[file pkg/__init__.py.2]\nfrom . import mod1\n\n[file pkg/mod1.py.2]\nfrom . import mod2\n\n[file pkg/mod2.py.2]\n\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"pkg\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n\n[case testFollowImportsNormalDeletePackage]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n\n[file main.py]\nimport pkg\n\n[file pkg/__init__.py]\nfrom . import mod\n\n[file pkg/mod.py]\nfrom . import mod2\nimport pkg2\n\n[file pkg/mod2.py]\nfrom . import mod2\nimport pkg2\n\n[file pkg2/__init__.py]\nfrom . import mod3\n\n[file pkg2/mod3.py]\n\n[delete pkg/.2]\n[delete pkg2/.2]\n\n[out]\n==\nmain.py:1: error: Cannot find implementation or library stub for module named \"pkg\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testNewImportCycleTypeVarBound]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n# cmd2: mypy other.py\n\n[file main.py]\n# empty\n\n[file other.py.2]\nimport trio\n\n[file trio/__init__.py.2]\nfrom typing import TypeVar\nimport trio\nfrom . import abc as abc\n\nT = TypeVar(\"T\", bound=trio.abc.A)\n\n[file trio/abc.py.2]\nimport trio\nclass A: ...\n[out]\n==\n\n[case testNewImportCycleTupleBase]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n# cmd2: mypy other.py\n\n[file main.py]\n# empty\n\n[file other.py.2]\nimport trio\n\n[file trio/__init__.py.2]\nfrom typing import TypeVar, Tuple\nimport trio\nfrom . import abc as abc\n\nclass C(Tuple[trio.abc.A, trio.abc.A]): ...\n\n[file trio/abc.py.2]\nimport trio\nclass A: ...\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNewImportCycleTypedDict]\n# flags: --follow-imports=normal\n# cmd: mypy main.py\n# cmd2: mypy other.py\n\n[file main.py]\n# empty\n\n[file other.py.2]\nimport trio\n\n[file trio/__init__.py.2]\nfrom typing import TypeVar\nfrom typing_extensions import TypedDict\nimport trio\nfrom . import abc as abc\n\nclass C(TypedDict):\n    x: trio.abc.A\n    y: trio.abc.A\n\n[file trio/abc.py.2]\nimport trio\nclass A: ...\n[builtins fixtures/dict.pyi]\n[out]\n==\n"
  },
  {
    "path": "test-data/unit/fine-grained-inspect.test",
    "content": "[case testInspectTypeBasic]\n# inspect2: --include-kind tmp/foo.py:10:13\n# inspect2: --show=type --include-kind tmp/foo.py:10:13\n# inspect2: --include-span -vv tmp/foo.py:12:5\n# inspect2: --include-span --include-kind tmp/foo.py:12:5:12:9\nimport foo\n[file foo.py]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None: ...\n    x: T\n\ndef foo(arg: C[T]) -> T:\n    return arg.x\n\nfoo(C(42))\n[out]\n==\nNameExpr -> \"C[T]\"\nMemberExpr -> \"T\"\nNameExpr -> \"C[T]\"\nMemberExpr -> \"T\"\n12:5:12:5 -> \"Type[foo.C[builtins.int]]\"\n12:5:12:9 -> \"foo.C[builtins.int]\"\n12:1:12:10 -> \"builtins.int\"\nCallExpr:12:5:12:9 -> \"C[int]\"\n\n[case testInspectAttrsBasic]\n# inspect2: --show=attrs tmp/foo.py:6:1\n# inspect2: --show=attrs tmp/foo.py:7:1\n# inspect2: --show=attrs tmp/foo.py:10:1\n# inspect2: --show=attrs --include-object-attrs  tmp/foo.py:10:1\nimport foo\n[file foo.py]\nfrom bar import Meta\nclass C(metaclass=Meta):\n    x: int\n    def meth(self) -> None: ...\n\nc: C\nC\n\ndef foo() -> int: ...\nfoo\n[file bar.py]\nclass Meta(type):\n    y: int\n[out]\n==\n{\"C\": [\"meth\", \"x\"]}\n{\"C\": [\"meth\", \"x\"], \"Meta\": [\"y\"], \"type\": [\"__init__\"]}\n{\"function\": [\"__name__\"]}\n{\"function\": [\"__name__\"], \"object\": [\"__init__\"]}\n\n[case testInspectDefBasic]\n# inspect2: --show=definition tmp/foo.py:5:5\n# inspect2: --show=definition --include-kind tmp/foo.py:6:3\n# inspect2: --show=definition --include-span tmp/foo.py:7:5\n# inspect2: --show=definition tmp/foo.py:8:1:8:4\n# inspect2: --show=definition tmp/foo.py:8:6:8:8\n# inspect2: --show=definition tmp/foo.py:9:3\nimport foo\n[file foo.py]\nfrom bar import var, test, A\nfrom baz import foo\n\na: A\na.meth()\na.x\nA.B.y\ntest(var)\nfoo\n[file bar.py]\nclass A:\n    x: int\n    @classmethod\n    def meth(cls) -> None: ...\n    class B:\n        y: int\n\nvar = 42\ndef test(x: int) -> None: ...\n[file baz.py]\nfrom typing import overload, Union\n\n@overload\ndef foo(x: int) -> None: ...\n@overload\ndef foo(x: str) -> None: ...\ndef foo(x: Union[int, str]) -> None:\n    pass\n[builtins fixtures/classmethod.pyi]\n[out]\n==\ntmp/bar.py:4:0:meth\nMemberExpr -> tmp/bar.py:2:5:x\n7:1:7:5 -> tmp/bar.py:6:9:y\ntmp/bar.py:9:1:test\ntmp/bar.py:8:1:var\ntmp/baz.py:3:2:foo\n\n[case testInspectFallbackAttributes]\n# inspect2: --show=attrs --include-object-attrs tmp/foo.py:5:1\n# inspect2: --show=attrs tmp/foo.py:8:1\n# inspect2: --show=attrs --include-kind tmp/foo.py:10:1\n# inspect2: --show=attrs --include-kind --include-object-attrs tmp/foo.py:10:1\nimport foo\n[file foo.py]\nclass B: ...\nclass C(B):\n    x: int\nc: C\nc  # line 5\n\nt = 42, \"foo\"\nt  # line 8\n\nNone\n[builtins fixtures/args.pyi]\n[out]\n==\n{\"C\": [\"x\"], \"object\": [\"__eq__\", \"__init__\", \"__ne__\"]}\n{\"Iterable\": [\"__iter__\"]}\nNameExpr -> {}\nNameExpr -> {\"object\": [\"__eq__\", \"__init__\", \"__ne__\"]}\n\n[case testInspectTypeVarBoundAttrs]\n# inspect2: --show=attrs tmp/foo.py:8:13\nimport foo\n[file foo.py]\nfrom typing import TypeVar\n\nclass C:\n    x: int\n\nT = TypeVar('T', bound=C)\ndef foo(arg: T) -> T:\n    return arg\n[out]\n==\n{\"C\": [\"x\"]}\n\n[case testInspectTypeVarValuesAttrs]\n# inspect2: --show=attrs --force-reload tmp/foo.py:13:13\n# inspect2: --show=attrs --force-reload --union-attrs tmp/foo.py:13:13\n# inspect2: --show=attrs tmp/foo.py:16:5\n# inspect2: --show=attrs --union-attrs tmp/foo.py:16:5\nimport foo\n[file foo.py]\nfrom typing import TypeVar, Generic\n\nclass A:\n    x: int\n    z: int\n\nclass B:\n    y: int\n    z: int\n\nT = TypeVar('T', A, B)\ndef foo(arg: T) -> T:\n    return arg\n\nclass C(Generic[T]):\n    x: T\n[out]\n==\n{\"A\": [\"z\"], \"B\": [\"z\"]}\n{\"A\": [\"x\", \"z\"], \"B\": [\"y\", \"z\"]}\n{\"A\": [\"z\"], \"B\": [\"z\"]}\n{\"A\": [\"x\", \"z\"], \"B\": [\"y\", \"z\"]}\n\n[case testInspectTypeVarBoundDef]\n# inspect2: --show=definition tmp/foo.py:9:13\n# inspect2: --show=definition tmp/foo.py:8:9\nimport foo\n[file foo.py]\nfrom typing import TypeVar\n\nclass C:\n    x: int\n\nT = TypeVar('T', bound=C)\ndef foo(arg: T) -> T:\n    arg.x\n    return arg\n[out]\n==\ntmp/foo.py:7:9:arg\ntmp/foo.py:4:5:x\n\n[case testInspectTypeVarValuesDef]\n# inspect2: --show=definition --force-reload tmp/foo.py:13:9\n# inspect2: --show=definition --force-reload tmp/foo.py:14:13\n# inspect2: --show=definition tmp/foo.py:18:7\nimport foo\n[file foo.py]\nfrom typing import TypeVar, Generic\n\nclass A:\n    x: int\n    z: int\n\nclass B:\n    y: int\n    z: int\n\nT = TypeVar('T', A, B)\ndef foo(arg: T) -> T:\n    arg.z\n    return arg\n\nclass C(Generic[T]):\n    x: T\n    x.z\n[out]\n==\ntmp/foo.py:5:5:z, tmp/foo.py:9:5:z\ntmp/foo.py:12:9:arg\ntmp/foo.py:5:5:z, tmp/foo.py:9:5:z\n\n[case testInspectModuleAttrs]\n# inspect2: --show=attrs tmp/foo.py:2:1\nimport foo\n[file foo.py]\nfrom pack import bar\nbar\n[file pack/__init__.py]\n[file pack/bar.py]\nx: int\ndef bar() -> None: ...\nclass C: ...\n[builtins fixtures/module.pyi]\n[out]\n==\n{\"<pack.bar>\": [\"C\", \"__annotations__\", \"__doc__\", \"__file__\", \"__name__\", \"__package__\", \"__spec__\", \"bar\", \"x\"], \"ModuleType\": [\"__file__\", \"__getattr__\"]}\n\n[case testInspectModuleDef]\n# inspect2: --show=definition --include-kind tmp/foo.py:2:1\nimport foo\n[file foo.py]\nfrom pack import bar\nbar.x\n[file pack/__init__.py]\n[file pack/bar.py]\npass\nif True:\n    x: int\n[out]\n==\nNameExpr -> tmp/pack/bar.py:1:1:bar\nMemberExpr -> tmp/pack/bar.py:3:5:x\n\n[case testInspectFunctionArgDef]\n# inspect2: --show=definition --include-span tmp/foo.py:4:13\n# TODO: for now all arguments have line/column set to function definition.\nimport foo\n[file foo.py]\ndef foo(arg: int) -> int:\n    pass\n    pass\n    return arg\n\n[out]\n==\n4:12:4:14 -> tmp/foo.py:1:9:arg\n"
  },
  {
    "path": "test-data/unit/fine-grained-modules.test",
    "content": "-- Test cases for fine-grained incremental mode related to modules\n--\n-- Covers adding and deleting modules, changes to multiple modules,\n-- changes to import graph, and changes to module references.\n--\n-- The comments in fine-grained.test explain how these tests work.\n\n\n-- Add file\n-- --------\n\n\n[case testAddFile]\nimport b\n[file b.py]\n[file a.py.2]\ndef f() -> None: pass\n[file b.py.3]\nimport a\na.f(1)\n[out]\n==\n==\nb.py:2: error: Too many arguments for \"f\"\n\n[case testAddFileWithErrors]\nimport b\n[file b.py]\n[file a.py.2]\ndef f() -> str:\n    return 1\n[file b.py.3]\nimport a\na.f(1)\n[file a.py.4]\ndef f(x: int) -> None: pass\n[out]\n==\na.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n==\na.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\nb.py:2: error: Too many arguments for \"f\"\n==\n\n[case testAddFileFixesError]\nimport b\n[file b.py]\n[file b.py.2]\nfrom a import f\nf()\n[file a.py.3]\ndef f() -> None: pass\n[out]\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n\n[case testAddFileFixesAndGeneratesError1]\nimport b\n[file b.py]\n[file b.py.2]\nfrom a import f\n[file b.py.3]\nfrom a import f\nf(1)\n[file a.py.4]\ndef f() -> None: pass\n[out]\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nb.py:2: error: Too many arguments for \"f\"\n\n[case testAddFileFixesAndGeneratesError2]\nimport b\n[file b.py]\n[file b.py.2]\nfrom a import f\nf(1)\n[file c.py.3]\nx = 'whatever'\n[file a.py.4]\ndef f() -> None: pass\n[out]\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nb.py:2: error: Too many arguments for \"f\"\n\n[case testAddFileGeneratesError1]\n# flags: --ignore-missing-imports\nimport a\n[file a.py]\nfrom b import f\nf(1)\n[file b.py.2]\ndef f() -> None: pass\n[out]\n==\na.py:2: error: Too many arguments for \"f\"\n\n[case testAddFilePreservesError1]\nimport b\n[file b.py]\n[file b.py.2]\nfrom a import f\nf(1)\n[file x.py.3]\n# unrelated change\n[out]\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"a\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testAddFilePreservesError2]\nimport b\n[file b.py]\nf()\n[file a.py.2]\n[out]\nb.py:1: error: Name \"f\" is not defined\n==\nb.py:1: error: Name \"f\" is not defined\n\n[case testRemoveSubmoduleFromBuild1]\n# cmd1: mypy a.py b/__init__.py b/c.py\n# cmd2: mypy a.py b/__init__.py\n# flags: --follow-imports=skip --ignore-missing-imports\n[file a.py]\nfrom b import c\nx=1\n[file a.py.2]\nfrom b import c\nx=2\n[file a.py.3]\nfrom b import c\nx=3\n[file b/__init__.py]\n[file b/c.py]\n[out]\n==\n==\n\n[case testImportLineNumber1]\nimport b\n[file b.py]\n[file b.py.2]\nx = 1\nimport a\n[out]\n==\nb.py:2: error: Cannot find implementation or library stub for module named \"a\"\nb.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testImportLineNumber2]\nimport b\n[file b.py]\n[file b.py.2]\nx = 1\nimport a\nfrom c import f\n[file x.py.3]\n[out]\n==\nb.py:2: error: Cannot find implementation or library stub for module named \"a\"\nb.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nb.py:3: error: Cannot find implementation or library stub for module named \"c\"\n==\nb.py:2: error: Cannot find implementation or library stub for module named \"a\"\nb.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nb.py:3: error: Cannot find implementation or library stub for module named \"c\"\n\n[case testAddPackage1]\nimport p.a\np.a.f(1)\n[file p/__init__.py.2]\n[file p/a.py.2]\ndef f(x: str) -> None: pass\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddPackage2]\nimport p\np.f(1)\n[file p/__init__.py.2]\nfrom p.a import f\n[file p/a.py.2]\ndef f(x: str) -> None: pass\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddPackage3]\nimport p.a\np.a.f(1)\n[file p/__init__.py.2]\n[file p/a.py.3]\ndef f(x: str) -> None: pass\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:1: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/module.pyi]\n\n[case testAddPackage4]\nimport p.a\np.a.f(1)\n[file p/a.py.2]\ndef f(x: str) -> None: pass\n[file p/__init__.py.3]\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:1: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddNonPackageSubdir]\n# cmd: mypy x.py\n# cmd2: mypy x.py foo/a.py foo/b.py\n[file x.py]\n[file foo/a.py.2]\nimport b\nb.foo(5)\n[file foo/b.py.2]\ndef foo(x: str) -> None: pass\n[out]\n==\nfoo/a.py:2: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddPackage5]\n# cmd: mypy main p/a.py\n# cmd2: mypy main p/a.py\n# cmd3: mypy main p/a.py p/__init__.py\nimport p.a\np.a.f(1)\n[file p/a.py]\n[file p/a.py.2]\ndef f(x: str) -> None: pass\n[file p/__init__.py.3]\n[out]\nmain:4: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:4: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:4: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:4: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:5: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddPackage6]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy x.py\n# cmd2: mypy x.py p/a.py\n[file x.py]\nimport p.a\np.a.f(1)\n[file p/a.py.2]\ndef f(x: str) -> None: pass\n[file p/__init__.py.2]\n[out]\n==\n-- It is a bug (#4797) that this isn't an error, but not a fine-grained specific one\n\n[case testAddPackage7]\n# flags: --follow-imports=skip\n# cmd: mypy x.py\n# cmd2: mypy x.py p/a.py\n[file x.py]\nfrom p.a import f\nf(1)\n[file p/a.py.2]\ndef f(x: str) -> None: pass\n[file p/__init__.py.2]\n[out]\nx.py:1: error: Cannot find implementation or library stub for module named \"p.a\"\nx.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nx.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n\n[case testAddPackage8]\n# cmd: mypy x.py p/a.py\n# cmd2: mypy x.py p/a.py p/__init__.py\n# cmd3: mypy x.py p/a.py p/__init__.py\n[file x.py]\n[file p/a.py]\n1+'hi'\n[file p/__init__.py.2]\n[file p/a.py.3]\n1+3\n[out]\np/a.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n==\np/a.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n==\n\n\n-- Delete file\n-- -----------\n\n\n[case testDeleteBasic]\nimport a\n[file a.py]\nimport b\n[file b.py]\ndef f() -> None: pass\n[file a.py.2]\n[delete b.py.3]\n[out]\n==\n==\n\n[case testDeleteDepOfDunderInit1]\n[file p/__init__.py]\nfrom .foo import Foo\n[file p/foo.py]\nclass Foo: pass\n[file p/__init__.py.2]\n[delete p/foo.py.2]\n[out]\n==\n\n[case testDeleteDepOfDunderInit2]\n[file p/__init__.py]\nfrom p.foo import Foo\n[file p/foo.py]\nclass Foo: pass\n[file p/__init__.py.2]\n[delete p/foo.py.2]\n[out]\n==\n\n[case testDeletionTriggersImportFrom]\nimport a\n[file a.py]\nfrom b import f\n\ndef g() -> None:\n    f()\n[file b.py]\ndef f() -> None: pass\n[delete b.py.2]\n[file b.py.3]\ndef f(x: int) -> None: pass\n[out]\n==\na.py:1: error: Cannot find implementation or library stub for module named \"b\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\na.py:4: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testDeletionTriggersImport]\nimport a\n[file a.py]\ndef f() -> None: pass\n[delete a.py.2]\n[file a.py.3]\ndef f() -> None: pass\n[out]\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n\n[case testDeletionOfSubmoduleTriggersImportFrom1-only_when_nocache]\n-- Different cache/no-cache tests because:\n-- missing module error message mismatch\nfrom p import q\n[file p/__init__.py]\n[file p/q.py]\n[delete p/q.py.2]\n[file p/q.py.3]\n[out]\n==\nmain:1: error: Module \"p\" has no attribute \"q\"\n-- TODO: The following messages are different compared to non-incremental mode\nmain:1: error: Cannot find implementation or library stub for module named \"p.q\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n\n-- TODO: Fix this bug. It is a real bug that was been papered over\n-- by the test harness.\n[case testDeletionOfSubmoduleTriggersImportFrom1_2-only_when_cache-skip]\n-- Different cache/no-cache tests because:\n-- missing module error message mismatch\nfrom p import q\n[file p/__init__.py]\n[file p/q.py]\n[delete p/q.py.2]\n[file p/q.py.3]\n[out]\n==\nmain:1: error: Cannot find implementation or library stub for module named \"p.q\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\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==\nmain:1: error: Cannot find implementation or library stub for module named \"p.q\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testDeletionOfSubmoduleTriggersImport]\nimport p.q\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==\nmain:1: error: Cannot find implementation or library stub for module named \"p.q\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n\n[case testDeleteSubpackageWithNontrivialParent1]\n[file p/__init__.py]\ndef g() -> None:\n    pass\n[file p/b.py.2]\ndef foo() -> None: pass\nfoo()\n[delete p/b.py.3]\n[out]\n==\n==\n\n[case testDeleteModuleWithError]\nimport a\n[file a.py]\ndef f() -> int:\n    return 1\n[file a.py.2]\ndef f() -> str:\n    return 1\n[delete a.py.3]\ndef f() -> str:\n    return 1\n[out]\n==\na.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testDeleteModuleWithErrorInsidePackage]\nimport a.b\n[file a/__init__.py]\n[file a/b.py]\ndef f() -> int:\n    return ''\n[delete a/b.py.2]\ndef f() -> str:\n    return 1\n[out]\na/b.py:2: error: Incompatible return value type (got \"str\", expected \"int\")\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a.b\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testModifyTwoFilesNoError1]\nimport a\n[file a.py]\nimport b\nb.f()\n[file b.py]\ndef f() -> None: pass\n[file a.py.2]\nimport b\nb.f(1)\n[file b.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\n\n[case testDeleteSubpackageInit1]\n# cmd: mypy q/r/s.py\n# flags: --follow-imports=skip --ignore-missing-imports\n[file q/__init__.py]\n[file q/r/__init__.py]\n[file q/r/s.py]\n[delete q/__init__.py.2]\n[out]\n==\n\n[case testAddSubpackageInit2]\n# cmd: mypy q/r/s.py\n# flags: --follow-imports=skip --ignore-missing-imports\n[file q/r/__init__.py]\n[file q/r/s.py]\n1\n[file q/r/s.py.2]\n2\n[file q/__init__.py.2]\n[out]\n==\n\n[case testModifyTwoFilesNoError2]\nimport a\n[file a.py]\nfrom b import g\ndef f() -> None: pass\n[file b.py]\nimport a\ndef g() -> None: pass\na.f()\n[file a.py.2]\nfrom b import g\ndef f(x: int) -> None: pass\n[file b.py.2]\nimport a\ndef g() -> None: pass\na.f(1)\n[out]\n==\n\n[case testModifyTwoFilesErrorsElsewhere]\nimport a\nimport b\na.f()\nb.g(1)\n[file a.py]\ndef f() -> None: pass\n[file b.py]\ndef g(x: int) -> None: pass\n[file a.py.2]\ndef f(x: int) -> None: pass\n[file b.py.2]\ndef g() -> None: pass\n[out]\n==\nmain:3: error: Missing positional argument \"x\" in call to \"f\"\nmain:4: error: Too many arguments for \"g\"\n\n[case testModifyTwoFilesErrorsInBoth]\nimport a\n[file a.py]\nimport b\ndef f() -> None: pass\nb.g(1)\n[file b.py]\nimport a\ndef g(x: int) -> None: pass\na.f()\n[file a.py.2]\nimport b\ndef f(x: int) -> None: pass\nb.g(1)\n[file b.py.2]\nimport a\ndef g() -> None: pass\na.f()\n[out]\n==\nb.py:3: error: Missing positional argument \"x\" in call to \"f\"\na.py:3: error: Too many arguments for \"g\"\n\n[case testModifyTwoFilesFixErrorsInBoth]\nimport a\n[file a.py]\nimport b\ndef f(x: int) -> None: pass\nb.g(1)\n[file b.py]\nimport a\ndef g() -> None: pass\na.f()\n[file a.py.2]\nimport b\ndef f() -> None: pass\nb.g(1)\n[file b.py.2]\nimport a\ndef g(x: int) -> None: pass\na.f()\n[out]\nb.py:3: error: Missing positional argument \"x\" in call to \"f\"\na.py:3: error: Too many arguments for \"g\"\n==\n\n[case testAddTwoFilesNoError]\nimport a\n[file a.py]\nimport b\nimport c\nb.f()\nc.g()\n[file b.py.2]\nimport c\ndef f() -> None: pass\nc.g()\n[file c.py.2]\nimport b\ndef g() -> None: pass\nb.f()\n[out]\na.py:1: error: Cannot find implementation or library stub for module named \"b\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\na.py:2: error: Cannot find implementation or library stub for module named \"c\"\n==\n\n[case testAddTwoFilesErrorsInBoth]\nimport a\n[file a.py]\nimport b\nimport c\nb.f()\nc.g()\n[file b.py.2]\nimport c\ndef f() -> None: pass\nc.g(1)\n[file c.py.2]\nimport b\ndef g() -> None: pass\nb.f(1)\n[out]\na.py:1: error: Cannot find implementation or library stub for module named \"b\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\na.py:2: error: Cannot find implementation or library stub for module named \"c\"\n==\nc.py:3: error: Too many arguments for \"f\"\nb.py:3: error: Too many arguments for \"g\"\n\n[case testAddTwoFilesErrorsElsewhere]\nimport a\nimport b\na.f(1)\nb.g(1)\n[file a.py.2]\ndef f() -> None: pass\n[file b.py.2]\ndef g() -> None: pass\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"b\"\n==\nmain:3: error: Too many arguments for \"f\"\nmain:4: error: Too many arguments for \"g\"\n\n[case testDeleteTwoFilesErrorsElsewhere]\nimport a\nimport b\na.f()\nb.g()\n[file a.py]\ndef f() -> None: pass\n[file b.py]\ndef g() -> None: pass\n[delete a.py.2]\n[delete b.py.2]\n[out]\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"b\"\n\n[case testDeleteTwoFilesNoErrors]\nimport a\n[file a.py]\nimport b\nimport c\nb.f()\nc.g()\n[file b.py]\ndef f() -> None: pass\n[file c.py]\ndef g() -> None: pass\n[file a.py.2]\n[delete b.py.3]\n[delete c.py.3]\n[out]\n==\n==\n\n[case testDeleteTwoFilesFixErrors]\nimport a\nimport b\na.f()\nb.g()\n[file a.py]\nimport b\ndef f() -> None: pass\nb.g(1)\n[file b.py]\nimport a\ndef g() -> None: pass\na.f(1)\n[delete a.py.2]\n[delete b.py.2]\n[out]\nb.py:3: error: Too many arguments for \"f\"\na.py:3: error: Too many arguments for \"g\"\n==\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"b\"\n\n[case testAddFileWhichImportsLibModule]\nimport a\na.x = 0\n[file a.py.2]\nimport sys\nx = sys.platform\n[builtins fixtures/tuple.pyi]\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:2: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAddFileWhichImportsLibModuleWithErrors]\n# flags: --no-silence-site-packages\nimport a\na.x = 0\n[file a.py.2]\nimport broken\nx = broken.x\nz\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"a\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\na.py:3: error: Name \"z\" is not defined\n<ROOT>/test-data/unit/lib-stub/broken.pyi:2: error: Name \"y\" is not defined\n\n[case testRenameModule]\nimport a\n[file a.py]\nimport b\nb.f()\n[file b.py]\ndef f() -> None: pass\n[file a.py.2]\nimport c\nc.f()\n[file c.py.2]\ndef f() -> None: pass\n[file a.py.3]\nimport c\nc.f(1)\n[out]\n==\n==\na.py:2: error: Too many arguments for \"f\"\n\n[case testDeleteFileWSuperClass]\n# flags: --ignore-missing-imports\n[file a.py]\nfrom c import Bar\nfrom b import Foo\nz = (1, Foo())\n[file b.py]\nfrom e import Quux\nfrom d import Baz\nclass Foo(Baz, Quux):\n    pass\n\n[file e.py]\nfrom c import Bar\nclass Quux(Bar):\n    pass\n[file c.py]\nclass Bar:\n    pass\n[file d.py]\nclass Baz:\n    pass\n[delete c.py.2]\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testDeleteFileWithinPackage]\n\nimport a\n[file a.py]\nimport m.x\nm.x.g(1)\n[file m/__init__.py]\n[file m/x.py]\ndef g() -> None: pass\n[delete m/x.py.2]\n[builtins fixtures/module.pyi]\n[out]\na.py:2: error: Too many arguments for \"g\"\n==\na.py:1: error: Cannot find implementation or library stub for module named \"m.x\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\na.py:2: error: Module has no attribute \"x\"\n\n[case testDeletePackage1]\nimport p.a\np.a.f(1)\n[file p/__init__.py]\n[file p/a.py]\ndef f(x: str) -> None: pass\n[delete p.2]\n[out]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n==\nmain:1: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\n\n[case testDeletePackage2]\nimport p\np.f(1)\n[file p/__init__.py]\nfrom p.a import f\n[file p/a.py]\ndef f(x: str) -> None: pass\n[delete p.2]\n[out]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n==\nmain:1: error: Cannot find implementation or library stub for module named \"p\"\nmain:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testDeletePackage3]\n\nimport p.a\np.a.f(1)\n[file p/__init__.py]\n[file p/a.py]\ndef f(x: str) -> None: pass\n[delete p/a.py.2]\n[delete p.3]\n[builtins fixtures/module.pyi]\n[out]\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n==\nmain:2: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:3: error: Module has no attribute \"a\"\n==\nmain:2: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"p\"\n\n[case testDeletePackage4]\n# flags: --no-namespace-packages\nimport p.a\np.a.f(1)\n[file p/a.py]\ndef f(x: str) -> None: pass\n[file p/__init__.py]\n[delete p/__init__.py.2]\n[delete p.3]\n[out]\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n==\nmain:2: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:2: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"p\"\n\n[case testDeletePackage5]\n# flags: --no-namespace-packages\n# cmd1: mypy -m main -m p.a -m p.__init__\n# cmd2: mypy -m main -m p.a\n# cmd3: mypy -m main\n\nimport p.a\np.a.f(1)\n[file p/a.py]\ndef f(x: str) -> None: pass\n[file p/__init__.py]\n[delete p/__init__.py.2]\n[delete p.3]\n[out]\nmain:7: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n==\nmain:6: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:6: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:6: error: Cannot find implementation or library stub for module named \"p\"\n==\nmain:6: error: Cannot find implementation or library stub for module named \"p.a\"\nmain:6: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:6: error: Cannot find implementation or library stub for module named \"p\"\n\n\n[case testDeletePackage6]\n# flags: --no-namespace-packages\n# cmd1: mypy -m p.a -m p.b -m p.__init__\n# cmd2: mypy -m p.a -m p.b\n# cmd3: mypy -m p.a -m p.b\n[file p/a.py]\ndef f(x: str) -> None: pass\n[file p/b.py]\nfrom p.a import f\nf(12)\n[file p/__init__.py]\n[delete p/__init__.py.2]\n[file p/b.py.3]\nfrom a import f\nf(12)\n[out]\np/b.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n==\np/b.py:1: error: Cannot find implementation or library stub for module named \"p.a\"\np/b.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\np/b.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n\n-- TODO:\n-- - add one file which imports another new file, blocking error in new file\n-- - arbitrary blocking errors\n-- - order of processing makes a difference\n-- - mix of modify, add and delete in one iteration\n\n\n-- Controlling imports using command line options\n-- ----------------------------------------------\n\n\n[case testIgnoreMissingImports]\n# flags: --ignore-missing-imports\nimport a\n[file a.py]\nimport b\nimport c\n[file c.py]\n[delete c.py.2]\n[file b.py.3]\nimport d\n1 + ''\n[out]\n==\n==\nb.py:2: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testSkipImports]\n# cmd: mypy main a.py\n# flags: --follow-imports=skip --ignore-missing-imports\nimport a\n[file a.py]\nimport b\n[file b.py]\n1 + ''\nclass A: pass\n[file a.py.2]\nimport b\nreveal_type(b)\nreveal_type(b.A)\n[file a.py.3]\nimport b\nreveal_type(b)\nreveal_type(b.A)\n[file b.py.3]\n1 + ''\nclass A: pass\n[out]\n==\na.py:2: note: Revealed type is \"Any\"\na.py:3: note: Revealed type is \"Any\"\n==\na.py:2: note: Revealed type is \"Any\"\na.py:3: note: Revealed type is \"Any\"\n\n[case testSkipImportsWithinPackage]\n# cmd: mypy a/b.py\n# flags: --follow-imports=skip --ignore-missing-imports\n[file a/__init__.py]\n1 + ''\n[file a/b.py]\nimport a.c\n[file a/b.py.2]\nimport a.c\nimport x\nreveal_type(a.c)\n[file a/b.py.3]\nimport a.c\nimport x\n1 + ''\n[out]\n==\na/b.py:3: note: Revealed type is \"Any\"\n==\na/b.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testDeleteModuleWithinPackageInitIgnored-only_when_nocache]\n-- Disabled in cache mode because incorrect behavior:\n-- Having deleted files specified on command line seems dodgy, though.\n# cmd: mypy x.py a/b.py\n# flags: --follow-imports=skip --ignore-missing-imports\n[file x.py]\nimport a.b\n[file a/__init__.py]\n[file a/b.py]\nx = 1\n[delete a/b.py.2]\n[out]\n==\n\n[case testAddImport]\nimport what.b\n[file aaa/__init__.py]\n[file aaa/z.py]\ndef foo(x: int) -> None:\n    pass\n[file aaa/z.py.2]\nimport config\ndef foo() -> None:\n    pass\n[file what/__init__.py]\n[file what/b.py]\nimport config\nimport aaa.z\ndef main() -> None:\n    aaa.z.foo(5)\n[file what/b.py.2]\nimport aaa.z\ndef main() -> None:\n    aaa.z.foo()\n[file config.py]\n[out]\n==\n\n[case testAddImport2]\nimport what.b\n[file aaa/__init__.py]\n[file aaa/z.py]\ndef foo(x: int) -> None:\n    pass\n[file aaa/z.py.2]\ndef foo() -> None:\n    pass\n[file what/__init__.py]\n[file what/b.py]\nimport aaa.z\ndef main() -> None:\n    aaa.z.foo(5)\n[file what/b.py.2]\nimport config\nimport aaa.z\ndef main() -> None:\n    aaa.z.foo()\n[file config.py]\n[out]\n==\n\n\n-- Misc\n-- ----\n\n\n[case testChangeModuleToVariable]\nfrom a import m\nm.x\n[file a.py]\nfrom b import m\n[file b.py]\nimport m\n[file b.py.2]\nm = ''\n[file m.py]\nx = 1\n[file m2.py]\n[out]\n==\nmain:2: error: \"str\" has no attribute \"x\"\n\n[case testChangeVariableToModule]\nfrom a import m\ny: str = m\n[file a.py]\nfrom b import m\n[file b.py]\nm = ''\n[file b.py.2]\nimport m\n[file m.py]\nx = 1\n[file m2.py]\n[builtins fixtures/module.pyi]\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type Module, variable has type \"str\")\n\n[case testRefreshImportOfIgnoredModule1]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy c.py a/__init__.py b.py\n[file c.py]\nfrom a import a2\nimport b\nb.x\n[file a/__init__.py]\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[file b.py.3]\nx = 0\n[file a/a2.py]\n[out]\n==\n==\n\n[case testRefreshImportOfIgnoredModule2]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy c.py a/__init__.py b.py\n[file c.py]\nfrom a import a2\nimport b\nb.x\n[file a/__init__.py]\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[file b.py.3]\nx = 0\n[file a/a2/__init__.py]\n[out]\n==\n==\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[out]\n==\n==\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==\n==\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[file b.py.3]\nclass Foo:\n    def foo(self, x: int) -> None: pass\nx = Foo()\n[out]\n==\n==\nmain:2: error: Missing positional argument \"x\" in call to \"foo\" of \"Foo\"\n\n-- This series of tests is designed to test adding a new module that\n-- does not appear in the cache, for cache mode. They are run in\n-- cache mode only because stale and rechecked differ heavily between\n-- the modes.\n[case testAddModuleAfterCache1-only_when_cache]\n# cmd: mypy main a.py\n# cmd2: mypy main a.py b.py\n# cmd3: mypy main a.py b.py\nimport a\n[file a.py]\npass\n[file a.py.2]\nimport b\nb.foo(0)\n[file b.py.2]\ndef foo() -> None: pass\n\n[stale a, b]\n[rechecked a, b]\n\n[file b.py.3]\ndef foo(x: int) -> None: pass\n\n[stale2 b]\n[rechecked2 b]\n\n[out]\n==\na.py:2: error: Too many arguments for \"foo\"\n==\n\n[case testAddModuleAfterCache2-only_when_cache]\n# cmd: mypy main a.py\n# cmd2: mypy main a.py b.py\n# cmd3: mypy main a.py b.py\n# flags: --ignore-missing-imports --follow-imports=skip\nimport a\n[file a.py]\nimport b\nb.foo(0)\n[file b.py.2]\ndef foo() -> None: pass\n\n[stale b]\n[rechecked a, b]\n\n[file b.py.3]\ndef foo(x: int) -> None: pass\n\n[stale2 b]\n\n[out]\n==\na.py:2: error: Too many arguments for \"foo\"\n==\n\n[case testAddModuleAfterCache3-only_when_cache]\n# cmd: mypy main a.py\n# cmd2: mypy main a.py b.py c.py d.py e.py f.py g.py h.py i.py j.py\n# cmd3: mypy main a.py b.py c.py d.py e.py f.py g.py h.py i.py j.py\n# flags: --ignore-missing-imports --follow-imports=skip\nimport a\n[file a.py]\nimport b, c, d, e, f, g, h, i, j\nb.foo(10)\n[file b.py.2]\ndef foo() -> None: pass\n[file c.py.2]\n[file d.py.2]\n[file e.py.2]\n[file f.py.2]\n[file g.py.2]\n[file h.py.2]\n[file i.py.2]\n[file j.py.2]\n\n-- No files should be stale or reprocessed in the first step since the large number\n-- of missing files will force build to give up on cache loading.\n[stale]\n\n[file b.py.3]\ndef foo(x: int) -> None: pass\n[stale2 b]\n\n[out]\n==\na.py:2: error: Too many arguments for \"foo\"\n==\n\n\n[case testAddModuleAfterCache4-only_when_cache]\n# cmd: mypy main a.py\n# cmd2: mypy main a.py b.py\n# cmd3: mypy main a.py b.py\n# flags: --ignore-missing-imports --follow-imports=skip\nimport a\nimport b\n[file a.py]\ndef foo() -> None: pass\n[file b.py.2]\nimport a\na.foo(10)\n[file a.py.3]\ndef foo(x: int) -> None: pass\n[out]\n==\nb.py:2: error: Too many arguments for \"foo\"\n==\n\n[case testAddModuleAfterCache5-only_when_cache]\n# cmd: mypy main a.py\n# cmd2: mypy main a.py b.py\n# cmd3: mypy main a.py b.py\n# flags: --ignore-missing-imports --follow-imports=skip\nimport a\nimport b\n[file a.py]\ndef foo(x: int) -> None: pass\n[file a.py.2]\ndef foo() -> None: pass\n[file b.py.2]\nimport a\na.foo(10)\n\n[stale a, b]\n\n[file a.py.3]\ndef foo(x: int) -> None: pass\n\n[stale2 a]\n\n[out]\n==\nb.py:2: error: Too many arguments for \"foo\"\n==\n\n[case testAddModuleAfterCache6-only_when_cache]\n# cmd: mypy main a.py\n# cmd2: mypy main a.py b.py\n# cmd3: mypy main a.py b.py\n# flags: --ignore-missing-imports --follow-imports=skip\nimport a\n[file a.py]\nimport b\nb.foo()\n\n[file a.py.2]\nimport b\nb.foo(0)\n[file b.py.2]\ndef foo() -> None: pass\n\n[stale a, b]\n\n[file b.py.3]\ndef foo(x: int) -> None: pass\n\n[stale2 b]\n\n[out]\n==\na.py:2: error: Too many arguments for \"foo\"\n==\n\n[case testRenameAndDeleteModuleAfterCache-only_when_cache]\nimport a\n[file a.py]\nfrom b1 import f\nf()\n[file b1.py]\ndef f() -> None: pass\n[file b2.py.2]\ndef f() -> None: pass\n[delete b1.py.2]\n[file a.py.2]\nfrom b2 import f\nf()\n\n-- in cache mode, there is no way to know about b1 yet\n[stale a, b2]\n\n[out]\n==\n\n[case testDeleteModuleAfterCache-only_when_cache]\nimport a\n[file a.py]\nfrom b import f\nf()\n[file b.py]\ndef f() -> None: pass\n[delete b.py.2]\n\n-- in cache mode, there is no way to know about b yet,\n-- but a should get flagged as changed by the initial cache\n-- check, since one of its dependencies is missing.\n[stale a]\n\n[out]\n==\na.py:1: error: Cannot find implementation or library stub for module named \"b\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n\n[case testRefreshImportIfMypyElse1]\nimport a\n[file a.py]\nfrom b import foo\n\nMYPY = False\nif MYPY:\n    x = 0\nelse:\n    from fictional import x\n\nx = 1\n[file b/__init__.py]\n[file b/foo.py]\n[file b/__init__.py.2]\n# Dummy change\n[builtins fixtures/primitives.pyi]\n[out]\n==\n\n[case testImportStarPropagateChange1]\nfrom b import f\nf()\n[file b.py]\nfrom c import *\n[file c.py]\ndef f() -> None: pass\n[file c.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportStarPropagateChange2]\nfrom b import *\nf()\n[file b.py]\ndef f() -> None: pass\n[file b.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportStarAddMissingDependency1]\nfrom b import f\nf()\n[file b.py]\nfrom c import *\n[file c.py]\n[file c.py.2]\ndef f(x: int) -> None: pass\n[out]\nmain:1: error: Module \"b\" has no attribute \"f\"\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportStarAddMissingDependency2]\nfrom b import *\nf()\n[file b.py]\n[file b.py.2]\ndef f(x: int) -> None: pass\n[out]\nmain:2: error: Name \"f\" is not defined\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportStarAddMissingDependencyWithinClass]\nclass A:\n    from b import *\n    f()\n    x: C\n[file b.py]\n[file b.py.2]\ndef f(x: int) -> None: pass\n[file b.py.3]\ndef f(x: int) -> None: pass\nclass C: pass\n[file b.py.4]\ndef f() -> None: pass\nclass C: pass\n[out]\nmain:3: error: Name \"f\" is not defined\nmain:4: error: Name \"C\" is not defined\n==\nmain:2: error: Unsupported class scoped import\nmain:4: error: Name \"C\" is not defined\n==\nmain:2: error: Unsupported class scoped import\n==\nmain:2: error: Unsupported class scoped import\n\n[case testImportStarAddMissingDependencyInsidePackage1]\nfrom p.b import f\nf()\n[file p/__init__.py]\n[file p/b.py]\nfrom p.c import *\n[file p/c.py]\n[file p/c.py.2]\ndef f(x: int) -> None: pass\n[out]\nmain:1: error: Module \"p.b\" has no attribute \"f\"\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportStarAddMissingDependencyInsidePackage2]\nimport p.a\n[file p/__init__.py]\n[file p/a.py]\nfrom p.b import *\nf()\n[file p/b.py]\n[file p/b.py.2]\ndef f(x: int) -> None: pass\n[out]\np/a.py:2: error: Name \"f\" is not defined\n==\np/a.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportStarRemoveDependency1]\nfrom b import f\nf()\n[file b.py]\nfrom c import *\n[file c.py]\ndef f() -> None: pass\n[file c.py.2]\n[out]\n==\nmain:1: error: Module \"b\" has no attribute \"f\"\n\n[case testImportStarRemoveDependency2]\nfrom b import *\nf()\n[file b.py]\ndef f() -> None: pass\n[file b.py.2]\n[out]\n==\nmain:2: error: Name \"f\" is not defined\n\n[case testImportStarWithinFunction]\ndef f() -> None:\n    from m import *\n    f()\n[file m.py]\n[file m.py.2]\ndef f(x: int) -> None: pass\n[file m.py.3]\ndef f() -> None: pass\n[out]\n==\nmain:3: error: Missing positional argument \"x\" in call to \"f\"\n==\n\n[case testImportStarMutuallyRecursive-skip]\n# FIXME: busted with new analyzer?\nimport a\n[file a.py]\nfrom b import *\n[file b.py]\nfrom a import *\n[file b.py.2]\nfrom a import *\nx = 0\n[file b.py.3]\nfrom a import *\nx = ''\n[out]\n==\n==\n\n[case testImportStarSomethingMoved]\nimport p\n[file p.py]\nfrom r2 import *\n[file r2.py]\nclass A: pass\n\n[file p.py.2]\nfrom r1 import *\nfrom r2 import *\n[file r2.py.2]\n\n[file r1.py.2]\nclass A: pass\n\n[out]\n==\n\n[case testImportStarOverlap]\nfrom b import *\nfrom c import *  # type: ignore\n[file b.py]\nfrom d import T\n[file c.py]\nfrom d import T\n[file c.py.2]\nfrom d import T\nz = 10\n[file d.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[out]\n==\n\n[case testImportStarOverlap2]\nfrom b import *\nimport typing\ndef foo(x: typing.List[int]) -> int:\n    return x[0]\n[file b.py]\nimport typing\nz = 10\n[file b.py.2]\nimport typing\nz = '10'\n[builtins fixtures/list.pyi]\n[out]\n==\n\n\n[case testImportStarOverlap3]\nfrom b import *\nfrom c import typing\ndef foo(x: typing.List[int]) -> int:\n    return x[0]\n[file b.py]\nimport typing\nz = 10\n[file b.py.2]\nimport typing\nz = '10'\n[file c.py]\nimport typing\nz = 10\n[builtins fixtures/list.pyi]\n[out]\n==\n\n\n[case testImportPartialAssign]\nimport a\n[file a.py]\nfrom c import *\nfrom b import A, x\n[file b.py]\nA = 10\nx = 1\n[file b.py.2]\nclass A: pass\nx = 1\n[file c.py]\nx = 10\n[out]\n==\n\n[case testDeleteFileWithErrors]\n# cmd: mypy main a.py\n# cmd2: mypy main\n# flags: --follow-imports=skip --ignore-missing-imports\nimport a\n[file a.py]\ndef f() -> None:\n    1()\n''()\n[file b.py.2]\n# unrelated change\n[out]\na.py:2: error: \"int\" not callable\na.py:3: error: \"str\" not callable\n==\n\n[case testAddAndUseClass1]\n[file a.py]\n[file a.py.2]\nfrom b import Foo\ndef bar(f: Foo) -> None:\n    f.foo(12)\n[file b.py.2]\nclass Foo:\n    def foo(self, s: str) -> None: pass\n[out]\n==\na.py:3: error: Argument 1 to \"foo\" of \"Foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddAndUseClass2]\n[file a.py]\n[file a.py.3]\nfrom b import Foo\ndef bar(f: Foo) -> None:\n    f.foo(12)\n[file b.py.2]\nclass Foo:\n    def foo(self, s: str) -> None: pass\n[out]\n==\n==\na.py:3: error: Argument 1 to \"foo\" of \"Foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddAndUseClass3]\n# flags: --ignore-missing-imports\n[file a.py]\n[file a.py.2]\nfrom b import Foo\ndef bar(f: Foo) -> None:\n    f.foo(12)\n[file b.py.3]\nclass Foo:\n    def foo(self, s: str) -> None: pass\n[out]\n==\n==\na.py:3: error: Argument 1 to \"foo\" of \"Foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddAndUseClass4]\n[file a.py]\n[file a.py.2]\nfrom b import *\ndef bar(f: Foo) -> None:\n    f.foo(12)\n[file b.py.2]\nclass Foo:\n    def foo(self, s: str) -> None: pass\n[out]\n==\na.py:3: error: Argument 1 to \"foo\" of \"Foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddAndUseClass4_2]\n[file a.py]\n[file a.py.2]\nfrom p.b import *\ndef bar(f: Foo) -> None:\n    f.foo(12)\n[file p/__init__.py]\n[file p/b.py.2]\nclass Foo:\n    def foo(self, s: str) -> None: pass\n[out]\n==\na.py:3: error: Argument 1 to \"foo\" of \"Foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddAndUseClass5]\n[file a.py]\n[file a.py.2]\nfrom b import *\ndef bar(f: Foo) -> None:\n    f.foo(12)\n[file b.py.2]\nclass Foo:\n    def foo(self, s: str) -> None: pass\n[out]\n==\na.py:3: error: Argument 1 to \"foo\" of \"Foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testSkipButDontIgnore1]\n# cmd: mypy a.py c.py\n# flags: --follow-imports=skip\n[file a.py]\nimport b\nfrom c import x\n[file b.py]\n1+'lol'\n[file c.py]\nx = 1\n[file c.py.2]\nx = '2'\n[file b.py.3]\n[out]\n==\n==\n\n[case testSkipButDontIgnore2]\n# cmd: mypy a.py c.py\n# flags: --follow-imports=skip\n[file a.py]\nfrom c import x\nimport b\n[file b.py]\n[file c.py]\nx = 1\n[file b.py.2]\n1+'x'\n[file c.py.2]\nx = '2'\n[file c.py.3]\nx = 2\n[delete b.py.3]\n[out]\n==\n==\na.py:2: error: Cannot find implementation or library stub for module named \"b\"\na.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testErrorButDontIgnore1]\n# cmd: mypy a.py c.py\n# flags: --follow-imports=error\n[file a.py]\nfrom c import x\nimport b\n[file b.py]\n[file c.py]\nx = 1\n[file c.py.2]\nx = '2'\n[out]\na.py:2: error: Import of \"b\" ignored\na.py:2: note: (Using --follow-imports=error, module not passed on command line)\n==\na.py:2: error: Import of \"b\" ignored\na.py:2: note: (Using --follow-imports=error, module not passed on command line)\n\n[case testErrorButDontIgnore2]\n# cmd1: mypy a.py c.py b.py\n# cmd2: mypy a.py c.py\n# flags: --follow-imports=error\n[file a.py]\nfrom c import x\nimport b\n[file b.py]\n[file c.py]\nx = 1\n[file c.py.2]\nx = '2'\n[out]\n==\na.py:2: error: Import of \"b\" ignored\na.py:2: note: (Using --follow-imports=error, module not passed on command line)\n\n-- TODO: This test fails because p.b does not depend on p (#4847)\n[case testErrorButDontIgnore3-skip]\n# cmd1: mypy a.py c.py p/b.py p/__init__.py\n# cmd2: mypy a.py c.py p/b.py\n# flags: --follow-imports=error\n[file a.py]\nfrom c import x\nfrom p.b import y\n[file p/b.py]\ny = 12\n[file p/__init__.py]\n[file c.py]\nx = 1\n[file c.py.2]\nx = '2'\n[out]\n==\np/b.py: error: Ancestor package \"p\" ignored\np/b.py: note: (Using --follow-imports=error, submodule passed on command line)\n\n[case testErrorButDontIgnore4]\n# cmd: mypy a.py z.py p/b.py p/__init__.py\n# cmd2: mypy a.py p/b.py\n# flags: --follow-imports=error\n[file a.py]\nfrom p.b import y\n[file p/b.py]\nfrom z import x\ny = 12\n[file p/__init__.py]\n[file z.py]\nx = 1\n[delete z.py.2]\n[out]\n==\np/b.py: error: Ancestor package \"p\" ignored\np/b.py: note: (Using --follow-imports=error, submodule passed on command line)\np/b.py:1: error: Cannot find implementation or library stub for module named \"z\"\np/b.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testTurnPackageToModule]\n[file a.py]\n[file b.py]\nimport p\nx = p.f()\n[file p/__init__.py]\ndef f() -> int: pass\n[delete p/__init__.py.2]\n[file p.py.2]\ndef f() -> str: pass\n[file a.py.3]\nimport b\nreveal_type(b.x)\n[out]\n==\n==\na.py:2: note: Revealed type is \"builtins.str\"\n\n[case testModuleToPackage]\n[file a.py]\n[file b.py]\nimport p\nx = p.f()\n[file p.py]\ndef f() -> str: pass\n[delete p.py.2]\n[file p/__init__.py.2]\ndef f() -> int: pass\n[file a.py.3]\nimport b\nreveal_type(b.x)\n[out]\n==\n==\na.py:2: note: Revealed type is \"builtins.int\"\n\n[case testQualifiedSubpackage1]\n[file c/__init__.py]\n[file c/a.py]\nfrom lurr import x\nfrom c.d import f\n\n[file c/d.py]\ndef f() -> None: pass\ndef g(x: int) -> None: pass\n[file lurr.py]\nx = 10\n[file lurr.py.2]\nx = '10'\n[out]\n==\n\n[case testImportedMissingSubpackage]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy a.py b/__init__.py\n[file a.py]\nfrom b.foo import bar\nx = 10\n[file b/__init__.py]\n[file a.py.2]\nfrom b.foo import bar\nx = '10'\n[out]\n==\n\n[case testFineAddedMissingStubs]\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==\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsPackage]\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==\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsPackageFrom]\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==\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsPackagePartial]\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==\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsPackagePartialGetAttr]\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==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsIgnore]\nfrom missing import f  # type: ignore\nf(int())\n[file missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsIgnorePackage]\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==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsIgnorePackageFrom]\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==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineAddedMissingStubsIgnorePackagePartial]\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==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testFineFollowImportSkipNotInvalidatedOnPresent]\n# flags: --follow-imports=skip\n# cmd: mypy main.py\n[file main.py]\nimport other\n[file other.py]\nx = 1\n[file other.py.2]\nx = 'hi'\n[stale]\n[rechecked]\n[out]\n==\n\n[case testFineFollowImportSkipNotInvalidatedOnPresentPackage]\n# flags: --follow-imports=skip\n# cmd: mypy main.py\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[out]\n==\n\n[case testFineFollowImportSkipNotInvalidatedOnAdded]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy main.py\n[file main.py]\nimport other\n[file other.py.2]\nx = 1\n[stale]\n[rechecked]\n[out]\n==\n\n-- TODO: Fix this: stubs should be followed normally even with follow-imports=skip\n[case testFineFollowImportSkipInvalidatedOnAddedStub-skip]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy main.py\n[file main.py]\nimport other\nx: str = other.x\n[file other.pyi.2]\nx = 1\n[stale main, other]\n[rechecked main, other]\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testFineAddedSkippedStubsPackageFrom]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy main.py\n# cmd2: mypy main.py package/__init__.py package/missing.py\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==\nmain.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testIgnoredAttrReprocessedModule]\nimport a\n[file a.py]\nimport b\nx = b.x  # type: ignore\ny: int = x\n[file b.py]\nimport c\n[file b.py.2]\nimport c\nx = c.x\n[file c.py]\nx: str\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testMissingStubAdded1]\n# flags: --follow-imports=skip\n# cmd: mypy main.py\n\n[file main.py]\nimport foo\nfoo.x = 1\n[file foo.pyi.2]\nx = 'x'\n[file main.py.3]\nimport foo\nfoo.x = 'y'\n[out]\nmain.py:1: error: Cannot find implementation or library stub for module named \"foo\"\nmain.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain.py:2: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n==\n\n[case testMissingStubAdded2]\n# flags: --follow-imports=skip\n# cmd: mypy main.py\n\n[file main.py]\nimport foo  # type: ignore\nfoo.x = 1\n[file foo.pyi.2]\nx = 'x'\n[file main.py.3]\nimport foo\nfoo.x = 'y'\n[out]\n==\nmain.py:2: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n==\n\n[case testDoNotFollowImportToNonStubFile]\n# flags: --follow-imports=skip\n# cmd: mypy main.py\n\n[file main.py]\nimport foo  # type: ignore\nfoo.x = 1\n[file foo.py.2]\nx = 'x'\n1 + 'x'\n\n[out]\n==\n\n[case testLibraryStubsNotInstalled]\nimport a\n[file a.py]\nimport requests\n[file a.py.2]\n# nothing\n[file a.py.3]\nimport jack\n[out]\na.py:1: error: Library stubs not installed for \"requests\"\na.py:1: note: Hint: \"python3 -m pip install types-requests\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n==\na.py:1: error: Library stubs not installed for \"jack\"\na.py:1: note: Hint: \"python3 -m pip install types-JACK-Client\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testIgnoreErrorsFromTypeshed]\n# flags: --custom-typeshed-dir tmp/ts --follow-imports=normal\n# cmd1: mypy a.py\n# cmd2: mypy a.py\n\n[file a.py]\nimport foobar\n\n[file ts/stdlib/abc.pyi]\n[file ts/stdlib/builtins.pyi]\nclass object: pass\nclass str: pass\nclass ellipsis: pass\n[file ts/stdlib/sys.pyi]\n[file ts/stdlib/types.pyi]\n[file ts/stdlib/typing.pyi]\ndef cast(x): ...\n[file ts/stdlib/typing_extensions.pyi]\n[file ts/stdlib/VERSIONS]\n[file ts/stubs/mypy_extensions/mypy_extensions.pyi]\n\n[file ts/stdlib/foobar.pyi.2]\n# We report no errors from typeshed. It would be better to test ignoring\n# errors from PEP 561 packages, but it's harder to test and uses the\n# same code paths, so we are using typeshed instead.\nimport baz\nimport zar\nundefined\n\n[file ts/stdlib/baz.pyi.2]\nimport whatever\nundefined\n\n[out]\na.py:1: error: Cannot find implementation or library stub for module named \"foobar\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n"
  },
  {
    "path": "test-data/unit/fine-grained-python312.test",
    "content": "[case testPEP695TypeAliasDep]\nimport m\ndef g() -> m.C:\n    return m.f()\n[file m.py]\ntype C = int\n\ndef f() -> int:\n    pass\n[file m.py.2]\ntype C = str\n\ndef f() -> int:\n    pass\n[out]\n==\nmain:3: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testPEP695ChangeOldStyleToNewStyleTypeAlias]\nfrom m import A\nA()\n\n[file m.py]\nA = int\n\n[file m.py.2]\ntype A = int\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: \"TypeAliasType\" not callable\n\n[case testPEP695VarianceChangesDueToDependency]\nfrom a import C\n\nx: C[object] = C[int]()\n\n[file a.py]\nfrom b import A\n\nclass C[T]:\n    def f(self) -> A[T]: ...\n\n[file b.py]\nclass A[T]:\n    def f(self) -> T: ...\n\n[file b.py.2]\nclass A[T]:\n    def f(self) -> list[T]: ...\n\n[out]\n==\nmain:3: error: Incompatible types in assignment (expression has type \"C[int]\", variable has type \"C[object]\")\n\n[case testPEP695TypeAliasChangesDueToDependency]\nfrom a import A\nx: A\nx = 0\nx = ''\n\n[file a.py]\nfrom b import B\ntype A = B[int, str]\n\n[file b.py]\nfrom typing import Union as B\n\n[file b.py.2]\nfrom builtins import tuple as B\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\n==\nmain:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"Tuple[int, str]\")\nmain:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"Tuple[int, str]\")\n\n[case testPEP695NestedGenericClassMethodUpdated]\nfrom a import f\n\nclass C:\n    class D[T]:\n        x: T\n        def m(self) -> T:\n            f()\n            return self.x\n\n[file a.py]\ndef f() -> None: pass\n\n[file a.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\nmain:7: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testPEP695MultipleNestedGenericClassMethodUpdated]\nfrom a import f\n\nclass A:\n    class C:\n        class D[T]:\n            x: T\n            def m(self) -> T:\n                f()\n                return self.x\n\n[file a.py]\ndef f() -> None: pass\n\n[file a.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\nmain:8: error: Missing positional argument \"x\" in call to \"f\"\n"
  },
  {
    "path": "test-data/unit/fine-grained-suggest.test",
    "content": "[case testSuggestCallsites1]\n# suggest: --callsites foo.foo\n[file foo.py]\ndef foo(arg):\n    return 12\nvar = 0\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n    foo(arg='xyz')\n    args = ['']\n    foo(*args)\n    kwds = {'arg': ''}\n    foo(**kwds)\n[builtins fixtures/dict.pyi]\n[out]\nbar.py:3: (str)\nbar.py:4: (arg=str)\nbar.py:6: (*typing.List[str])\nbar.py:8: (**typing.Dict[str, str])\n==\n\n[case testSuggestCallsitesStep2]\n# suggest2: --callsites foo.foo\n[file foo.py]\ndef foo(arg):\n    return 12\nvar = 0\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n    foo(arg='xyz')\n    args = ['']\n    foo(*args)\n    kwds = {'arg': ''}\n    foo(**kwds)\n[builtins fixtures/dict.pyi]\n[out]\n==\nbar.py:3: (str)\nbar.py:4: (arg=str)\nbar.py:6: (*typing.List[str])\nbar.py:8: (**typing.Dict[str, str])\n\n[case testMaxGuesses]\n# suggest: foo.foo\n# suggest: --max-guesses=2 foo.foo\n[file foo.py]\n# The idea here is that we can only find the union type with more guesses.\ndef foo(x, y):\n    if not isinstance(x, int):\n        x+'1'\n\nfoo(1, 2)\nfoo('3', '4')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Union[int, str], object) -> None\n(object, object) -> None\n==\n\n[case testSuggestInferFunc1]\n# suggest: foo.foo\n[file foo.py]\ndef foo(arg, lol=None):\n    if isinstance(arg, int):\n        arg+1\n    else:\n        assert arg\n        arg+'1'\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n    foo(lol=10, arg=10)\n    foo(None)\ndef untyped(x) -> None:\n    foo(x)\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Union[str, int, None], Optional[int]) -> None\n==\n\n[case testSuggestInferFunc2]\n# suggest: foo.foo\n[file foo.py]\ndef foo(arg):\n    return arg\n[file bar.py]\nfrom foo import foo\ndef thing() -> str:\n    return ''\ndef bar() -> None:\n    # We stick it in a list so that the argument type is marked as \"inferred\",\n    # which we want to make sure doesn't show up.\n    x = ['hello']\n    foo(x[0])\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestInferFuncAny1]\n# suggest: foo.foo\n# suggest: foo.bar\n[file foo.py]\ndef foo(arg):\n    return arg.x\ndef bar(arg):\n    pass\n[file bar.py]\nfrom foo import bar\nbar(None)\n[out]\n(Any) -> Any\n(Optional[Any]) -> None\n==\n\n[case testSuggestInferFuncAny2]\n# suggest: --no-any foo.foo\n# suggest: --no-any foo.bar\n[file foo.py]\ndef foo(arg):\n    return arg.x\ndef bar(arg):\n    pass\n[file bar.py]\nfrom foo import bar\nbar(None)\n[out]\nNo guesses that match criteria!\nNo guesses that match criteria!\n==\n\n[case testSuggestInferTuple]\n# suggest: --no-any foo.foo\n[file foo.py]\ndef foo():\n    return 1, \"1\"\n[builtins fixtures/tuple.pyi]\n[out]\n() -> Tuple[int, str]\n==\n\n[case testSuggestInferNamedTuple]\n# suggest: foo.foo\n[file foo.py]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int)])\ndef foo():\n    return N(1)\n[builtins fixtures/tuple.pyi]\n[out]\n() -> foo.N\n==\n\n[case testSuggestInferTypedDict]\n# suggest: foo.foo\n[file foo.py]\nfrom typing_extensions import TypedDict\nTD = TypedDict('TD', {'x': int})\ndef foo():\n    return bar()\n\ndef bar() -> TD: ...\n[builtins fixtures/dict.pyi]\n[out]\n() -> foo.TD\n==\n\n[case testSuggestWithNested]\n# suggest: foo.foo\n[file foo.py]\ndef foo():\n    def bar():\n        return 1\n    return 'lol'\n\n[out]\n() -> str\n==\n\n[case testSuggestReexportNaming]\n# suggest: foo.foo\n[file foo.py]\nfrom bar import A\ndef foo(x):\n    return A(), A.C()\n[file bar.py]\nfrom baz import A\n[file baz.py]\nclass A:\n    class C:\n        ...\nclass B: ...\n\n[file caller.py]\nfrom foo import foo\nfrom baz import B\nfoo(B())\n[builtins fixtures/tuple.pyi]\n\n[out]\n(baz.B) -> Tuple[foo.A, foo:A.C]\n==\n\n[case testSuggestInferInit]\n# suggest: foo.Foo.__init__\n[file foo.py]\nclass Foo:\n    def __init__(self, arg):\n        self.arg = arg\n[file bar.py]\nfrom foo import Foo\nFoo('lol')\n[out]\n(str) -> None\n==\n\n[case testSuggestInferMethod1]\n# suggest: --no-any foo.Foo.foo\n[file foo.py]\nclass Foo:\n    def __init__(self) -> None:\n        self.y = '10'\n\n    def foo(self, arg, lol=None):\n        if isinstance(arg, int):\n            return arg+1\n        else:\n            assert arg\n            return arg+self.y\n[file bar.py]\nfrom foo import Foo\ndef bar() -> None:\n    x = Foo()\n    x.foo('abc')\n    x.foo(lol=10, arg=10)\n    x.foo(None)\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Union[str, int, None], Optional[int]) -> object\n==\n\n[case testSuggestInferMethod2]\n# suggest: foo.Foo.foo\n[file foo.py]\nclass Foo:\n    def i(self, x: int) -> int: return x\n    def s(self, x: str) -> str: return x\n\n    def foo(self, arg, lol=None):\n        if isinstance(arg, int):\n            return self.i(arg)\n        else:\n            assert arg\n            return self.s(arg)\n[file bar.py]\nfrom typing import Union\nfrom foo import Foo\ndef bar() -> None:\n    x = Foo()\n    x.foo('abc')\n    x.foo(lol=10, arg=10)\n    a: Union[str, int] = x.foo(None)\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Union[str, int, None], Optional[int]) -> Union[int, str]\n==\n\n[case testSuggestInferMethod3]\n# suggest2: foo.Foo.foo\n[file foo.py]\nclass Foo:\n    def foo(self, lol = None):\n        pass\n\n    def lol(self) -> None:\n        self.foo('lol')\n[file bar.py]\nfrom foo import Foo\ndef bar() -> None:\n    x = Foo()\n    x.foo('abc')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n==\n(Optional[str]) -> None\n\n[case testSuggestBackflow]\n# suggest: foo.foo\n# suggest: foo.bar\n# suggest: foo.baz\n# suggest: foo.Cls.spam\n# suggest: foo.method\n# suggest: foo.meet\n# suggest: foo.has_nested\n[file foo.py]\nfrom typing import Any, List, Optional\n\nclass A: pass\nclass B(A):\n    def test(self, x: A) -> None:\n        pass\n\ndef take_optional_a(x: Optional[A]) -> None:\n    pass\n\ndef take_a(x: A) -> None:\n    pass\n\ndef take_b(x: B) -> None:\n    pass\n\ndef take_any(x: Any) -> None:\n    pass\n\ndef take_kws(a: A, b: B) -> None:\n    pass\n\ndef take_star(*a: A) -> None:\n    pass\n\ndef foo(x):\n    take_b(x)\n\ndef bar(x):\n    take_b(x)\n\nbar(A())\n\ndef baz(x, y):\n    take_kws(a=y, b=x)\n\nclass Cls:\n    def spam(self, x, y):\n        take_star(x, y)\n\ndef method(x):\n    b = B()\n    b.test(x)\n\ndef meet(x, y):\n    take_a(x)\n    take_b(x)\n\n    take_a(y)\n    take_optional_a(y)\n    take_any(y)\n    foo(y)  # unannotated\n\ndef has_nested(x):\n    def nested():\n        take_b(x)\n\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(foo.B) -> None\n(foo.A) -> None\n(foo.B, foo.A) -> None\n(foo.A, foo.A) -> None\n(foo.A) -> None\n(foo.B, foo.A) -> None\n(foo.B) -> None\n==\n\n[case testSuggestInferFunctionUnreachable]\n# suggest: foo.foo\n[file foo.py]\nimport sys\ndef foo(lol):\n    if sys.platform == 'nothing':\n        return lol\n    else:\n        return lol + lol\n[file bar.py]\nfrom foo import foo\nfoo('test')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestInferMethodStep2]\n# suggest2: foo.Foo.foo\n[file foo.py]\nclass Foo:\n    def i(self, x: int) -> int: return x\n    def s(self, x: str) -> str: return x\n\n    def foo(self, arg, lol=None):\n        if isinstance(arg, int):\n            return self.i(arg)\n        else:\n            assert arg\n            return self.s(arg)\n[file bar.py]\nfrom typing import Union\nfrom foo import Foo\ndef bar() -> None:\n    x = Foo()\n    x.foo('abc')\n    x.foo(lol=10, arg=10)\n    a: Union[str, int] = x.foo(None)\n[builtins fixtures/isinstancelist.pyi]\n[out]\n==\n(Union[str, int, None], Optional[int]) -> Union[int, str]\n\n[case testSuggestInferNestedMethod]\n# suggest: foo.Foo.Bar.baz\n[file foo.py]\nclass Foo:\n    class Bar:\n        def baz(self, lol):\n            return lol\n[file bar.py]\nfrom foo import Foo\ndef bar() -> None:\n    x = Foo.Bar()\n    x.baz('abc')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestCallable]\n# suggest: foo.foo\n# suggest: foo.bar\n# suggest: --flex-any=0.9 foo.bar\n# suggest: foo.baz\n# suggest: foo.quux\n[file foo.py]\ndef foo(f):\n    return f(0, \"lol\")\ndef bar(f):\n    return f(0, \"lol\", 100)\ndef baz(f):\n    return f(y=1) + f(x=10, y=1)\ndef quux(f):\n    return f(1)\n[file bar.py]\nfrom typing import Any\nfrom foo import foo, bar, baz, quux\n\ndef whatever(x: int, y: str) -> int:\n    return 0\n\ndef starargs(*args: Any) -> int:\n    return 0\n\ndef named(*, x: int = 0, y: int) -> str:\n    return '0'\n\n# we don't properly handle default really. we just assume it is\n# actually required.\ndef default(x: int = 0) -> str:\n    return '0'\n\ndef test() -> None:\n    foo(whatever)\n    bar(starargs)\n    baz(named)\n    quux(default)\n[builtins fixtures/primitives.pyi]\n[out]\n(Callable[[int, str], int]) -> int\n(Callable[..., int]) -> int\nNo guesses that match criteria!\n(Callable[..., str]) -> str\n(Callable[[int], str]) -> str\n==\n\n[case testSuggestNewSemanal]\n# suggest: foo.Foo.foo\n# suggest: foo.foo\n[file foo.py]\nclass Foo:\n    def __init__(self) -> None:\n        self.y = '10'\n\n    def foo(self, arg, lol=None):\n        if isinstance(arg, int):\n            return arg+1\n        else:\n            assert arg\n            return arg+self.y\ndef foo(arg, lol=None):\n    if isinstance(arg, int):\n        arg+1\n    else:\n        assert arg\n        arg+'1'\n[file bar.py]\nfrom foo import Foo, foo\ndef bar() -> None:\n    x = Foo()\n    x.foo('abc')\n    x.foo(lol=10, arg=10)\n    x.foo(None)\ndef baz() -> None:\n    foo('abc')\n    foo(lol=10, arg=10)\n    foo(None)\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Union[str, int, None], Optional[int]) -> object\n(Union[str, int, None], Optional[int]) -> None\n==\n\n[case testSuggestInferFuncDecorator1]\n# suggest: foo.foo\n[file foo.py]\nfrom typing import TypeVar\nF = TypeVar('F')\n\ndef dec(x: F) -> F:\n    return x\n\n@dec\ndef foo(arg):\n    return arg\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestInferFuncDecorator2]\n# suggest: foo.foo\n[file foo.py]\nfrom typing import TypeVar, Callable, Any\nF = TypeVar('F', bound=Callable[..., Any])\n\ndef dec(x: F) -> F:\n    return x\n\n@dec\ndef foo(arg):\n    return arg\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestInferFuncDecorator3]\n# suggest: foo.foo\n[file foo.py]\nfrom typing import TypeVar, Callable, Any\nF = TypeVar('F', bound=Callable[..., Any])\n\ndef dec(s: str) -> Callable[[F], F]:\n    def f(x: F) -> F:\n        return x\n    return f\n\n@dec('lol')\ndef foo(arg):\n    return arg\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestInferFuncDecorator4]\n# suggest: foo.foo\n[file dec.py]\nfrom typing import TypeVar, Callable, Any\nF = TypeVar('F', bound=Callable[..., Any])\n\ndef dec(s: str) -> Callable[[F], F]:\n    def f(x: F) -> F:\n        return x\n    return f\n\n[file foo.py]\nimport dec\n\n@dec.dec('lol')\ndef foo(arg):\n    return arg\n[file bar.py]\nfrom foo import foo\ndef bar() -> None:\n    foo('abc')\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(str) -> str\n==\n\n[case testSuggestFlexAny1]\n# suggest: --flex-any=0.4 m.foo\n# suggest: --flex-any=0.7 m.foo\n# suggest: --flex-any=0.4 m.bar\n# suggest: --flex-any=0.6 m.bar\n# suggest2: --flex-any=0.4 m.foo\n# suggest2: --flex-any=0.7 m.foo\n[file m.py]\nfrom typing import Any\nany: Any\n\ndef foo(arg):\n    return 0\ndef bar(x, y):\n    return any\n\n[file n.py]\nfrom typing import Any\nany: Any\n\nfrom m import foo, bar\ndef wtvr() -> None:\n    foo(any)\n    bar(1, 2)\n\n[file n.py.2]\nfrom typing import Any\nany: Any\n\nfrom m import foo, bar\ndef wtvr() -> None:\n    foo([any])\n\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Any) -> int\nNo guesses that match criteria!\n(int, int) -> Any\nNo guesses that match criteria!\n==\n(typing.List[Any]) -> int\n(typing.List[Any]) -> int\n\n\n[case testSuggestFlexAny2]\n# suggest: --flex-any=0.5 m.baz\n# suggest: --flex-any=0.0 m.baz\n# suggest: --flex-any=0.5 m.F.foo\n# suggest: --flex-any=0.7 m.F.foo\n# suggest: --flex-any=0.7 m.noargs\n[file m.py]\n# Test mostly corner cases\n\n# Test that a None return doesn't get counted\ndef baz(x):\n    pass\n\nclass F:\n    # Test that self doesn't get counted\n    def foo(self, x):\n        return 0\n\n# Make sure we don't crash on noarg functions\ndef noargs():\n    pass\n\n[builtins fixtures/isinstancelist.pyi]\n[out]\nNo guesses that match criteria!\n(Any) -> None\n(Any) -> int\nNo guesses that match criteria!\n() -> None\n==\n\n[case testSuggestClassMethod]\n# suggest: foo.F.bar\n# suggest: foo.F.baz\n# suggest: foo.F.eggs\n[file foo.py]\nclass F:\n    @classmethod\n    def bar(cls, x, y):\n        return x\n\n    @staticmethod\n    def baz(x, y):\n        return x\n\n    @classmethod\n    def spam(cls):\n        # type: () -> None\n        cls.eggs(4)\n\n    @classmethod\n    def eggs(cls, x):\n        pass\n\n[file bar.py]\nfrom foo import F\ndef bar(iany) -> None:\n    F.bar(0, iany)\n    F().bar(0, 5)\n    F.baz('lol', iany)\n    F().baz('lol', 10)\n[builtins fixtures/classmethod.pyi]\n[out]\n(int, int) -> int\n(str, int) -> str\n(int) -> None\n==\n\n[case testSuggestColonBasic]\n# suggest: tmp/foo.py:1\n# suggest: tmp/bar/baz.py:2\n[file foo.py]\ndef func(arg):\n    return 0\nfunc('test')\nfrom bar.baz import C\nC().method('test')\n[file bar/__init__.py]\n[file bar/baz.py]\nclass C:\n    def method(self, x):\n        return 0\n[out]\n(str) -> int\n(str) -> int\n==\n\n[case testSuggestColonAfter]\n# suggest: tmp/foo.py:6\n# suggest: tmp/foo.py:15\n# suggest: tmp/foo.py:16\n# suggest: tmp/foo.py:18\n[file foo.py]\nfrom typing import TypeVar\nF = TypeVar('F')\n\ndef foo():\n    # hi\n    return 1\n\ndef dec(x: F) -> F:\n    return x\n\nclass A:\n    @dec\n    def bar(self):\n        return 1.0\n\n@dec\ndef baz():\n    return 'test'\n\n[out]\n() -> int\n() -> float\n() -> str\n() -> str\n==\n\n[case testSuggestParent]\n# suggest: foo.B.foo\n# suggest: foo.B.bar\n# suggest: foo.C.foo\n[file foo.py]\nfrom typing import TypeVar, Callable, Any\nF = TypeVar('F', bound=Callable[..., Any])\ndef deco(f: F) -> F: ...\n\nclass A:\n    def foo(self, x: int) -> float:\n        return 0.0\n\n    @deco\n    def bar(self, x: int) -> float:\n        return 0.0\n\n\nclass B(A):\n    def foo(self, x):\n        return 0.0\n\n    @deco\n    def bar(self, x):\n        return 0.0\n\nclass C(B):\n    def foo(self, x):\n        return 0.0\n\n[out]\n(int) -> float\n(int) -> float\n(int) -> float\n==\n\n[case testSuggestColonBadLocation]\n# suggest: tmp/foo.py:7:8:9\n[file foo.py]\n[out]\nMalformed location for function: tmp/foo.py:7:8:9. Must be either package.module.Class.method or path/to/file.py:line\n==\n\n[case testSuggestColonBadLine]\n# suggest: tmp/foo.py:bad\n[file foo.py]\n[out]\nLine number must be a number. Got bad\n==\n\n[case testSuggestColonBadFile]\n# suggest: tmp/foo.txt:1\n[file foo.txt]\ndef f(): pass\n[out]\nSource file is not a Python file\n==\n\n[case testSuggestColonClass]\n# suggest: tmp/foo.py:1\n[file foo.py]\nclass C:\n    pass\n[out]\nCannot find a function at line 1\n==\n\n[case testSuggestColonDecorator]\n# suggest: tmp/foo.py:6\n[file foo.py]\nfrom typing import TypeVar, Callable, Any\nF = TypeVar('F', bound=Callable[..., Any])\ndef deco(f: F) -> F: ...\n\n@deco\ndef func(arg):\n    return 0\nfunc('test')\n[out]\n(str) -> int\n==\n\n[case testSuggestColonMethod]\n# suggest: tmp/foo.py:3\n[file foo.py]\nclass Out:\n    class In:\n        def method(self, x):\n            return Out()\nx: Out.In\nx.method(x)\n[out]\n(foo:Out.In) -> foo.Out\n==\n\n[case testSuggestColonMethodJSON]\n# suggest: --json tmp/foo.py:3\n[file foo.py]\nclass Out:\n    class In:\n        def method(self, x):\n            return Out()\nx: Out.In\nx.method(x)\n[out]\n\\[{\"func_name\": \"Out.In.method\", \"line\": 3, \"path\": \"tmp/foo.py\", \"samples\": 0, \"signature\": {\"arg_types\": [\"foo:Out.In\"], \"return_type\": \"foo.Out\"}}]\n==\n\n[case testSuggestColonNonPackageDir]\n# cmd: mypy foo/bar/baz.py\n# suggest: tmp/foo/bar/baz.py:1\n[file foo/bar/baz.py]\ndef func(arg):\n    return 0\nfunc('test')\n[out]\n(str) -> int\n==\n\n[case testSuggestUseFixmeBasic]\n# suggest: --use-fixme=UNKNOWN foo.foo\n# suggest: --use-fixme=UNKNOWN foo.bar\n[file foo.py]\n\ndef foo():\n    return g()\n\ndef bar(x):\n    return None\n\ndef g(): ...\nx = bar(g())\n[out]\n() -> UNKNOWN\n(UNKNOWN) -> None\n==\n\n[case testSuggestUseFixmeNoNested]\n# suggest: --use-fixme=UNKNOWN foo.foo\n[file foo.py]\nfrom typing import List, Any\n\ndef foo(x, y):\n    return x, y\n\ndef f() -> List[Any]: ...\ndef g(): ...\n\nz = foo(f(), g())\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(foo.List[Any], UNKNOWN) -> Tuple[foo.List[Any], Any]\n==\n\n[case testSuggestBadImport]\n# suggest: foo.foo\n[file foo.py]\nfrom nothing import Foo  # type: ignore\n\ndef foo(x: Foo):\n    return 10\n[out]\n(foo.Foo) -> int\n==\n\n[case testSuggestDict]\n# suggest: foo.foo\n# suggest: foo.bar\n# suggest: foo.baz\n# suggest: foo.quux\n# suggest: foo.spam\n[file foo.py]\nfrom typing import List, Any\n\ndef foo():\n    return {'x': 5}\n\ndef bar():\n    return {}\n\ndef baz() -> List[Any]:\n    return [{'x': 5}]\n\ndef quux() -> List[Any]:\n    return [1]\n\ndef spam(x):\n    pass\n\nspam({'x': 5})\n\n[builtins fixtures/dict.pyi]\n[out]\n() -> typing.Dict[str, int]\n() -> typing.Dict[Any, Any]\n() -> foo:List[typing.Dict[str, int]]\n() -> foo.List[int]\n(typing.Dict[str, int]) -> None\n==\n\n[case testSuggestWithErrors]\n# suggest: foo.foo\n[file foo.py]\n1+'no'\n\ndef foo():\n    return 10\n[out]\nfoo.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n() -> int\n==\nfoo.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testSuggestWithBlockingError]\n# suggest: foo.foo\n[file foo.py]\ndef foo():\n    return 10\n\n(\n[out]\nfoo.py:4: error: unexpected EOF while parsing\nCommand 'suggest' is only valid after a 'check' command (that produces no parse errors)\n==\nfoo.py:4: error: unexpected EOF while parsing\n[out version>=3.10]\nfoo.py:4: error: '(' was never closed\nCommand 'suggest' is only valid after a 'check' command (that produces no parse errors)\n==\nfoo.py:4: error: '(' was never closed\n-- )\n\n[case testSuggestRefine]\n# suggest: foo.foo\n# suggest: foo.spam\n# suggest: foo.eggs\n# suggest: foo.take_l\n# suggest: foo.union\n# suggest: foo.callable1\n# suggest: foo.callable2\n# suggest: foo.optional1\n# suggest: foo.optional2\n# suggest: foo.optional3\n# suggest: foo.optional4\n# suggest: foo.optional5\n# suggest: foo.optional_any\n# suggest: foo.dict1\n# suggest: foo.tuple1\n[file foo.py]\nfrom typing import Any, List, Union, Callable, Optional, Set, Dict, Tuple\n\ndef bar():\n    return 10\n\ndef foo(x: int, y):\n    return x + y\n\nfoo(bar(), 10)\n\ndef spam(x: int, y: Any) -> Any:\n    return x + y\n\nspam(bar(), 20)\n\ndef eggs(x: int) -> List[Any]:\n    a = [x]\n    return a\n\ndef take_l(x: List[Any]) -> Any:\n    return x[0]\n\ntest = [10, 20]\ntake_l(test)\n\ndef union(x: Union[int, str]):\n    pass\n\nunion(10)\n\ndef add1(x: float) -> int:\n    pass\n\ndef callable1(f: Callable[[int], Any]):\n    return f(10)\n\ncallable1(add1)\n\ndef callable2(f: Callable[..., Any]):\n    return f(10)\n\ncallable2(add1)\n\ndef optional1(x: Optional[Any]):\n    pass\n\noptional1(10)\n\ndef optional2(x: Union[None, int, Any]):\n    if x is None:\n        pass\n    elif isinstance(x, str):\n        pass\n    else:\n        add1(x)\n\noptional2(10)\noptional2('test')\n\ndef optional3(x: Optional[List[Any]]):\n    assert x\n    return x[0]\n\noptional3(test)\n\nset_test = {1, 2}\n\ndef optional4(x: Union[Set[Any], List[Any]]):\n    pass\n\noptional4(test)\noptional4(set_test)\n\ndef optional5(x: Optional[Any]):\n    pass\n\noptional5(10)\noptional5(None)\n\ndef optional_any(x: Optional[Any] = None):\n    pass\n\ndef dict1(d: Dict[int, Any]):\n    pass\n\nd: Dict[Any, int]\ndict1(d)\n\ndef tuple1(d: Tuple[int, Any]):\n    pass\n\nt: Tuple[Any, int]\ntuple1(t)\n\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(int, int) -> int\n(int, int) -> int\n(int) -> foo.List[int]\n(foo.List[int]) -> int\n(Union[int, str]) -> None\n(Callable[[int], int]) -> int\n(Callable[[float], int]) -> int\n(Optional[int]) -> None\n(Union[None, int, str]) -> None\n(Optional[foo.List[int]]) -> int\n(Union[foo.Set[int], foo.List[int]]) -> None\n(Optional[int]) -> None\n(Optional[Any]) -> None\n(foo.Dict[int, int]) -> None\n(Tuple[int, int]) -> None\n==\n\n[case testSuggestRefine2]\n# suggest: foo.optional5\n[file foo.py]\nfrom typing import Optional, Any\n\ndef optional5(x: Optional[Any]):\n    pass\n\noptional5(10)\noptional5(None)\n\n[builtins fixtures/isinstancelist.pyi]\n[out]\n(Optional[int]) -> None\n==\n"
  },
  {
    "path": "test-data/unit/fine-grained.test",
    "content": "-- Test cases for fine-grained incremental checking\n--\n-- Test cases may define multiple versions of a file\n-- (e.g. m.py, m.py.2). There is always an initial batch\n-- pass that processes all files present initially, followed\n-- by one or more fine-grained incremental passes that use\n-- alternative versions of files, if available. If a file\n-- just has a single .py version, it is used for all passes.\n\n-- TODO: what if version for some passes but not all\n\n-- Output is laid out like this:\n--\n--   [out]\n--   <optional output from batch pass>\n--   ==\n--   <optional output from first incremental pass>\n--\n--\n-- Modules that are expected to be detected as changed by dmypy_server\n-- can be checked with [stale ...]\n-- Generally this should mean added, deleted, or changed files, though there\n-- are important edge cases related to the cache: deleted files won't be detected\n-- as changed in the initial run with the cache while modules that depended on them\n-- should be.\n--\n-- Modules that require a full-module reprocessing by update can be checked with\n-- [rechecked ...]. This should include any files detected as having changed as well\n-- as any files that contain targets that need to be reprocessed but which haven't\n-- been loaded yet. If there is no [rechecked...] directive, it inherits the value of\n-- [stale ...].\n--\n-- Specifications for later runs can be given with [stale2 ...], [stale3 ...], etc.\n--\n-- Test runner can parse options from mypy.ini file. Updating this file in between\n-- incremental runs is not yet supported.\n--\n-- Each test case run without caching and with caching (if the initial run passes),\n-- unless it has one a -only_when_cache or -only_when_nocache arguments. We sometimes\n-- skip caching test cases to speed up tests, if the caching variant is not useful.\n-- The caching test case variants get an implicit _cached suffix.\n\n[case testReprocessFunction]\nimport m\ndef g() -> int:\n    return m.f()\n[file m.py]\ndef f() -> int:\n    pass\n[file m.py.2]\ndef f() -> str:\n    pass\n[out]\n==\nmain:3: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testReprocessTopLevel]\nimport m\nm.f(1)\ndef g() -> None: pass\n[file m.py]\ndef f(x: int) -> None: pass\n[file m.py.2]\ndef f(x: str) -> None: pass\n[out]\n==\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testReprocessMethod]\nimport m\nclass B:\n    def f(self, a: m.A) -> None:\n        a.g() # E\n[file m.py]\nclass A:\n    def g(self) -> None: pass\n[file m.py.2]\nclass A:\n    def g(self, a: A) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"a\" in call to \"g\" of \"A\"\n\n[case testReprocessMethodShowSource]\n# flags: --pretty --show-error-codes\nimport m\nclass B:\n    def f(self, a: m.A) -> None:\n        a.g() # E\n[file m.py]\nclass A:\n    def g(self) -> None: pass\n[file m.py.2]\nclass A:\n    def g(self, a: A) -> None: pass\n[out]\n==\nmain:5: error: Missing positional argument \"a\" in call to \"g\" of \"A\"  [call-arg]\n            a.g() # E\n            ^~~~~\n\n[case testFunctionMissingModuleAttribute]\nimport m\ndef h() -> None:\n    m.f(1)\n[file m.py]\ndef f(x: int) -> None: pass\n[file m.py.2]\ndef g(x: str) -> None: pass\n[builtins fixtures/fine_grained.pyi]\n[out]\n==\nmain:3: error: Module has no attribute \"f\"\n\n[case testTopLevelMissingModuleAttribute]\nimport m\nm.f(1)\ndef g() -> None: pass\n[file m.py]\ndef f(x: int) -> None: pass\n[file m.py.2]\ndef g(x: int) -> None: pass\n[builtins fixtures/fine_grained.pyi]\n[out]\n==\nmain:2: error: Module has no attribute \"f\"\n\n[case testClassChangedIntoFunction]\n\nimport m\ndef f(a: m.A) -> None:\n    pass\n[file m.py]\nclass A: pass\n[file m.py.2]\ndef A() -> None: pass\n[out]\n==\nmain:3: error: Function \"m.A\" is not valid as a type\nmain:3: note: Perhaps you need \"Callable[...]\" or a callback protocol?\n\n[case testClassChangedIntoFunction2]\n\nimport m\nclass B:\n    def f(self, a: m.A) -> None: pass\n[file m.py]\nclass A: pass\n[file m.py.2]\ndef A() -> None: pass\n[file n.py.3]\n[out]\n==\nmain:4: error: Function \"m.A\" is not valid as a type\nmain:4: note: Perhaps you need \"Callable[...]\" or a callback protocol?\n==\nmain:4: error: Function \"m.A\" is not valid as a type\nmain:4: note: Perhaps you need \"Callable[...]\" or a callback protocol?\n\n[case testAttributeTypeChanged]\nimport m\ndef f(a: m.A) -> int:\n    return a.x\n[file m.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n[file m.py.2]\nclass A:\n    def f(self) -> None:\n        self.x = 'x'\n[out]\n==\nmain:3: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testAttributeRemoved]\nimport m\ndef f(a: m.A) -> int:\n    return a.x\n[file m.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n[file m.py.2]\nclass A:\n    def f(self) -> None: pass\n[out]\n==\nmain:3: error: \"A\" has no attribute \"x\"\n\n[case testVariableTypeBecomesInvalid]\nimport m\ndef f() -> None:\n    a: m.A\n[file m.py]\nclass A: pass\n[file m.py.2]\n[out]\n==\nmain:3: error: Name \"m.A\" is not defined\n\n[case testTwoIncrementalSteps]\nimport m\nimport n\n[file m.py]\ndef f() -> None: pass\n[file n.py]\nimport m\ndef g() -> None:\n    m.f() # E\n[file m.py.2]\nimport n\ndef f(x: int) -> None:\n    n.g() # E\n[file n.py.3]\nimport m\ndef g(a: str) -> None:\n    m.f('') # E\n[out]\n==\nn.py:3: error: Missing positional argument \"x\" in call to \"f\"\n==\nn.py:3: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\nm.py:3: error: Missing positional argument \"a\" in call to \"g\"\n\n[case testTwoRounds]\nimport m\ndef h(a: m.A) -> int:\n    return a.x\n[file m.py]\nimport n\nclass A:\n    def g(self, b: n.B) -> None:\n        self.x = b.f()\n[file n.py]\nclass B:\n    def f(self) -> int: pass\n[file n.py.2]\nclass B:\n    def f(self) -> str: pass\n[out]\n==\nmain:3: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testFixTypeError]\nimport m\ndef f(a: m.A) -> None:\n    a.f(a)\n[file m.py]\nclass A:\n    def f(self, a: 'A') -> None: pass\n[file m.py.2]\nclass A:\n    def f(self) -> None: pass\n[file m.py.3]\nclass A:\n    def f(self, a: 'A') -> None: pass\n[out]\n==\nmain:3: error: Too many arguments for \"f\" of \"A\"\n==\n\n[case testFixTypeError2]\nimport m\ndef f(a: m.A) -> None:\n    a.f()\n[file m.py]\nclass A:\n    def f(self) -> None: pass\n[file m.py.2]\nclass A:\n    def g(self) -> None: pass\n[file m.py.3]\nclass A:\n    def f(self) -> None: pass\n[out]\n==\nmain:3: error: \"A\" has no attribute \"f\"\n==\n\n[case testFixSemanticAnalysisError]\nimport m\ndef f() -> None:\n    m.A()\n[file m.py]\nclass A: pass\n[file m.py.2]\nclass B: pass\n[file m.py.3]\nclass A: pass\n[builtins fixtures/fine_grained.pyi]\n[out]\n==\nmain:3: error: Module has no attribute \"A\"\n==\n\n[case testContinueToReportTypeCheckError]\nimport m\ndef f(a: m.A) -> None:\n    a.f()\ndef g(a: m.A) -> None:\n    a.g()\n[file m.py]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[file m.py.2]\nclass A: pass\n[file m.py.3]\nclass A:\n    def f(self) -> None: pass\n[out]\n==\nmain:3: error: \"A\" has no attribute \"f\"\nmain:5: error: \"A\" has no attribute \"g\"\n==\nmain:5: error: \"A\" has no attribute \"g\"\n\n[case testContinueToReportSemanticAnalysisError]\nimport m\ndef f() -> None:\n    m.A()\ndef g() -> None:\n    m.B()\n[file m.py]\nclass A: pass\nclass B: pass\n[file m.py.2]\n[file m.py.3]\nclass A: pass\n[builtins fixtures/fine_grained.pyi]\n[out]\n==\nmain:3: error: Module has no attribute \"A\"\nmain:5: error: Module has no attribute \"B\"\n==\nmain:5: error: Module has no attribute \"B\"\n\n[case testContinueToReportErrorAtTopLevel-only_when_nocache]\n-- Different cache/no-cache tests because:\n-- Error message ordering differs\nimport n\nimport m\nm.A().f()\n[file n.py]\nimport m\nm.A().g()\n[file m.py]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[file m.py.2]\nclass A: pass\n[file m.py.3]\nclass A:\n    def f(self) -> None: pass\n[out]\n==\nmain:3: error: \"A\" has no attribute \"f\"\nn.py:2: error: \"A\" has no attribute \"g\"\n==\nn.py:2: error: \"A\" has no attribute \"g\"\n\n[case testContinueToReportErrorAtTopLevel2-only_when_cache]\n-- Different cache/no-cache tests because:\n-- Error message ordering differs\nimport n\nimport m\nm.A().f()\n[file n.py]\nimport m\nm.A().g()\n[file m.py]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[file m.py.2]\nclass A: pass\n[file m.py.3]\nclass A:\n    def f(self) -> None: pass\n[out]\n==\nn.py:2: error: \"A\" has no attribute \"g\"\nmain:3: error: \"A\" has no attribute \"f\"\n==\nn.py:2: error: \"A\" has no attribute \"g\"\n\n[case testContinueToReportErrorInMethod]\nimport m\nclass C:\n    def f(self, a: m.A) -> None:\n        a.f()\n    def g(self, a: m.A) -> None:\n        a.g()\n[file m.py]\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[file m.py.2]\nclass A: pass\n[file m.py.3]\nclass A:\n    def f(self) -> None: pass\n[out]\n==\nmain:4: error: \"A\" has no attribute \"f\"\nmain:6: error: \"A\" has no attribute \"g\"\n==\nmain:6: error: \"A\" has no attribute \"g\"\n\n[case testInitialBatchGeneratedError]\nimport m\ndef g() -> None:\n    m.f()\ndef h() -> None:\n    m.g()\n[file m.py]\ndef f(x: object) -> None: pass\n[file m.py.2]\ndef f() -> None: pass\n[file m.py.3]\ndef f() -> None: pass\ndef g() -> None: pass\n[builtins fixtures/fine_grained.pyi]\n[out]\nmain:3: error: Missing positional argument \"x\" in call to \"f\"\nmain:5: error: Module has no attribute \"g\"\n==\nmain:5: error: Module has no attribute \"g\"\n==\n\n[case testKeepReportingErrorIfNoChanges]\nimport m\ndef h() -> None:\n    m.g()\n[file m.py]\n[file m.py.2]\n[builtins fixtures/fine_grained.pyi]\n[out]\nmain:3: error: Module has no attribute \"g\"\n==\nmain:3: error: Module has no attribute \"g\"\n\n[case testFixErrorAndReintroduce]\nimport m\ndef h() -> None:\n    m.g()\n[file m.py]\n[file m.py.2]\ndef g() -> None: pass\n[file m.py.3]\n[builtins fixtures/fine_grained.pyi]\n[out]\nmain:3: error: Module has no attribute \"g\"\n==\n==\nmain:3: error: Module has no attribute \"g\"\n\n[case testIgnoreWorksAfterUpdate]\nimport a\n[file a.py]\nimport b\nint() + str()  # type: ignore\n[file b.py]\nx = 1\n[file b.py.2]\nx = 2\n[file b.py.3]\nx = 3\n[delete b.py.4]\n[out]\n==\n==\n==\na.py:1: error: Cannot find implementation or library stub for module named \"b\"\na.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testIgnoreWorksWithMissingImports]\nimport a\n[file a.py]\nimport b\nimport xyz  # type: ignore\nxyz.whatever\n[file b.py]\nx = 1\n[file b.py.2]\nx = 2\n[file b.py.3]\nx = 3\n[file xyz.py.4]\n[out]\n==\n==\n==\na.py:3: error: \"object\" has no attribute \"whatever\"\n\n[case testAddedIgnoreWithMissingImports]\nimport a\n[file a.py]\nfrom b import x\ny: int = x\n[file b.py]\nfrom xyz import x\n[file b.py.2]\nfrom xyz import x  # type: ignore\n[file xyz.py.3]\nx = str()\n[out]\nb.py:1: error: Cannot find implementation or library stub for module named \"xyz\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n==\na.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testRemovedIgnoreWithMissingImport]\nimport a\n[file a.py]\nfrom b import x\ny: int = x\n[file b.py]\nfrom xyz import x  # type: ignore\n[file b.py.2]\nfrom xyz import x\n[file xyz.py.3]\nx = str()\n[out]\n==\nb.py:1: error: Cannot find implementation or library stub for module named \"xyz\"\nb.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\na.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testRemovedModuleUnderIgnore]\nimport a\n[file a.py]\nimport c\nfrom b import x  # type: ignore\ny: int = x\n[file b.py]\nx = str()\n[file c.py]\nx = 1\n[delete b.py.2]\n[file c.py.3]\nx = 3\n[out]\na.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n==\n==\n\n[case AddedModuleUnderIgnore]\nimport a\n[file a.py]\nimport c\nfrom b import x  # type: ignore\ny: int = x\n[file c.py]\nx = 1\n[file c.py.2]\nx = 2\n[file b.py.3]\n# empty\n[out]\n==\n==\n\n[case testIgnoreInBetween]\nimport a\n[file a.py]\nimport b\nx: int = b.x\n[file b.py]\nimport c\nx = c.C.x  # type: ignore\n[file c.py]\nclass C:\n    pass\n[file c.py.2]\nclass C:\n    x: int\n[file c.py.3]\n# empty\n[file c.py.4]\nclass C:\n    x: str\n[out]\n==\n==\n==\na.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testIgnoredAttrReprocessedModule]\nimport a\n[file a.py]\nimport b\nx = b.x  # type: ignore\ny: int = x\n[file b.py]\nimport c\n[file b.py.2]\nimport c\nx = c.x\n[file c.py]\nx: str\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testIgnoredAttrReprocessedBase]\nimport a\n[file a.py]\nimport b\ndef fun() -> None:\n    x = b.C.x  # type: ignore\n    y: int = x\n[file b.py]\nimport c\nclass C:\n    pass\n[file b.py.2]\nimport c\nclass C(c.B):\n    pass\n[file c.py]\nclass B:\n    x: str\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testIgnoredAttrReprocessedMeta]\nimport a\n[file a.py]\nimport b\ndef fun() -> None:\n    x = b.C.x  # type: ignore\n    y: int = x\n[file b.py]\nimport c\nclass C:\n    pass\n[file b.py.2]\nimport c\nclass C(metaclass=c.M):\n    pass\n[file c.py]\nclass M(type):\n    x: str\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testDataclassUpdate1]\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: int\n\n[file b.py]\nfrom dataclasses import dataclass\n\nfrom a import A\n@dataclass\nclass B(A):\n    y: int\n\nB(1, 2)\n\n[file a.py.2]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: str\n\n[file a.py.3]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: int\n\n[out]\n==\nb.py:8: error: Argument 1 to \"B\" has incompatible type \"int\"; expected \"str\"\n==\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassUpdate2]\n[file c.py]\nFoo = int\n\n[file c.py.2]\nFoo = str\n\n[file a.py]\nfrom dataclasses import dataclass\nfrom c import Foo\n\n@dataclass\nclass A:\n    x: Foo\n\n[file b.py]\nfrom dataclasses import dataclass\n\nfrom a import A\n@dataclass\nclass B(A):\n    y: int\n\nB(1, 2)\n\n[out]\n==\nb.py:8: error: Argument 1 to \"B\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassUpdate3]\nfrom b import B\nB(1, 2)\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n@dataclass\nclass B(A):\n    b: int\n[file a.py]\nfrom dataclasses import dataclass\n@dataclass\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n@dataclass\nclass A:\n    a: int\n    other: int\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nmain:2: error: Missing positional argument \"b\" in call to \"B\"\n\n[case testDataclassUpdate4]\nfrom b import B\nB(1, 2)\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n@dataclass(frozen=True)\nclass B(A):\n    b: int\n[file a.py]\nfrom dataclasses import dataclass\n@dataclass(frozen=True)\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n@dataclass(frozen=True)\nclass A:\n    a: int\n    other: int\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nmain:2: error: Missing positional argument \"b\" in call to \"B\"\n\n[case testDataclassUpdate5]\nfrom b import B\nB(1, 2)\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n@dataclass\nclass B(A):\n    b: int\n[file a.py]\nfrom dataclasses import dataclass\n@dataclass(init=False)\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n@dataclass(init=False)\nclass A:\n    a: int\n    other: int\n\n[file a.py.3]\nfrom dataclasses import dataclass\n@dataclass(init=False)\nclass A:\n    a: int\n\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nmain:2: error: Missing positional argument \"b\" in call to \"B\"\n==\n\n[case testDataclassUpdate6]\nfrom b import B\nB(1, 2) < B(1, 2)\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n@dataclass\nclass B(A):\n    b: int\n[file a.py]\nfrom dataclasses import dataclass\n@dataclass(order=True)\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n@dataclass\nclass A:\n    a: int\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nmain:2: error: Unsupported left operand type for < (\"B\")\n\n[case testDataclassUpdate8]\nfrom c import C\nC(1, 2, 3)\n[file c.py]\nfrom b import B\nfrom dataclasses import dataclass\n@dataclass\nclass C(B):\n    c: int\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n@dataclass\nclass B(A):\n    b: int\n[file a.py]\nfrom dataclasses import dataclass\n@dataclass\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n@dataclass\nclass A:\n    a: int\n    other: int\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nmain:2: error: Missing positional argument \"c\" in call to \"C\"\n\n[case testDataclassUpdate9]\nfrom c import C\nC(1, 2, 3)\n[file c.py]\nfrom b import B\nfrom dataclasses import dataclass\n@dataclass\nclass C(B):\n    c: int\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n@dataclass\nclass B(A):\n    b: int\n[file a.py]\nfrom dataclasses import dataclass\n@dataclass(init=False)\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n@dataclass(init=False)\nclass A:\n    a: int\n    other: int\n\n[file a.py.3]\nfrom dataclasses import dataclass\n@dataclass(init=False)\nclass A:\n    a: int\n\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\nmain:2: error: Missing positional argument \"c\" in call to \"C\"\n==\n\n[case testAttrsUpdate1]\n[file a.py]\nimport attr\n@attr.s\nclass A:\n    a = attr.ib()   # type: int\n\n[file b.py]\nfrom a import A\nimport attr\n@attr.s\nclass B(A):\n    b = attr.ib()   # type: int\n\nB(1, 2)\n\n[file a.py.2]\nimport attr\n@attr.s\nclass A:\n    a = attr.ib()   # type: int\n    other = attr.ib()   # type: int\n[builtins fixtures/list.pyi]\n[out]\n==\nb.py:7: error: Missing positional argument \"b\" in call to \"B\"\n\n[case testAttrsUpdate2]\nfrom b import B\nB(1, 2)\n[file b.py]\nfrom a import A\nimport attr\n@attr.s\nclass B(A):\n    b = attr.ib()   # type: int\n[file a.py]\nimport attr\n@attr.s(init=False)\nclass A:\n    a = attr.ib()   # type: int\n\n[file a.py.2]\nimport attr\n@attr.s(init=False)\nclass A:\n    a = attr.ib()   # type: int\n    other = attr.ib()   # type: int\n[builtins fixtures/list.pyi]\n[out]\n==\nmain:2: error: Missing positional argument \"b\" in call to \"B\"\n\n[case testAttrsUpdate3]\nfrom b import B\nB(1, 2)\n[file b.py]\nfrom a import A\nimport attr\n@attr.s(auto_attribs=True)\nclass B(A):\n    x: int\n[file a.py]\nimport attr\n@attr.s(auto_attribs=True, init=False)\nclass A:\n    a: int\n\n[file a.py.2]\nimport attr\n@attr.s(auto_attribs=True, init=False)\nclass A:\n    a: int\n    other: int\n\n[file a.py.3]\nimport attr\n@attr.s(auto_attribs=True, init=False)\nclass A:\n    a: int\n[builtins fixtures/list.pyi]\n\n[out]\n==\nmain:2: error: Missing positional argument \"x\" in call to \"B\"\n==\n\n[case testAttrsUpdate4]\nfrom b import B\nB(1, 2) < B(1, 2)\n[file b.py]\nfrom a import A\nimport attr\n@attr.s(eq=False)\nclass B(A):\n    b = attr.ib()   # type: int\n[file a.py]\nimport attr\n@attr.s(init=False)\nclass A:\n    a = attr.ib()   # type: int\n\n[file a.py.2]\nimport attr\n@attr.s(eq=False, init=False)\nclass A:\n    a = attr.ib()   # type: int\n[builtins fixtures/list.pyi]\n[out]\n==\nmain:2: error: Unsupported left operand type for < (\"B\")\n\n[case testAttrsUpdateBaseKwOnly]\nfrom b import B\nB(5)\n[file a.py]\nimport attr\n@attr.s()\nclass A:\n    a = attr.ib(15)   # type: int\n[file b.py]\nfrom a import A\nimport attr\n@attr.s(kw_only=True)\nclass B(A):\n    b = attr.ib(\"16\")   # type: str\n\n[file a.py.2]\nimport attr\n@attr.s(kw_only=True)\nclass A:\n    a = attr.ib(15)   # type: int\n[builtins fixtures/plugin_attrs.pyi]\n[out]\n==\nmain:2: error: Too many positional arguments for \"B\"\n\n[case testAddBaseClassMethodCausingInvalidOverride]\nimport m\nclass B(m.A):\n    def f(self) -> str: pass\n[file m.py]\nclass A: pass\n[file m.py.2]\nclass A:\n    def f(self) -> int: pass\n[file n.py.3]\n[out]\n==\nmain:3: error: Return type \"str\" of \"f\" incompatible with return type \"int\" in supertype \"A\"\n==\nmain:3: error: Return type \"str\" of \"f\" incompatible with return type \"int\" in supertype \"A\"\n\n[case testModifyBaseClassMethodCausingInvalidOverride]\nimport m\nclass B(m.A):\n    def f(self) -> str: pass\n[file m.py]\nclass A:\n    def f(self) -> str: pass\n[file m.py.2]\nclass A:\n    def f(self) -> int: pass\n[out]\n==\nmain:3: error: Return type \"str\" of \"f\" incompatible with return type \"int\" in supertype \"A\"\n\n[case testAddBaseClassAttributeCausingErrorInSubclass]\nimport m\nclass B(m.A):\n    def a(self) -> None:\n        x = 1\n        if int():\n            x = self.x\n\n    def f(self) -> None:\n        self.x = 1\n\n    def z(self) -> None:\n        x = 1\n        if int():\n            x = self.x\n[file m.py]\nclass A: pass\n[file m.py.2]\nclass A:\n    def g(self) -> None:\n        self.x = 'a'\n[out]\n==\nmain:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:9: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nmain:14: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testChangeBaseClassAttributeType]\nimport m\nclass B(m.A):\n    def f(sel) -> None:\n        sel.x = 1\n[file m.py]\nclass A:\n    def g(self) -> None:\n        self.x = 1\n[file m.py.2]\nclass A:\n    def g(self) -> None:\n        self.x = 'a'\n[out]\n==\nmain:4: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testRemoveAttributeInBaseClass]\nimport m\nclass B(m.A):\n    def f(self) -> None:\n        a = 1\n        a = self.x\n[file m.py]\nclass A:\n    def g(self) -> None:\n        self.x = 1\n[file m.py.2]\nclass A: pass\n[out]\n==\nmain:5: error: \"B\" has no attribute \"x\"\n\n[case testTestSignatureOfInheritedMethod]\nimport m\nclass B(m.A):\n    def f(self) -> None:\n        self.g()\n[file m.py]\nclass A:\n    def g(self) -> None: pass\n[file m.py.2]\nclass A:\n    def g(self, a: 'A') -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"a\" in call to \"g\" of \"A\"\n\n[case testRemoveBaseClass]\nimport m\nclass A(m.B):\n    def f(self) -> None:\n        self.g()\n        self.x\n        self.y = 1\n[file m.py]\nclass C:\n    def g(self) -> None:\n        self.x = 1\nclass B(C): pass\n[file m.py.2]\nclass C: pass\nclass B: pass\n[out]\n==\nmain:4: error: \"A\" has no attribute \"g\"\nmain:5: error: \"A\" has no attribute \"x\"\n\n[case testRemoveBaseClass2]\nimport m\nclass A(m.B):\n    def f(self) -> None:\n        self.g()\n        self.x\n        self.y = 1\n[file m.py]\nclass C:\n    def g(self) -> None:\n        self.x = 1\nclass B(C): pass\n[file m.py.2]\nclass C:\n    def g(self) -> None:\n        self.x = 1\nclass B: pass\n[out]\n==\nmain:4: error: \"A\" has no attribute \"g\"\nmain:5: error: \"A\" has no attribute \"x\"\n\n[case testChangeInPackage]\nimport m.n\ndef f() -> None:\n    m.n.g()\n[file m/__init__.py]\n[file m/n.py]\ndef g() -> None: pass\n[file m/n.py.2]\ndef g(x: int) -> None: pass\n[out]\n==\nmain:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testTriggerTargetInPackage]\nimport m.n\n[file m/__init__.py]\n[file m/n.py]\nimport a\ndef f() -> None:\n    a.g()\n[file a.py]\ndef g() -> None: pass\n[file a.py.2]\ndef g(x: int) -> None: pass\n[out]\n==\nm/n.py:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testChangeInPackage__init__]\nimport m\nimport m.n\ndef f() -> None:\n    m.g()\n[file m/__init__.py]\ndef g() -> None: pass\n[file m/__init__.py.2]\ndef g(x: int) -> None: pass\n[file m/n.py]\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testTriggerTargetInPackage__init__]\nimport m\nimport m.n\n[file m/__init__.py]\nimport a\ndef f() -> None:\n    a.g()\n[file a.py]\ndef g() -> None: pass\n[file a.py.2]\ndef g(x: int) -> None: pass\n[file m/n.py]\n[out]\n==\nm/__init__.py:3: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testModuleAttributeTypeChanges]\nimport m\ndef f() -> None:\n    x = 1\n    if int():\n        x = m.x\n[file m.py]\nx = 1\n[file m.py.2]\nx = ''\n[out]\n==\nmain:5: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testTwoStepsDueToModuleAttribute]\nimport m\nx = m.f()\n\ndef g() -> None:\n    y = 1\n    if int():\n        y = x # E\n[file m.py]\ndef f() -> int: pass\n[file m.py.2]\ndef f() -> str: pass\n[out]\n==\nmain:7: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testTwoStepsDueToMultipleNamespaces]\nimport m\nx = m.f()\n\ndef g() -> None:\n    xx = 1\n    if int():\n        xx = x # E\n\nclass A:\n    def a(self) -> None:\n        self.y = m.f()\n    def b(self) -> None:\n        yy = 1\n        if int():\n            yy = self.y\n\nclass B:\n    def c(self) -> None:\n        self.z = m.f()\n    def b(self) -> None:\n        zz = 1\n        if int():\n            zz = self.z\n[file m.py]\ndef f() -> int: pass\n[file m.py.2]\ndef f() -> str: pass\n[out]\n==\nmain:7: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:15: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:23: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testConstructorSignatureChanged]\nimport m\n\ndef f() -> None:\n    m.A()\n[file m.py]\nclass A:\n    def __init__(self) -> None: pass\n[file m.py.2]\nclass A:\n    def __init__(self, x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"A\"\n\n[case testConstructorSignatureChanged2]\nfrom typing import Callable\nimport m\n\ndef use(x: Callable[[], m.A]) -> None:\n    x()\ndef f() -> None:\n    use(m.A)\n[file m.py]\nclass A:\n    def __init__(self) -> None: pass\n[file m.py.2]\nclass A:\n    def __init__(self, x: int) -> None: pass\n[out]\n==\n-- This is a bad error message\nmain:7: error: Argument 1 to \"use\" has incompatible type \"Type[A]\"; expected \"Callable[[], A]\"\n\n[case testConstructorSignatureChanged3]\nfrom a import C\nclass D(C):\n    def g(self) -> None:\n        super().__init__()\nD()\n[file a.py]\nclass C:\n    def __init__(self) -> None: pass\n[file a.py.2]\nclass C:\n    def __init__(self, x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"__init__\" of \"C\"\nmain:5: error: Missing positional argument \"x\" in call to \"D\"\n\n[case testConstructorAdded]\nimport m\n\ndef f() -> None:\n    m.A()\n[file m.py]\nclass A: pass\n[file m.py.2]\nclass A:\n    def __init__(self, x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"A\"\n\n[case testConstructorDeleted]\nimport m\n\ndef f() -> None:\n    m.A(1)\n[file m.py]\nclass A:\n    def __init__(self, x: int) -> None: pass\n[file m.py.2]\nclass A: pass\n[out]\n==\nmain:4: error: Too many arguments for \"A\"\n\n[case testBaseClassConstructorChanged]\nimport m\n\ndef f() -> None:\n    m.B()\n[file m.py]\nclass A:\n    def __init__(self) -> None: pass\nclass B(A): pass\n[file m.py.2]\nclass A:\n    def __init__(self, x: int) -> None: pass\nclass B(A): pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"B\"\n\n[case testSuperField]\nfrom a import C\nclass D(C):\n    def g(self) -> int:\n        return super().x\n[file a.py]\nclass C:\n    def __init__(self) -> None: self.x = 12\n[file a.py.2]\nclass C:\n    def __init__(self) -> None: self.x = 'ar'\n[out]\n==\nmain:4: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testImportFrom]\nfrom m import f\n\ndef g() -> None:\n    f()\n[file m.py]\ndef f() -> None: pass\n[file m.py.2]\ndef f(x: int) -> None: pass\n[builtins fixtures/fine_grained.pyi]\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportFrom2]\nfrom m import f\nf()\n[file m.py]\ndef f() -> None: pass\n[file m.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testImportFromTargetsClass]\nfrom m import C\n\ndef f(c: C) -> None:\n    c.g()\n[file m.py]\nclass C:\n    def g(self) -> None: pass\n[file m.py.2]\nclass C:\n    def g(self, x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"g\" of \"C\"\n\n[case testImportFromTargetsVariable]\nfrom m import x\n\ndef f() -> None:\n    y = 1\n    if int():\n        y = x\n[file m.py]\nx = 1\n[file m.py.2]\nx = ''\n[out]\n==\nmain:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testImportFromSubmoduleOfPackage]\nfrom m import n\n\ndef f() -> None:\n    n.g()\n[file m/__init__.py]\n[file m/n.py]\ndef g() -> None: pass\n[file m/n.py.2]\ndef g(x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"g\"\n\n[case testImportedFunctionGetsImported]\nfrom m import f\n\ndef g() -> None:\n    f()\n[file m.py]\nfrom n import f\n[file n.py]\ndef f() -> None: pass\n[file n.py.2]\ndef f(x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testNestedClassMethodSignatureChanges]\nfrom m import A\n\ndef f(x: A.B) -> None:\n    x.g()\n[file m.py]\nclass A:\n    class B:\n        def g(self) -> None: pass\n[file m.py.2]\nclass A:\n    class B:\n        def g(self, x: int) -> None: pass\n[out]\n==\nmain:4: error: Missing positional argument \"x\" in call to \"g\" of \"B\"\n\n[case testNestedClassAttributeTypeChanges]\nfrom m import A\n\ndef f(x: A.B) -> None:\n    z = 1\n    if int():\n        z = x.y\n[file m.py]\nclass A:\n    class B:\n        def g(self) -> None:\n            self.y = 1\n[file m.py.2]\nclass A:\n    class B:\n        def g(self) -> None:\n            self.y = ''\n[out]\n==\nmain:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testReprocessMethodInNestedClass]\nfrom m import f\n\nclass A:\n    class B:\n        def g(self) -> None:\n            x = 1\n            if int():\n                x = f()\n[file m.py]\ndef f() -> int: pass\n[file m.py.2]\ndef f() -> str: pass\n[file n.py.3]\n[out]\n==\nmain:8: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n==\nmain:8: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testReprocessMethodInNestedClassSemanal]\nimport a\n[file a.py]\nclass A:\n    class B:\n        def g() -> None: pass\n    def foo(self) -> int: return 12\n[file b.py.2]\n[file b.py.3]\n2\n[out]\na.py:3: error: Method must have at least one argument. Did you forget the \"self\" argument?\n==\na.py:3: error: Method must have at least one argument. Did you forget the \"self\" argument?\n==\na.py:3: error: Method must have at least one argument. Did you forget the \"self\" argument?\n\n[case testBaseClassDeleted]\nimport m\n\nclass A(m.C):\n    def f(self) -> None:\n        self.g()  # No error here because m.C becomes an Any base class\n    def g(self) -> None:\n        self.x\n[file m.py]\nclass C:\n    def g(self) -> None: pass\n[file m.py.2]\n[out]\nmain:7: error: \"A\" has no attribute \"x\"\n==\nmain:3: error: Name \"m.C\" is not defined\n\n[case testBaseClassOfNestedClassDeleted]\nimport m\n\nclass A:\n    class B(m.C):\n        def f(self) -> None:\n            self.g()  # No error here because m.C becomes an Any base class\n        def g(self) -> None:\n            self.x\n[file m.py]\nclass C:\n    def g(self) -> None: pass\n[file m.py.2]\n[out]\nmain:8: error: \"B\" has no attribute \"x\"\n==\nmain:4: error: Name \"m.C\" is not defined\n\n[case testImportQualifiedModuleName]\nimport a\n[file a.py]\nimport b.c\nb.c.f()\n[file a.py.2]\nimport b.c\nb.c.f() # dummy change\n[file b/__init__.py]\n[file b/c.py]\ndef f() -> None: pass\n[out]\n==\n\n[case testTypeAliasRefresh]\nfrom typing import Callable\nfrom a import f\nC = Callable[[int], str]\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\n[out]\n==\nmain:2: error: Module \"a\" has no attribute \"f\"\n\n[case testTypeVarRefresh]\nfrom typing import TypeVar\nfrom a import f\nT = TypeVar('T')\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\n[out]\n==\nmain:2: error: Module \"a\" has no attribute \"f\"\n\n[case testRefreshTyping]\nfrom typing import Sized\nfrom c import A\nimport z\n\n# Force typing to get refreshed by using a protocol from it\nx: Sized = A()\n\n[file c.py]\nclass D:\n    def __len__(self) -> int: return 0\nA = D\n[file c.py.2]\nclass C:\n    def __len__(self) -> int: return 0\nA = C\n[file z.py]\nfrom typing import List\nT = List[int]\n[file z.py.2]\nfrom typing import List\nT = List[int]  # yo\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n==\n\n[case testNamedTupleRefresh]\nfrom typing import NamedTuple\nfrom a import f\nN = NamedTuple('N', [('x', int)])\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: Module \"a\" has no attribute \"f\"\n\n[case testModuleLevelAttributeRefresh]\nfrom typing import Callable\nfrom a import f\nx = 1\ny = ''  # type: str\n[file a.py]\ndef f() -> None: pass\n[file a.py.2]\n[out]\n==\nmain:2: error: Module \"a\" has no attribute \"f\"\n\n[case testClassBodyRefresh]\nfrom a import f\nclass A:\n    x = 1\n    y = '' # type: str\n\n    def f(self) -> None:\n        self.x = 1\n[file a.py]\nf = 1\n[file a.py.2]\n[out]\n==\nmain:1: error: Module \"a\" has no attribute \"f\"\n\n[case testDecoratedMethodRefresh]\nfrom typing import Iterator, Callable, List, Optional\nfrom a import f\nimport a\n\ndef dec(f: Callable[['A'], Optional[Iterator[int]]]) -> Callable[[int], int]: pass\n\nclass A:\n    @dec\n    def f(self) -> Optional[Iterator[int]]:\n        self.x = a.g()  # type: int\n        return None\n[builtins fixtures/list.pyi]\n[file a.py]\nf = 1\ndef g() -> int: pass\n[file a.py.2]\ndef f() -> None: pass\ndef g() -> int: pass\n[file a.py.3]\ndef f() -> None: pass\ndef g() -> str: pass\n[out]\n==\n==\nmain:10: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testTwoPassTypeChecking]\nimport a\n[file a.py]\n[file a.py.2]\nclass A:\n    def __init__(self, b: B) -> None:\n        self.a = b.a\n\nclass B:\n    def __init__(self) -> None:\n        self.a = int()\n[file a.py.3]\nclass A:\n    def __init__(self, b: B) -> None:\n        self.a = b.a\n        reveal_type(self.a) # E\n\nclass B:\n    def __init__(self) -> None:\n        self.a = int()\n[out]\n==\n==\na.py:4: note: Revealed type is \"builtins.int\"\n\n[case testStripRevealType]\nimport a\nreveal_type(a.f())\n[file a.py]\ndef f() -> int: pass\n[file a.py.2]\ndef f() -> str: pass\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\n==\nmain:2: note: Revealed type is \"builtins.str\"\n\n[case testDecoratorTypeAfterReprocessing]\nimport a\nreveal_type(a.f())\n[file a.py]\nfrom contextlib import contextmanager\nfrom typing import Iterator\nimport b\n@contextmanager\ndef f() -> Iterator[None]:\n    yield\n[file b.py]\n[delete b.py.2]\n[file b.py.3]\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[triggered]\n2: <b>, <b[wildcard]>, __main__\n3: <b>, <b[wildcard]>, __main__, a\n[out]\nmain:2: note: Revealed type is \"contextlib.GeneratorContextManager[None]\"\n==\nmain:2: note: Revealed type is \"contextlib.GeneratorContextManager[None]\"\na.py:3: error: Cannot find implementation or library stub for module named \"b\"\na.py:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\nmain:2: note: Revealed type is \"contextlib.GeneratorContextManager[None]\"\n\n[case testDecoratorSpecialCase1]\nimport a\n[file a.py]\nimport contextlib\nfrom typing import List, Iterator\n\n@contextlib.contextmanager\ndef f(x: List[int]) -> Iterator[None]:\n    x.append(1)\n    yield\n\ndef g() -> None:\n    import b\n    b.h(1)\n[file b.py]\ndef h() -> None: pass\n[delete b.py.2]\n[file b.py.3]\ndef h() -> None: pass\n[file a.py.4]\nimport contextlib\nfrom typing import List, Iterator\n\n@contextlib.contextmanager\ndef f(x: List[int]) -> Iterator[None]:\n    x.append(1)\n    yield\n\ndef g() -> None:\n    import b\n    b.h(1)\n    pass\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[triggered]\n2: <b.h>, <b>, <b[wildcard]>, a.g\n3: <b.h>, <b>, <b[wildcard]>, a\n4: a.g\n[out]\na.py:11: error: Too many arguments for \"h\"\n==\na.py:10: error: Cannot find implementation or library stub for module named \"b\"\na.py:10: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\na.py:11: error: Too many arguments for \"h\"\n==\na.py:11: error: Too many arguments for \"h\"\n\n[case testDecoratorSpecialCase2]\nimport a\n[file a.py]\nfrom contextlib import contextmanager\nfrom typing import Iterator, List\nimport b\n\n@contextmanager\ndef f(x: List[int]) -> Iterator[None]:\n    x.append(1)\n    yield\n[file b.py]\n[delete b.py.2]\n[file b.py.3]\n[file a.py.4]\nfrom contextlib import contextmanager\nfrom typing import Iterator, List\nimport b\n\n@contextmanager\ndef f(x: List[int]) -> Iterator[None]:\n    x.append(1)\n    yield\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[out]\n==\na.py:3: error: Cannot find implementation or library stub for module named \"b\"\na.py:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n==\n==\n\n[case testDecoratorMethodCompat]\nfrom typing import Callable, List, TypeVar\nimport x\n\nclass Base: pass\n_Base = TypeVar('_Base', bound=Base)\n\ndef dec(f: Callable[[_Base], int]) -> Callable[[_Base], List[int]]: pass\n\nclass B(Base):\n    def foo(self) -> List[int]: pass\n\nclass A(B):\n    @dec\n    def foo(self) -> int:\n        x.lol()\n        return 12\n\n[file x.py]\ndef lol() -> str: pass\n[file x.py.2]\ndef lol() -> int: pass\n[file x.py.3]\ndef lol() -> str: pass\n\n[builtins fixtures/list.pyi]\n[out]\n==\n==\n\n[case testPreviousErrorInDecoratedFunction]\nimport a\n[file a.py]\nfrom typing import Callable\nimport b\n\ndef dec(x: Callable[[], None]) -> Callable[[], None]:\n    return x\n\n@dec\ndef f() -> None:\n    1 + ''\n[file b.py]\n[file b.py.2]\n1\n[file b.py.3]\n2\n[file a.py.4]\nfrom typing import Callable\nimport b\n\ndef dec(f: Callable[[], None]) -> Callable[[], None]:\n    return f\n\n@dec\ndef f() -> None:\n    1 + 2\n[out]\na.py:9: error: Unsupported operand types for + (\"int\" and \"str\")\n==\na.py:9: error: Unsupported operand types for + (\"int\" and \"str\")\n==\na.py:9: error: Unsupported operand types for + (\"int\" and \"str\")\n==\n\n[case testPreviousErrorInDecoratedMethodOverride]\nimport a\n[file a.py]\nfrom typing import Callable\nfrom b import B\n\ndef dec(x: Callable[['A'], int]) -> Callable[['A'], int]:\n    return x\n\nclass A(B):\n    @dec\n    def foo(self) -> int: return 12\n\n[file b.py]\nclass B:\n    def foo(self) -> str: return 'hi'\n[file c.py.2]\n[file c.py.3]\n1\n[file b.py.4]\nclass B:\n    def foo(self) -> int: return 12\n[out]\na.py:9: error: Return type \"int\" of \"foo\" incompatible with return type \"str\" in supertype \"B\"\n==\na.py:9: error: Return type \"int\" of \"foo\" incompatible with return type \"str\" in supertype \"B\"\n==\na.py:9: error: Return type \"int\" of \"foo\" incompatible with return type \"str\" in supertype \"B\"\n==\n\n[case testPreviousErrorInMethodSemanal1]\nimport a\n[file a.py]\nclass A:\n    def foo() -> int: pass\n[file c.py.2]\n[file c.py.3]\n1\n[file a.py.4]\nclass A:\n    def foo(self) -> int: pass\n[out]\na.py:2: error: Method must have at least one argument. Did you forget the \"self\" argument?\n==\na.py:2: error: Method must have at least one argument. Did you forget the \"self\" argument?\n==\na.py:2: error: Method must have at least one argument. Did you forget the \"self\" argument?\n==\n\n[case testPreviousErrorInMethodSemanal2]\nimport a\n[file a.py]\nclass A:\n    def foo(self) -> None:\n        nothing\n[file c.py.2]\n[file c.py.3]\n1\n[file a.py.4]\nclass A:\n    def foo(self) -> int: pass\n[out]\na.py:3: error: Name \"nothing\" is not defined\n==\na.py:3: error: Name \"nothing\" is not defined\n==\na.py:3: error: Name \"nothing\" is not defined\n==\n\n[case testPreviousErrorInMethodSemanalPass3]\nimport a\n[file a.py]\nfrom typing import List\nclass A:\n    def __init__(self) -> None:\n        self.x = []  # type: List[int, str]\n[file c.py.2]\n[file c.py.3]\n1\n[file a.py.4]\nfrom typing import List\nclass A:\n    def __init__(self) -> None:\n        self.x = []  # type: List[int]\n[builtins fixtures/list.pyi]\n[out]\na.py:4: error: \"list\" expects 1 type argument, but 2 given\n==\na.py:4: error: \"list\" expects 1 type argument, but 2 given\n==\na.py:4: error: \"list\" expects 1 type argument, but 2 given\n==\n\n[case testPreviousErrorInOverloadedFunctionSemanalPass3]\nimport a\n[file a.py]\nfrom typing import overload, List\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> List[int, str]: ...\ndef f(x: object) -> object:\n    pass\n[file c.py.2]\n[file c.py.3]\n1\n[file a.py.4]\nfrom typing import overload, List\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> List[int]: ...\ndef f(x: object) -> object:\n    pass\n[builtins fixtures/list.pyi]\n[out]\na.py:5: error: \"list\" expects 1 type argument, but 2 given\n==\na.py:5: error: \"list\" expects 1 type argument, but 2 given\n==\na.py:5: error: \"list\" expects 1 type argument, but 2 given\n==\n\n[case testPreviousErrorInOverloadedFunction]\nimport a\n[file a.py]\nfrom typing import overload\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> int: ...\ndef f(x: object) -> None:\n\tpass\n[file b.py]\n[file b.py.2]\n1\n[file b.py.3]\n2\n[file a.py.4]\nfrom typing import overload\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> None: ...\ndef f(x: object) -> None:\n\tpass\n[out]\na.py:6: error: Overloaded function implementation cannot produce return type of signature 2\n==\na.py:6: error: Overloaded function implementation cannot produce return type of signature 2\n==\na.py:6: error: Overloaded function implementation cannot produce return type of signature 2\n==\n\n[case testPreviousErrorInOverloadedFunctionSemanal]\nimport a\n[file a.py]\nfrom typing import overload\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> None: ...\n[file b.py]\n[file b.py.2]\n1\n[file b.py.3]\n2\n[file a.py.4]\nfrom typing import overload\n@overload\ndef f(x: str) -> None: ...\n@overload\ndef f(x: int) -> None: ...\ndef f(x: object) -> None:\n\tpass\n[out]\na.py:2: error: An overloaded function outside a stub file must have an implementation\n==\na.py:2: error: An overloaded function outside a stub file must have an implementation\n==\na.py:2: error: An overloaded function outside a stub file must have an implementation\n==\n\n[case testPreviousErrorInDecoratedMethodSemanalPass3]\nimport a\n[file a.py]\nfrom typing import Callable, TypeVar, Any, List\n\nT = TypeVar('T', bound=Callable)\ndef dec(x: T) -> T:\n    return x\n\n@dec\ndef foo(self) -> List[str, int]: return []\n\n[file c.py.2]\n[file c.py.3]\n[file a.py.4]\nfrom typing import Callable, TypeVar, Any, List\n\nT = TypeVar('T', bound=Callable[..., Any])\ndef dec(x: T) -> T:\n    return x\n\n@dec\ndef foo(self) -> List[str]: return []\n[builtins fixtures/list.pyi]\n[out]\na.py:8: error: \"list\" expects 1 type argument, but 2 given\n==\na.py:8: error: \"list\" expects 1 type argument, but 2 given\n==\na.py:8: error: \"list\" expects 1 type argument, but 2 given\n==\n\n[case testDecoratorUpdateMod]\nimport a\n[file a.py]\nimport mod\n\n@mod.deca\n@mod.decb(mod.C())\ndef func(x: mod.B) -> mod.B:\n    x.x\n    return x\n[file mod.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[B], B]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    x: int\n[file mod.py.2]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[str], str]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    x: int\n[file mod.py.3]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[B], B]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    y: int\n[file mod.py.4]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[B], B]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    def __init__(self, x: int) -> None:\n        pass\nclass B:\n    x: int\n[out]\n==\na.py:3: error: Argument 1 to \"deca\" has incompatible type \"Callable[[B], B]\"; expected \"Callable[[str], str]\"\n==\na.py:6: error: \"B\" has no attribute \"x\"\n==\na.py:4: error: Missing positional argument \"x\" in call to \"C\"\n\n[case testDecoratorUpdateFunc]\nimport a\n[file a.py]\nimport mod\n\ndef outer() -> None:\n    @mod.deca\n    @mod.decb(mod.C())\n    def func(x: mod.B) -> mod.B:\n        x.x\n        return x\n[file mod.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[B], B]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    x: int\n[file mod.py.2]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[str], str]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    x: int\n[file mod.py.3]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[B], B]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    y: int\n[file mod.py.4]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[[B], B]) -> Callable[[str], str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    def __init__(self, x: int) -> None:\n        pass\nclass B:\n    x: int\n[out]\n==\na.py:4: error: Argument 1 to \"deca\" has incompatible type \"Callable[[B], B]\"; expected \"Callable[[str], str]\"\n==\na.py:7: error: \"B\" has no attribute \"x\"\n==\na.py:5: error: Missing positional argument \"x\" in call to \"C\"\n\n[case DecoratorUpdateMethod]\nimport a\n[file a.py]\nimport mod\n\nclass D:\n    @mod.deca\n    @mod.decb(mod.C())\n    def func(self, x: mod.B) -> mod.B:\n        x.x\n        return x\n[file mod.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[..., B]) -> Callable[..., str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    x: int\n[file mod.py.2]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[..., str]) -> Callable[..., str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    x: int\n[file mod.py.3]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[..., B]) -> Callable[..., str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    pass\nclass B:\n    y: int\n[file mod.py.4]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\n\ndef deca(func: Callable[..., B]) -> Callable[..., str]:\n    pass\ndef decb(arg: C) -> Callable[[F], F]:\n    pass\nclass C:\n    def __init__(self, x: int) -> None:\n        pass\nclass B:\n    x: int\n[out]\n==\na.py:4: error: Argument 1 to \"deca\" has incompatible type \"Callable[[D, B], B]\"; expected \"Callable[..., str]\"\n==\na.py:7: error: \"B\" has no attribute \"x\"\n==\na.py:5: error: Missing positional argument \"x\" in call to \"C\"\n\n[case testDecoratorUpdateDeepNested]\nimport a\n[file a.py]\nimport mod\n\ndef outer() -> None:\n    def inner() -> None:\n        @mod.dec\n        def func(x: int) -> int:\n            pass\n[file mod.py]\nfrom typing import Callable\ndef dec(func: Callable[[int], int]) -> Callable[[str], str]:\n    pass\n[file mod.py.2]\nfrom typing import Callable\ndef dec(func: Callable[[str], str]) -> Callable[[str], str]:\n    pass\n[out]\n==\na.py:5: error: Argument 1 to \"dec\" has incompatible type \"Callable[[int], int]\"; expected \"Callable[[str], str]\"\n\n[case testDecoratorUpdateNestedClass]\nimport a\n[file a.py]\nimport mod\n\nclass Outer:\n    class Inner:\n        c = mod.C()\n        @c.dec\n        def func(self, x: int) -> int:\n            pass\n[file mod.py]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., int]) -> Callable[..., str]:\n        pass\n[file mod.py.2]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., str]) -> Callable[..., str]:\n        pass\n[out]\n==\na.py:6: error: Argument 1 to \"dec\" of \"C\" has incompatible type \"Callable[[Inner, int], int]\"; expected \"Callable[..., str]\"\n\n[case testDecoratorUpdateClassInFunction]\nimport a\n[file a.py]\nimport mod\n\ndef outer() -> None:\n    class Inner:\n        c = mod.C()\n        @c.dec\n        def func(self, x: mod.B) -> int:\n            return x.x\n[file mod.py]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., int]) -> Callable[..., str]:\n        pass\nclass B:\n    x: int\n[file mod.py.2]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., str]) -> Callable[..., str]:\n        pass\nclass B:\n    x: int\n[file mod.py.3]\nfrom typing import Callable\nclass C:\n    def dec(self, func: Callable[..., int]) -> Callable[..., str]:\n        pass\nclass B:\n    x: str\n[out]\n==\na.py:6: error: Argument 1 to \"dec\" of \"C\" has incompatible type \"Callable[[Inner, B], int]\"; expected \"Callable[..., str]\"\n==\na.py:8: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testDecoratorUpdateMROUpdated]\nimport a\n[file a.py]\nimport mod\n\n@mod.dec\ndef func(x: mod.B) -> int:\n    pass\n[file mod.py]\nfrom typing import Callable\nclass B:\n    pass\nclass C(B):\n    pass\ndef dec(f: Callable[[C], int]) -> Callable[[int], int]:\n    pass\n[file mod.py.2]\nfrom typing import Callable\nclass B:\n    pass\nclass C:\n    pass\ndef dec(f: Callable[[C], int]) -> Callable[[int], int]:\n    pass\n[out]\n==\na.py:3: error: Argument 1 to \"dec\" has incompatible type \"Callable[[B], int]\"; expected \"Callable[[C], int]\"\n\n[case testOverloadRefresh]\nfrom typing import overload\nimport m\n\n@overload\ndef f(x: m.A) -> None: ...\n@overload\ndef f(x: int) -> None: ...\ndef f(x: object) -> None:\n    from n import g\n[file m.py]\nclass A: pass\n[file n.py]\ndef g() -> None: pass\n[delete m.py.2]\n[delete n.py.2]\n[out]\n==\nmain:2: error: Cannot find implementation or library stub for module named \"m\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:7: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\nmain:9: error: Cannot find implementation or library stub for module named \"n\"\n\n[case testOverloadSpecialCase]\nfrom typing import overload\nimport m\nimport sys\n\nclass C:\n    if sys.platform == 'nonexistent':\n        def f(self, x): pass\n    else:\n        @overload\n        def f(self, x: m.A) -> None: pass\n        @overload\n        def f(self, x: int) -> None: pass\n        def f(self, x: object) -> None:\n            from n import g\n[file m.py]\nclass A: pass\n[file n.py]\ndef g() -> None: pass\n[delete m.py.2]\n[delete n.py.2]\n[builtins fixtures/ops.pyi]\n[out]\n==\nmain:2: error: Cannot find implementation or library stub for module named \"m\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:12: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\nmain:14: error: Cannot find implementation or library stub for module named \"n\"\n\n[case testOverloadClassmethodDisappears]\nfrom typing import overload\nfrom m import Wrapper\nreveal_type(Wrapper.foo(3))\n[file m.pyi]\nfrom typing import overload\nclass Wrapper:\n    @overload\n    @classmethod\n    def foo(self, x: int) -> int: ...\n    @overload\n    @classmethod\n    def foo(self, x: str) -> str: ...\n[file m.pyi.2]\nfrom typing import overload\nclass Wrapper:\n    @overload\n    def foo(cls, x: int) -> int: ...\n    @overload\n    def foo(cls, x: str) -> str: ...\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:3: note: Revealed type is \"builtins.int\"\n==\nmain:3: error: No overload variant of \"foo\" of \"Wrapper\" matches argument type \"int\"\nmain:3: note: Possible overload variants:\nmain:3: note:     def foo(cls: Wrapper, x: int) -> int\nmain:3: note:     def foo(cls: Wrapper, x: str) -> str\nmain:3: note: Revealed type is \"Any\"\n\n[case testRefreshGenericClass]\nfrom typing import TypeVar, Generic\nfrom a import A\n\nX = TypeVar('X')\n\nclass C(Generic[X]):\n    def f(self, x: A) -> X: ...\n[file a.py]\nclass A: pass\n[file a.py.2]\n[file a.py.3]\nclass A: pass\n[out]\n==\nmain:2: error: Module \"a\" has no attribute \"A\"\n==\n\n[case testRefreshGenericAndFailInPass3]\n# Failure in semantic analysis pass 3\nfrom a import C\na: C[int]\n[file a.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]): pass\n[file a.py.2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass C(Generic[T, S]): pass\n[file a.py.3]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]): pass\n[out]\n==\nmain:3: error: \"C\" expects 2 type arguments, but 1 given\n==\n\n[case testUnannotatedClass]\nimport a\n[file a.py]\nclass A:\n    def f(self, x):\n        self.y = x\n        self.g()\n\n    def g(self): pass\n[file a.py.2]\nclass A:\n    def f(self, x, y):\n        self.y = x\n        self.z = y\n        self.g()\n\n    def g(self): pass\n[triggered]\n2: <a.A.f>, <a.A.z>, <a.A[wildcard]>\n[out]\n==\n\n[case testSuperBasics]\nimport a\n[file a.py]\nclass A:\n    def f(self) -> None: pass\nclass B(A):\n    def f(self) -> None:\n        super(B, self).f()\n[file a.py.2]\nclass A:\n    def f(self) -> None: pass\nclass B(A):\n    def f(self) -> None:\n        super(B, self).f()\n[out]\n==\n\n[case testErrorInTypeCheckSecondPassThroughPropagation]\nimport a\n\ndef f() -> None:\n    x = a.C()\n[file a.py]\n[file a.py.2]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass C(Generic[T]): pass\n[out]\nmain:4: error: \"object\" has no attribute \"C\"\n==\nmain:4: error: Need type annotation for \"x\"\n\n[case testPartialTypeInNestedClass]\nimport a\nclass C:\n    def f(self) -> None:\n        a.g()\n        class D:\n            def __init__(self) -> None:\n                self.x = {}\n            def meth(self) -> None:\n                self.x['a'] = 'b'\n[file a.py]\ndef g() -> None: pass\n[file a.py.2]\ndef g() -> int: pass\n[builtins fixtures/dict.pyi]\n[out]\nmain:7: error: Need type annotation for \"x\" (hint: \"x: Dict[<type>, <type>] = ...\")\n==\nmain:7: error: Need type annotation for \"x\" (hint: \"x: Dict[<type>, <type>] = ...\")\n\n[case testRefreshPartialTypeInClass]\nimport a\nclass D:\n    def __init__(self) -> None:\n        a.g()\n        self.x = {}\n    def meth(self) -> None:\n        self.x['a'] = 'b'\n[file a.py]\ndef g() -> None: pass\n[file a.py.2]\ndef g() -> int: pass\n[builtins fixtures/dict.pyi]\n[out]\nmain:5: error: Need type annotation for \"x\" (hint: \"x: Dict[<type>, <type>] = ...\")\n==\nmain:5: error: Need type annotation for \"x\" (hint: \"x: Dict[<type>, <type>] = ...\")\n\n[case testRefreshPartialTypeInferredAttributeIndex]\nfrom c import C\nreveal_type(C().a)\n[file c.py]\nfrom b import f\nclass C:\n    def __init__(self) -> None:\n        self.a = {}\n        if bool():\n            self.a[0] = f()\n[file b.py]\ndef f() -> int: ...\n[file b.py.2]\nfrom typing import List\ndef f() -> str: ...\n[builtins fixtures/dict.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.dict[builtins.int, builtins.int]\"\n==\nmain:2: note: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\n[case testRefreshPartialTypeInferredAttributeAssign]\nfrom c import C\nreveal_type(C().a)\n[file c.py]\nfrom b import f\nclass C:\n    def __init__(self) -> None:\n        self.a = []\n        if bool():\n            self.a = f()\n[file b.py]\nfrom typing import List\ndef f() -> List[int]: ...\n[file b.py.2]\nfrom typing import List\ndef f() -> List[str]: ...\n[builtins fixtures/list.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.list[builtins.int]\"\n==\nmain:2: note: Revealed type is \"builtins.list[builtins.str]\"\n\n[case testRefreshPartialTypeInferredAttributeAppend]\nfrom c import C\nreveal_type(C().a)\n[file c.py]\nfrom b import f\nclass C:\n    def __init__(self) -> None:\n        self.a = []\n        if bool():\n            self.a.append(f())\n[file b.py]\ndef f() -> int: ...\n[file b.py.2]\ndef f() -> str: ...\n[builtins fixtures/list.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.list[builtins.int]\"\n==\nmain:2: note: Revealed type is \"builtins.list[builtins.str]\"\n\n[case testRefreshTryExcept]\nimport a\ndef f() -> None:\n    a.g()\n    try:\n        pass\n    except BaseException as e:\n        e\n[file a.py]\ndef g() -> int: pass\n[file a.py.2]\ndef g() -> str: pass\n[builtins fixtures/exception.pyi]\n[out]\n==\n\n[case testMroSpecialCase]\nimport b\nimport a\n\n[file a.py]\nclass C: pass\nclass D(C):\n    1()\nclass E(D): pass\n\n[file b.py]\nimport a\n\n[file a.py.2]\nclass C: pass\nclass D(C):\n    1()\nclass E(D): pass\n# Something needs to change\n\n[file b.py.2]\nimport a\n# Something needs to change\n\n[triggered]\n2: a, a\n[out]\na.py:3: error: \"int\" not callable\n==\na.py:3: error: \"int\" not callable\n\n[case testMetaclassAttributes]\nimport a\n[file a.py]\nfrom mod import C\nfrom typing import Type\ndef f(arg: Type[C]) -> None:\n    arg.x = int()\n[file mod.py]\nimport submod\nclass C(metaclass=submod.M):\n    pass\n[file submod.py]\nclass M(type):\n    x: int\n[file submod.py.2]\nclass M(type):\n    x: str\n[file submod.py.3]\nclass M(type):\n    y: str\n[file submod.py.4]\nclass M(type):\n    x: int\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n==\na.py:4: error: \"Type[C]\" has no attribute \"x\"\n==\n\n[case testMetaclassAttributesDirect]\nimport a\n[file a.py]\nfrom mod import C\ndef f() -> None:\n    C.x = int()\n[file mod.py]\nimport submod\nclass C(metaclass=submod.M):\n    pass\n[file submod.py]\nclass M(type):\n    x: int\n[file submod.py.2]\nclass M(type):\n    x: str\n[file submod.py.3]\nclass M(type):\n    y: str\n[file submod.py.4]\nclass M(type):\n    x: int\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n==\na.py:3: error: \"Type[C]\" has no attribute \"x\"\n==\n\n[case testMetaclassOperators]\nimport a\n[file a.py]\nfrom mod import C\nfrom typing import Type\ndef f(arg: Type[C]) -> None:\n    arg + arg\n[file mod.py]\nimport submod\nclass C(metaclass=submod.M):\n    pass\n[file submod.py]\nclass M(type):\n    def __add__(self, other: M) -> M:\n        pass\n[file submod.py.2]\nclass M(type):\n    def __add__(self, other: int) -> M:\n        pass\n[out]\n==\na.py:4: error: Unsupported operand types for + (\"Type[C]\" and \"Type[C]\")\n\n[case testMetaclassOperatorsDirect]\nimport a\n[file a.py]\nfrom mod import C\ndef f() -> None:\n    C + C\n[file mod.py]\nimport submod\nclass C(metaclass=submod.M):\n    pass\n[file submod.py]\nclass M(type):\n    def __add__(self, other: int) -> M:\n        pass\n[file submod.py.2]\nclass M(type):\n    def __add__(self, other: M) -> M:\n        pass\n[out]\na.py:3: error: Unsupported operand types for + (\"Type[C]\" and \"Type[C]\")\n==\n\n[case testFineMetaclassUpdate]\nimport a\n[file a.py]\nfrom c import M\nimport b\ndef f(arg: M) -> None:\n    pass\n\nf(b.B)\n[file b.py]\nimport c\nclass B: pass\n\n[file b.py.2]\nimport c\nclass B(metaclass=c.M): pass\n\n[file c.py]\nclass M(type):\n    pass\n[out]\na.py:6: error: Argument 1 to \"f\" has incompatible type \"Type[B]\"; expected \"M\"\n==\n\n[case testFineMetaclassRecalculation]\nimport a\n[file a.py]\nfrom b import B\nclass M2(type): pass\nclass D(B, metaclass=M2): pass\n[file b.py]\nimport c\nclass B: pass\n\n[file b.py.2]\nimport c\nclass B(metaclass=c.M): pass\n\n[file c.py]\nclass M(type):\n    pass\n[out]\n==\na.py:3: error: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases\n\n[case testFineMetaclassDeclaredUpdate]\nimport a\n[file a.py]\nimport b\nclass B(metaclass=b.M): pass\nclass D(B, metaclass=b.M2): pass\n[file b.py]\nclass M(type): pass\nclass M2(M): pass\n[file b.py.2]\nclass M(type): pass\nclass M2(type): pass\n[out]\n==\na.py:3: error: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases\n\n[case testFineMetaclassRemoveFromClass]\nimport a\n[file a.py]\nimport b\ndef func() -> int:\n    return b.B.x\n[file b.py]\nfrom c import M\nclass B(metaclass=M):\n    pass\n[file b.py.2]\nfrom c import M\nclass B:\n    pass\n[file c.py]\nclass M(type):\n    x: int\n[out]\n==\na.py:3: error: \"Type[B]\" has no attribute \"x\"\n\n[case testFineMetaclassRemoveFromClass2]\nimport a\n[file a.py]\nimport b\ndef func() -> None:\n    b.test(b.B)\n[file b.py]\nimport c\ndef test(cls: c.M) -> None:\n    pass\nclass B(metaclass=c.M):\n    pass\n[file b.py.2]\nimport c\ndef test(cls: c.M) -> None:\n    pass\nclass B:\n    pass\n[file c.py]\nclass M(type):\n    x: int\n[out]\n==\na.py:3: error: Argument 1 to \"test\" has incompatible type \"Type[B]\"; expected \"M\"\n\n[case testBadMetaclassCorrected]\nimport a\n[file a.py]\nimport b\nclass C(metaclass=b.M):\n    pass\n[file b.py]\nfrom c import M\n[file c.py]\nM = 1\n[file c.py.2]\nclass M(type):\n    pass\n[out]\na.py:2: error: Invalid metaclass \"b.M\"\n==\n\n[case testFixedAttrOnAddedMetaclass]\nimport a\n[file a.py]\nimport b\ndef fun() -> None:\n    x: int = b.C.x\n[file b.py]\nimport c\nclass C:\n    pass\n[file b.py.2]\nimport c\nclass C(metaclass=c.M):\n    pass\n[file c.py]\nclass M(type):\n    x: int\n[out]\na.py:3: error: \"Type[C]\" has no attribute \"x\"\n==\n\n[case testIndirectSubclassReferenceMetaclass]\nimport a\n[file a.py]\nimport b\ndef f() -> None:\n    b.x = int()\n[file b.py]\nimport bb\nx = bb.D.x\n[file bb.py]\nimport mod\nclass D(mod.C):\n    pass\n[file mod.py]\nimport submod\nclass C(metaclass=submod.M):\n    pass\n[file submod.py]\nclass M(type):\n    x: int\n[file submod.py.2]\nclass M(type):\n    x: str\n[file submod.py.3]\nclass M(type):\n    y: str\n[file submod.py.4]\nclass M(type):\n    x: int\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n==\nb.py:2: error: \"Type[D]\" has no attribute \"x\"\n==\n\n[case testMetaclassDeletion]\nimport a\n[file a.py]\nimport b\ndef func() -> None:\n    b.B.x\n[file b.py]\nimport c\nclass B(metaclass=c.M):\n    pass\n[file c.py]\nclass M(type):\n    x: int\n[file c.py.2]\nwhatever: int\n[out]\n==\nb.py:2: error: Name \"c.M\" is not defined\n\n[case testFixMissingMetaclass]\nimport a\n[file a.py]\nimport b\ndef func() -> None:\n    b.B.x\n[file b.py]\nimport c\nclass B(metaclass=c.M):\n    pass\n[file c.py]\nwhatever: int\n[file c.py.2]\nclass M(type):\n    x: int\n[out]\nb.py:2: error: Name \"c.M\" is not defined\n==\n\n[case testGoodMetaclassSpoiled]\nimport a\n[file a.py]\nimport b\nclass C(metaclass=b.M):\n    pass\n[file b.py]\nclass M(type):\n    pass\n[file b.py.2]\nM = 1\n[out]\n==\na.py:2: error: Invalid metaclass \"b.M\"\n\n[case testRefreshGenericSubclass]\nfrom typing import Generic, TypeVar\nimport m\nm.x\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None:\n        pass\n\nclass D(C[T]):\n    def __init__(self, x: T) -> None:\n        m.x\n        super(D, self).__init__(x)\n[file m.py]\nx = 0\n[file m.py.2]\nx = ''\n[out]\n==\n\n[case testRefreshNamedTupleSubclass]\nfrom typing import NamedTuple\nimport m\nm.x\n\nN = NamedTuple('N', [('x', int)])\n\nclass C(N):\n    pass\n[file m.py]\nx = 0\n[file m.py.2]\nx = ''\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNewTypeRefresh]\nimport a\n\n[file a.py]\nfrom typing import Dict, NewType\n\nclass A: pass\nN = NewType('N', A)\n\na: Dict[N, int]\n\ndef f(self, x: N) -> None:\n    a.get(x)\n\n[file a.py.2]\nfrom typing import Dict, NewType  # dummy change\n\nclass A: pass\nN = NewType('N', A)\n\na: Dict[N, int]\n\ndef f(self, x: N) -> None:\n    a.get(x)\n\n[builtins fixtures/dict.pyi]\n[out]\n==\n\n[case testRefreshFunctionalEnum]\nimport a\n\n[file a.py]\nfrom typing import Dict\nfrom enum import Enum\n\nN = Enum('N', 'x')\na: Dict[N, int]\n\ndef f(self, x: N) -> None:\n    a.get(x)\n\n[file a.py.2]\nfrom typing import Dict\nfrom enum import Enum\n\nN = Enum('N', 'x')\na: Dict[N, int]\n\ndef f(self, x: N) -> None:\n    a.get(x)\n[builtins fixtures/dict.pyi]\n[out]\n==\n\n[case testFineGrainedCallable]\nimport a\n[file a.py]\ndef f(o: object) -> None:\n    if callable(o):\n        o()\n[file a.py.2]\ndef f(o: object) -> None:\n    if callable(o):\n        o()\n[builtins fixtures/callable.pyi]\n[out]\n==\n\n[case testRefreshFunctionalNamedTuple]\nimport a\n\n[file a.py]\nfrom typing import NamedTuple\nfrom b import L\n\nA = NamedTuple('A', [])\na: A\n\ndef g() -> None:\n    x = L(A())\n    x.f(a)\n\n[file b.pyi]\nfrom typing import TypeVar, Generic, overload\n\nT = TypeVar('T')\n\nclass L(Generic[T]):\n    def __init__(self, x: T) -> None: pass\n    @overload\n    def f(self) -> None: pass\n    @overload\n    def f(self, a: T) -> None: pass\n\n[file a.py.2]\nfrom typing import NamedTuple\nfrom b import L\n\nA = NamedTuple('A', [])\na: A\n\ndef g() -> None:\n    x = L(A())\n    x.f(a)\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testRefreshSubclassNestedInFunction1]\nfrom a import C\ndef f() -> None:\n    class D(C): pass\n[file a.py]\nclass C: pass\n[file a.py.2]\n[out]\n==\nmain:1: error: Module \"a\" has no attribute \"C\"\n\n[case testRefreshSubclassNestedInFunction2]\nfrom a import C\ndef f() -> None:\n    class D(C):\n        def g(self) -> None:\n            super().__init__()\n    d = D()\n[file a.py]\nclass C:\n    def __init__(self) -> None: pass\n[file a.py.2]\nclass C:\n    def __init__(self, x: int) -> None: pass\n[out]\n==\nmain:5: error: Missing positional argument \"x\" in call to \"__init__\" of \"C\"\nmain:6: error: Missing positional argument \"x\" in call to \"D\"\n\n[case testInferAttributeTypeAndMultipleStaleTargets]\nimport a\n\nclass A:\n    def g(self) -> None:\n        a.x\n        self.x = 1\n\n    def f(self) -> None:\n        a.x\n        b = self.x\n        self.x = 1\n\n[file a.py]\nx = 0\n[file a.py.2]\nx = ''\n[out]\n==\n\n[case testNamedTupleUpdate]\nimport b\n[file a.py]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int)])\nx = N(1)\n[file a.py.2]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', str)])\nx = N('hi')\n[file b.py]\nimport a\ndef f(x: a.N) -> None:\n    pass\nf(a.x)\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNamedTupleUpdate2]\nimport b\n[file a.py]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int)])\nx = N(1)\n[file a.py.2]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('y', int)])\nx = N(2)\n[file b.py]\nimport a\ndef f(x: a.N) -> None:\n    pass\nf(a.x)\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNamedTupleUpdate3]\nimport c\n[file a.py]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', int)])\nx = N(1)\n[file a.py.2]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('x', str)])\nx = N('hi')\n[file b.py]\nimport a\nfrom typing import NamedTuple\nM = NamedTuple('M', [('z', 'a.N')])\nx = M(a.x)\n[file c.py]\nimport a\nimport b\nfrom typing import Tuple\ndef lol(n: Tuple[Tuple[int]]) -> None:\n    pass\ndef f(x: b.M) -> None:\n    lol(x)\nf(b.x)\nlol(b.x)\n[builtins fixtures/tuple.pyi]\n[out]\n==\nc.py:7: error: Argument 1 to \"lol\" has incompatible type \"M\"; expected \"Tuple[Tuple[int]]\"\nc.py:9: error: Argument 1 to \"lol\" has incompatible type \"M\"; expected \"Tuple[Tuple[int]]\"\n\n[case testNamedTupleUpdate4]\nimport b\n[file a.py]\nfrom typing import NamedTuple\nclass N(NamedTuple):\n    x: int\nx = N(1)\n[file a.py.2]\nfrom typing import NamedTuple\nclass N(NamedTuple):\n    x: str\nx = N('hi')\n[file b.py]\nimport a\ndef f(x: a.N) -> None:\n    pass\nf(a.x)\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNamedTupleUpdate5]\nimport b\n[file a.py]\nfrom typing import NamedTuple, Optional\nclass N(NamedTuple):\n    r: Optional[N]\n    x: int\nx = N(None, 1)\n[file a.py.2]\nfrom typing import NamedTuple, Optional\nclass N(NamedTuple):\n    r: Optional[N]\n    x: str\nx = N(None, 'hi')\n[file b.py]\nimport a\ndef f(x: a.N) -> None:\n    pass\nf(a.x)\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNamedTupleUpdateGeneric]\nimport b\n[file a.py]\nfrom typing import NamedTuple\nclass Point(NamedTuple):\n    x: int\n    y: int\n[file a.py.2]\nfrom typing import Generic, TypeVar, NamedTuple\n\nT = TypeVar(\"T\")\nclass Point(NamedTuple, Generic[T]):\n    x: int\n    y: T\n[file b.py]\nfrom a import Point\ndef foo() -> None:\n    p = Point(x=0, y=1)\n    i: int = p.y\n[file b.py.3]\nfrom a import Point\ndef foo() -> None:\n    p = Point(x=0, y=\"no\")\n    i: int = p.y\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\nb.py:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testNamedTupleUpdateNonRecursiveToRecursiveFine]\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==\n==\nc.py:4: note: Revealed type is \"Tuple[Union[Tuple[Union[..., None], builtins.int, fallback=b.M], None], builtins.int, fallback=a.N]\"\nc.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", variable has type \"int\")\nc.py:7: note: Revealed type is \"Tuple[Union[Tuple[Union[..., None], builtins.int, fallback=b.M], None], builtins.int, fallback=a.N]\"\n\n[case testTupleTypeUpdateNonRecursiveToRecursiveFine]\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==\n==\nc.py:4: note: Revealed type is \"Tuple[Union[Tuple[Union[..., None], builtins.int, fallback=b.M], None], builtins.int, fallback=a.N]\"\nc.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", variable has type \"int\")\n\n[case testTypeAliasUpdateNonRecursiveToRecursiveFine]\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==\n==\nc.py:4: note: Revealed type is \"Tuple[Union[Tuple[Union[..., None], builtins.int], None], builtins.int]\"\nc.py:5: error: Incompatible types in assignment (expression has type \"Optional[N]\", variable has type \"int\")\n\n[case testTypedDictRefresh]\n[builtins fixtures/dict.pyi]\nimport a\n[file a.py]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\n[file a.py.2]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337)) # dummy change\n[out]\n==\n\n[case testTypedDictUpdate]\nimport b\n[file a.py]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(dict(x=42, y=1337))\n[file a.py.2]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': str})\np = Point(dict(x=42, y='lurr'))\n[file b.py]\nfrom a import Point\ndef foo(x: Point) -> int:\n    return x['x'] + x['y']\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testTypedDictUpdate2]\nimport b\n[file a.py]\nfrom mypy_extensions import TypedDict\nclass Point(TypedDict):\n    x: int\n    y: int\np = Point(dict(x=42, y=1337))\n[file a.py.2]\nfrom mypy_extensions import TypedDict\nclass Point(TypedDict):\n    x: int\n    y: str\np = Point(dict(x=42, y='lurr'))\n[file b.py]\nfrom a import Point\ndef foo(x: Point) -> int:\n    return x['x'] + x['y']\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testTypedDictUpdate3]\nimport b\n[file a.py]\nfrom mypy_extensions import TypedDict\nfrom typing import Optional\nclass Point(TypedDict):\n    x: Optional[Point]\n    y: int\n    z: int\np = Point(dict(x=None, y=1337, z=0))\n[file a.py.2]\nfrom mypy_extensions import TypedDict\nfrom typing import Optional\nclass Point(TypedDict):\n    x: Optional[Point]\n    y: str\n    z: int\np = Point(dict(x=None, y='lurr', z=0))\n[file b.py]\nfrom a import Point\ndef foo(x: Point) -> int:\n    assert x['x'] is not None\n    return x['x']['z'] + x['x']['y']\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:4: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testTypedDictUpdateGeneric]\nimport b\n[file a.py]\nfrom mypy_extensions import TypedDict\nclass Point(TypedDict):\n    x: int\n    y: int\n[file a.py.2]\nfrom mypy_extensions import TypedDict\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass Point(TypedDict, Generic[T]):\n    x: int\n    y: T\n[file b.py]\nfrom a import Point\ndef foo() -> None:\n    p = Point(x=0, y=1)\n    i: int = p[\"y\"]\n[file b.py.3]\nfrom a import Point\ndef foo() -> None:\n    p = Point(x=0, y=\"no\")\n    i: int = p[\"y\"]\n[builtins fixtures/dict.pyi]\n[out]\n==\n==\nb.py:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testTypedDictUpdateReadOnly]\nimport b\n[file a.py]\nfrom typing_extensions import TypedDict, ReadOnly\nPoint = TypedDict('Point', {'x': int, 'y': int})\np = Point(x=1, y=2)\n[file a.py.2]\nfrom typing_extensions import TypedDict, ReadOnly\nclass Point(TypedDict):\n    x: int\n    y: ReadOnly[int]\np = Point(x=1, y=2)\n[file a.py.3]\nfrom typing_extensions import TypedDict, ReadOnly\nPoint = TypedDict('Point', {'x': ReadOnly[int], 'y': int})\np = Point(x=1, y=2)\n[file b.py]\nfrom a import Point\ndef foo(x: Point) -> None:\n    x['x'] = 1\n    x['y'] = 2\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:4: error: ReadOnly TypedDict key \"y\" TypedDict is mutated\n==\nb.py:3: error: ReadOnly TypedDict key \"x\" TypedDict is mutated\n\n[case testBasicAliasUpdate]\nimport b\n[file a.py]\nN = int\nx = 1\n[file a.py.2]\nN = str\nx = 'hi'\n[file b.py]\nimport a\ndef f(x: a.N) -> None:\n    pass\nf(a.x)\n[out]\n==\n\n[case testBasicAliasUpdateGeneric]\nimport b\n[file a.py]\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nD = Dict[int, T]\nx = {1: 1}\n[file a.py.2]\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nD = Dict[str, T]\nx = {'hi': 1}\n[file b.py]\nimport a\ndef f(x: a.D[int]) -> None:\n    pass\nf(a.x)\n[builtins fixtures/dict.pyi]\n[out]\n==\n\n[case testAliasFineNormalMod]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nA = str\n[file b.py]\nimport a\nx: a.A = int()\n[out]\n==\nb.py:2: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineNormalFunc]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nA = str\n[file b.py]\nimport a\ndef f(x: a.A):\n    if int():\n        x = int()\n[out]\n==\nb.py:4: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineNormalClass]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nA = str\n[file b.py]\nimport a\nclass C:\n    x: a.A\nc = C()\nc.x = int()\n[out]\n==\nb.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineNormalClassBases]\nimport b\n[file a.py]\nimport c\nA = c.BaseI\n[file a.py.2]\nimport c\nA = c.BaseS\n[file b.py]\nimport a\nclass C(a.A):\n    x = int()\n[file c.py]\nclass BaseI:\n    x: int\nclass BaseS:\n    x: str\n[out]\n==\nb.py:3: error: Incompatible types in assignment (expression has type \"int\", base class \"BaseS\" defined the type as \"str\")\n\n[case testAliasFineGenericMod]\nimport b\n[file a.py]\nfrom typing import Dict\nA = Dict[str, int]\n[file a.py.2]\nfrom typing import Dict\nA = Dict[str, str]\n[file b.py]\nimport a\nx: a.A = {str(): int()}\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:2: error: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"str\": \"str\"\n\n[case testAliasFineGenericFunc]\nimport b\n[file a.py]\nfrom typing import Dict\nA = Dict[str, int]\n[file a.py.2]\nfrom typing import Dict\nA = Dict[str, str]\n[file b.py]\nimport a\ndef f(x: a.A):\n    pass\nf({str(): int()})\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:4: error: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"str\": \"str\"\n\n[case testAliasFineForwardMod]\nimport b\n[file b.py]\nx: A = int()\nA = int\n[file b.py.2]\nx: A = int()\nA = str\n[out]\n==\nb.py:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineForwardFunc]\nimport b\n[file b.py]\ndef f(x: A):\n    x = int()\nA = int\n[file b.py.2]\ndef f(x: A):\n    if int():\n        x = int()\nA = str\n[out]\n==\nb.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineChainedFunc]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nA = str\n[file aa.py]\nimport a\nB = a.A\n[file b.py]\nimport aa\ndef f(x: aa.B):\n    if int():\n        x = int()\n[out]\n==\nb.py:4: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineChainedClass]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nA = str\n[file aa.py]\nimport a\nB = a.A\n[file b.py]\nimport aa\nclass C:\n    x: aa.B\nc = C()\nc.x = int()\n[out]\n==\nb.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineNestedMod]\nimport b\n[file a.py]\nfrom typing import Dict\nA = Dict[str, int]\n[file a.py.2]\nfrom typing import Dict\nA = Dict[str, str]\n[file aa.py]\nfrom typing import Dict\nimport a\nB = Dict[str, a.A]\n[file b.py]\nimport aa\n\nx: aa.B = {'first': {str(): int()}}\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:3: error: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"str\": \"str\"\n\n[case testAliasFineNestedFunc]\nimport b\n[file a.py]\nfrom typing import Dict\nA = Dict[str, int]\n[file a.py.2]\nfrom typing import Dict\nA = Dict[str, str]\n[file aa.py]\nfrom typing import Dict\nimport a\nB = Dict[str, a.A]\n[file b.py]\nimport aa\ndef f(x: aa.B):\n    if int():\n        x = {'first': {str(): int()}}\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:4: error: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"str\": \"str\"\n\n[case testAliasFineNestedFuncDirect]\nimport b\n[file a.py]\nfrom typing import Dict\nA = Dict[str, int]\n[file a.py.2]\nfrom typing import Dict\nA = Dict[str, str]\n[file aa.py]\nfrom typing import Dict\nimport a\nE = Dict\n[file b.py]\nimport aa\ndef f(x: aa.E[str, aa.a.A]):\n    if int():\n        x = {'first': {str(): int()}}\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:4: error: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"str\": \"str\"\n\n[case testAliasFineNonGenericToGeneric]\nimport b\n[file a.py]\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nA = Dict[T, int]\n[file a.py.2]\nA = str\n[file b.py]\nimport a\ndef f(x: a.A[str]):\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:2: error: \"str\" expects no type arguments, but 1 given\n\n[case testAliasFineGenericToNonGeneric]\nimport b\n[file a.py]\nA = str\n[file a.py.2]\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nA = Dict[T, int]\n[file b.py]\nimport a\ndef f(x: a.A):\n    pass\nreveal_type(f)\n[builtins fixtures/dict.pyi]\n[out]\nb.py:4: note: Revealed type is \"def (x: builtins.str) -> Any\"\n==\nb.py:4: note: Revealed type is \"def (x: builtins.dict[Any, builtins.int]) -> Any\"\n\n[case testAliasFineChangedNumberOfTypeVars]\nimport b\n[file a.py]\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nA = Dict[T, int]\n[file a.py.2]\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nA = Dict[T, S]\n[file b.py]\nimport a\ndef f(x: a.A[str]):\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:2: error: Bad number of arguments for type alias, expected 2, given 1\n\n[case testAliasFineAdded]\nimport b\n[file a.py]\n[file a.py.2]\nA = int\n[file b.py]\nimport a\nx: a.A\n[out]\nb.py:2: error: Name \"a.A\" is not defined\n==\n\n[case testAliasFineDeleted]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\n[file b.py]\nimport a\nx: a.A\n[out]\n==\nb.py:2: error: Name \"a.A\" is not defined\n\n[case testAliasFineClassToAlias]\nimport b\n[file a.py]\nclass A: pass\n[file a.py.2]\nA = int\n[file b.py]\nimport a\nx: a.A\nx = 1\n[out]\nb.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\n==\n\n[case testAliasFineAliasToClass]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nclass A: pass\n[file b.py]\nimport a\nx: a.A\nx = 1\n[out]\n==\nb.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\n\n[case testAliasFineComponentDeleted]\nimport b\n[file a.py]\nclass B: pass\n[file a.py.2]\nx = 1\n[file b.py]\nimport a\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\nA = Dict[T, a.B]\ndef f(x: A[int]):\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n==\nb.py:4: error: Name \"a.B\" is not defined\n\n[case testAliasFineTargetDeleted]\nimport c\n[file a.py]\nA = int\n[file b.py]\nimport a\nB = a.A\n[file b.py.2]\nx = 1\n[file c.py]\nimport b\ndef f(x: b.B):\n    pass\n[out]\n==\nc.py:2: error: Name \"b.B\" is not defined\n\n[case testAliasFineClassInFunction]\nimport b\n[file a.py]\nA = int\n[file a.py.2]\nA = str\n[file b.py]\nimport a\ndef f() -> None:\n    class C:\n        x: a.A = int()\n[out]\n==\nb.py:4: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAliasFineInitNormalMod]\nimport c\n[file a.py]\nclass A:\n    def __init__(self, x: int) -> None:\n        pass\n[file a.py.2]\nclass A:\n    def __init__(self, x: str) -> None:\n        pass\n[file b.py]\nimport a\nB = a.A\n[file c.py]\nfrom b import B\nB(int())\n[out]\n==\nc.py:2: error: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testAliasFineInitNormalFunc]\nimport c\n[file a.py]\nclass A:\n    def __init__(self, x: int) -> None:\n        pass\n[file a.py.2]\nclass A:\n    def __init__(self, x: str) -> None:\n        pass\n[file b.py]\nimport a\nB = a.A\n[file c.py]\nfrom b import B\ndef f() -> None:\n    B(int())\n[out]\n==\nc.py:3: error: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testAliasFineInitGenericMod]\nimport c\n[file a.py]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T, S]):\n    def __init__(self, x: T) -> None:\n        pass\n[file a.py.2]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T, S]):\n    def __init__(self, x: S) -> None:\n        pass\n[file b.py]\nimport a\nB = a.A[int, str]\n[file c.py]\nfrom b import B\nB(int())\n[out]\n==\nc.py:2: error: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testAliasFineInitGenericFunc]\nimport c\n[file a.py]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T, S]):\n    def __init__(self, x: T) -> None:\n        pass\n[file a.py.2]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T, S]):\n    def __init__(self, x: S) -> None:\n        pass\n[file b.py]\nimport a\nB = a.A[int, str]\n[file c.py]\nfrom b import B\ndef f() -> None:\n    B(str())\n[out]\nc.py:3: error: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\n==\n\n[case testAliasFineInitChainedMod]\nimport d\n[file a.py]\nclass A:\n    def __init__(self, x: int) -> None:\n        pass\n[file a.py.2]\nclass A:\n    def __init__(self, x: str) -> None:\n        pass\n[file b.py]\nimport a\nB = a.A\n[file c.py]\nimport b\nC = b.B\n[file d.py]\nfrom c import C\nC(int())\n[out]\n==\nd.py:2: error: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n\n[case testAliasFineInitChainedFunc]\nimport d\n[file a.py]\nclass A:\n    def __init__(self, x: int) -> None:\n        pass\n[file a.py.2]\nclass A:\n    def __init__(self, x: str) -> None:\n        pass\n[file b.py]\nimport a\nB = a.A\n[file c.py]\nimport b\nC = b.B\n[file d.py]\nfrom c import C\ndef f() -> None:\n    C(str())\n[out]\nd.py:3: error: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\n==\n\n[case testNonePartialType1]\nimport a\na.y\n\nx = None\n\ndef f() -> None:\n    global x\n    x = 1\n[file a.py]\ny = 0\n[file a.py.2]\ny = ''\n[out]\nmain:4: error: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\n==\nmain:4: error: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\n\n[case testNonePartialType2]\nimport a\na.y\n\nx = None\n\ndef f():\n    global x\n    x = 1\n[file a.py]\ny = 0\n[file a.py.2]\ny = ''\n[out]\nmain:4: error: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\n==\nmain:4: error: Need type annotation for \"x\" (hint: \"x: Optional[<type>] = ...\")\n\n[case testNonePartialType3]\nimport a\n[file a.py]\n[file a.py.2]\ny = None\ndef f() -> None:\n    global y\n    y = ''\n[out]\n==\na.py:1: error: Need type annotation for \"y\" (hint: \"y: Optional[<type>] = ...\")\n\n[case testNonePartialType4]\nimport a\n[file a.py]\ny = None\ndef f() -> None:\n    global y\n    y = ''\n[file a.py.2]\nfrom typing import Optional\ny: Optional[str] = None\ndef f() -> None:\n    global y\n    y = ''\n[out]\na.py:1: error: Need type annotation for \"y\" (hint: \"y: Optional[<type>] = ...\")\n==\n\n[case testSkippedClass1]\nimport a\n[file a.py]\nclass A: pass\n[file a.py.2]\nimport sys\nif sys.platform == 'xyz':\n    class A: pass\n[builtins fixtures/ops.pyi]\n[out]\n==\n\n[case testSkippedClass2]\nimport a\n[file a.py]\nimport sys\nif sys.platform == 'xyz':\n    class A: pass\n[file a.py.2]\nimport sys\nif sys.platform == 'xyz':\n    class A: pass\n[builtins fixtures/ops.pyi]\n[out]\n==\n\n[case testSkippedClass3]\nimport a\n[file a.py]\nimport sys\nif sys.platform == 'xyz':\n    class A: pass\n[file a.py.2]\nclass A: pass\n[builtins fixtures/ops.pyi]\n[out]\n==\n\n[case testSkippedClass4]\nimport a\n[file a.py]\nimport sys\nif sys.platform == 'xyz':\n    class A: pass\nelse:\n    class A: pass\n[file a.py.2]\nimport sys\nif sys.platform == 'xyz':\n    class A: pass\nelse:\n    class A: pass\n[builtins fixtures/ops.pyi]\n[out]\n==\n\n[case testNewTypeDependencies1]\nfrom a import N\n\ndef f(x: N) -> None:\n    x.y = 1\n[file a.py]\nfrom typing import NewType\nfrom b import C\n\nN = NewType('N', C)\n[file b.py]\nclass C:\n    y: int\n[file b.py.2]\nclass C:\n    y: str\n[out]\n==\nmain:4: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testNewTypeDependencies2]\nfrom a import N\nfrom b import C, D\n\ndef f(x: C) -> None: pass\n\ndef g(x: N) -> None:\n    f(x)\n[file a.py]\nfrom typing import NewType\nfrom b import D\n\nN = NewType('N', D)\n[file b.py]\nclass C: pass\nclass D(C): pass\n[file b.py.2]\nclass C: pass\nclass D: pass\n[out]\n==\nmain:7: error: Argument 1 to \"f\" has incompatible type \"N\"; expected \"C\"\n\n[case testNewTypeDependencies3]\nfrom a import N\n\ndef f(x: N) -> None:\n    x.y\n[file a.py]\nfrom typing import NewType\nfrom b import C\nN = NewType('N', C)\n[file a.py.2]\nfrom typing import NewType\nfrom b import D\nN = NewType('N', D)\n[file b.py]\nclass C:\n    y: int\nclass D:\n    pass\n[out]\n==\nmain:4: error: \"N\" has no attribute \"y\"\n\n[case testNamedTupleWithinFunction]\nfrom typing import NamedTuple\nimport b\ndef f() -> None:\n    b.x\n    n = NamedTuple('n', [])\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testNamedTupleFallback]\n# This test will fail without semantic analyzer pass 2 patches\nimport a\n[file a.py]\nimport b\n[file b.py]\nfrom typing import NamedTuple\nimport c\nc.x\nclass N(NamedTuple):\n    count: int\n[file c.py]\nx = 0\n[file c.py.2]\nx = ''\n[builtins fixtures/tuple.pyi]\n[out]\nb.py:5: error: Incompatible types in assignment (expression has type \"int\", base class \"tuple\" defined the type as \"Callable[[Tuple[int, ...], object], int]\")\n==\nb.py:5: error: Incompatible types in assignment (expression has type \"int\", base class \"tuple\" defined the type as \"Callable[[Tuple[int, ...], object], int]\")\n\n[case testReprocessEllipses1]\nimport a\n[file a.py]\nfrom typing import Tuple\ndef foo(x: Tuple[int, ...]) -> None: pass\n[file a.py.2]\nfrom typing import Tuple\ndef foo(x: Tuple[int, ...]) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testReprocessEllipses2]\nimport a\n[file a.py]\nfrom typing import Callable\ndef foo(x: Callable[..., int]) -> None: pass\n[file a.py.2]\nfrom typing import Callable\ndef foo(x: Callable[..., int]) -> None: pass\n[out]\n==\n\n[case testReprocessCallableArg]\nimport a\n[file a.py]\nfrom typing import Callable\nfrom mypy_extensions import Arg\ndef a(f: Callable[[Arg(int, 'x')], int]) -> None: pass\n[file a.py.2]\nfrom typing import Callable\nfrom mypy_extensions import Arg\ndef a(f: Callable[[Arg(int, 'x')], int]) -> None: pass\n[builtins fixtures/dict.pyi]\n[out]\n==\n\n[case testImplicitTuple1]\nimport a\n[file a.py]\n# Bogus annotation in nested function masked because outer function\n# isn't annotated\ndef unchecked():\n    def inner():\n        # type: () -> (str, int)\n        return 'lol', 10\n[file a.py.2]\n# dummy change\ndef unchecked():\n    def inner():\n        # type: () -> (str, int)\n        return 'lol', 10\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testImplicitTuple2]\nimport a\n[file a.py]\ndef inner():\n    # type: () -> (str, int)\n    return 'lol', 10\n[file a.py.2]\n# dummy change\ndef inner():\n    # type: () -> (str, int)\n    return 'lol', 10\n[builtins fixtures/tuple.pyi]\n[out]\na.py:1: error: Syntax error in type annotation\na.py:1: note: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n==\na.py:2: error: Syntax error in type annotation\na.py:2: note: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n\n[case testImplicitTuple3]\nimport a\n[file a.py]\n(x, y) = 1, 'hi'  # type: (int, str)\n[file a.py.2]\n# dummy change\n(x, y) = 1, 'hi'  # type: (int, str)\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testCastConfusion]\nimport b\n[file a.py]\nfrom typing import cast\nclass Thing:\n    def foo(self) -> None: pass\n\nthing = cast(Thing, Thing())\n\n[file b.py]\nfrom typing import Optional\nfrom a import Thing, thing\nclass User:\n    def __init__(self, x: Optional[Thing]) -> None:\n        self.x = x if x else thing\n    def use(self) -> None: self.x.foo()\n\n[file a.py.2]\nfrom typing import cast\nclass Thing:\n    def foo(self) -> None: pass\n\nthing = cast(Thing, Thing())\n# update\n\n[file b.py.2]\nfrom typing import Optional\nfrom a import Thing, thing\nclass User:\n    def __init__(self, x: Optional[Thing]) -> None:\n        self.x = x if x else thing\n    def use(self) -> None: self.x.foo()\n# update\n[builtins fixtures/ops.pyi]\n[out]\n==\n\n[case testNoStrictOptionalModule]\n# flags: --no-strict-optional\nimport a\na.y = a.x\n[file a.py]\nfrom typing import Optional\nx: int\ny: int\n[file a.py.2]\nfrom typing import Optional\nx: Optional[int]\ny: int\n[file a.py.3]\nfrom typing import Optional\nx: Optional[str]\ny: int\n[out]\n==\n==\nmain:3: error: Incompatible types in assignment (expression has type \"Optional[str]\", variable has type \"int\")\n\n[case testNoStrictOptionalFunction]\n# flags: --no-strict-optional\nimport a\nfrom typing import Optional\ndef f() -> None:\n    x: Optional[int]\n    a.g(x)\n[file a.py]\nfrom typing import Optional\ndef g(x: Optional[int]) -> None:\n    pass\n[file a.py.2]\nfrom typing import Optional\ndef g(x: int) -> None:\n    pass\n[file a.py.3]\nfrom typing import Optional\ndef g(x: str) -> None:\n    pass\n[out]\n==\n==\nmain:6: error: Argument 1 to \"g\" has incompatible type \"Optional[int]\"; expected \"str\"\n\n[case testNoStrictOptionalMethod]\n# flags: --no-strict-optional\nimport a\nfrom typing import Optional\nclass C:\n    def f(self) -> None:\n        x: Optional[int]\n        a.B().g(x)\n[file a.py]\nfrom typing import Optional\nclass B:\n    def g(self, x: Optional[int]) -> None:\n        pass\n[file a.py.2]\nfrom typing import Optional\nclass B:\n    def g(self, x: int) -> None:\n        pass\n[file a.py.3]\nfrom typing import Optional\nclass B:\n    def g(self, x: str) -> None:\n        pass\n[out]\n==\n==\nmain:7: error: Argument 1 to \"g\" of \"B\" has incompatible type \"Optional[int]\"; expected \"str\"\n\n[case testStrictOptionalModule]\nimport a\na.y = a.x\n[file a.py]\nfrom typing import Optional\nx: int\ny: int\n[file a.py.2]\nfrom typing import Optional\nx: Optional[int]\ny: int\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type \"Optional[int]\", variable has type \"int\")\n\n[case testStrictOptionalFunction]\nimport a\nfrom typing import Optional\ndef f() -> None:\n    x: Optional[int]\n    a.g(x)\n[file a.py]\nfrom typing import Optional\ndef g(x: Optional[int]) -> None:\n    pass\n[file a.py.2]\nfrom typing import Optional\ndef g(x: int) -> None:\n    pass\n[out]\n==\nmain:5: error: Argument 1 to \"g\" has incompatible type \"Optional[int]\"; expected \"int\"\n\n[case testStrictOptionalMethod]\nimport a\nfrom typing import Optional\nclass C:\n    def f(self) -> None:\n        x: Optional[int]\n        a.B().g(x)\n[file a.py]\nfrom typing import Optional\nclass B:\n    def g(self, x: Optional[int]) -> None:\n        pass\n[file a.py.2]\nfrom typing import Optional\nclass B:\n    def g(self, x: int) -> None:\n        pass\n[out]\n==\nmain:6: error: Argument 1 to \"g\" of \"B\" has incompatible type \"Optional[int]\"; expected \"int\"\n\n[case testPerFileStrictOptionalModule]\nimport a\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-a.*]\nstrict_optional = True\n[file a.py]\nfrom typing import Optional\nimport b\nx: int\ny: int = x\n[file b.py]\nfrom typing import Optional\nx: int\ny: int = x\n[file b.py.2]\nfrom typing import Optional\nx: Optional[int]\ny: int = x\n[file a.py.3]\nfrom typing import Optional\nimport b\nx: Optional[int]\ny: int = x\n[out]\n==\n==\na.py:4: error: Incompatible types in assignment (expression has type \"Optional[int]\", variable has type \"int\")\n\n[case testPerFileStrictOptionalModuleOnly]\nimport a\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-a.*]\nstrict_optional = True\n[file a.py]\nfrom typing import Optional\nimport b\ny: int = b.x\nclass Dummy:\n    def f(self) -> None:\n        pass\n[file b.py]\nfrom typing import Optional\nimport c\nx: int\ny: int = c.x\nclass Dummy:\n    def f(self) -> None:\n        pass\n[file c.py]\nfrom typing import Optional\nx: int\n[file c.py.2]\nfrom typing import Optional\nx: Optional[int]\n[file b.py.3]\nfrom typing import Optional\nimport c\nx: Optional[int]\ny: int = c.x\n[file a.py.4]\nfrom typing import Optional\nimport b\ny: Optional[int] = b.x\nclass Dummy:\n    def f(self) -> None:\n        pass\n[out]\n==\n==\na.py:3: error: Incompatible types in assignment (expression has type \"Optional[int]\", variable has type \"int\")\n==\n\n[case testPerFileStrictOptionalFunction]\nimport a\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-b.*]\nstrict_optional = True\n[file a.py]\nfrom typing import Optional\nimport b\ndef f() -> None:\n    x: int\n    x = b.g(x)\n[file b.py]\nfrom typing import Optional\nimport c\ndef g(x: Optional[int]) -> Optional[int]:\n    return c.h(x)\n[file c.py]\nfrom typing import Optional\ndef h(x: Optional[int]) -> int:\n    pass\n[file c.py.2]\nfrom typing import Optional\ndef h(x: int) -> int:\n    pass\n[file b.py.3]\nfrom typing import Optional\nimport c\ndef g(x: int) -> Optional[int]:\n    return c.h(x)\n[out]\n==\nb.py:4: error: Argument 1 to \"h\" has incompatible type \"Optional[int]\"; expected \"int\"\n==\n\n[case testPerFileStrictOptionalMethod]\nimport a\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-b.*]\nstrict_optional = True\n[file a.py]\nfrom typing import Optional\nimport b\nclass A:\n    def f(self) -> None:\n        x: int\n        x = b.B().g(x)\n[file b.py]\nfrom typing import Optional\nimport c\nclass B:\n    def g(self, x: Optional[int]) -> Optional[int]:\n        return c.C().h(x)\n[file c.py]\nfrom typing import Optional\nclass C:\n    def h(self, x: Optional[int]) -> int:\n        pass\n[file c.py.2]\nfrom typing import Optional\nclass C:\n    def h(self, x: int) -> int:\n        pass\n[file b.py.3]\nfrom typing import Optional\nimport c\nclass B:\n    def g(self, x: int) -> Optional[int]:\n        return c.C().h(x)\n[out]\n==\nb.py:5: error: Argument 1 to \"h\" of \"C\" has incompatible type \"Optional[int]\"; expected \"int\"\n==\n\n[case testTypeVarValuesFunction]\nimport a\n[file a.py]\nfrom typing import TypeVar\nfrom c import A, B\nT = TypeVar('T', A, B)\n\ndef f(x: T) -> T:\n    x.x = int()\n    return x\n[file c.py]\nclass A:\n    x: int\nclass B:\n    x: int\n[file c.py.2]\nclass A:\n    x: int\nclass B:\n    x: str\n[out]\n==\na.py:6: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testTypeVarValuesClass]\nimport a\n[file a.py]\nimport c\nclass C:\n    x: c.D[c.A]\n[file c.py]\nfrom typing import TypeVar, Generic\nclass A: pass\nclass B: pass\nclass C: pass\nT = TypeVar('T', A, B, C)\nclass D(Generic[T]):\n    pass\n[file c.py.2]\nfrom typing import TypeVar, Generic\nclass A: pass\nclass B: pass\nclass C: pass\nT = TypeVar('T', B, C)\nclass D(Generic[T]):\n    pass\n[out]\n==\na.py:3: error: Value of type variable \"T\" of \"D\" cannot be \"A\"\na.py:3: note: \"T\" of \"D\" is a constrained type variable, it is not generic\n\n[case testTypeVarValuesMethod1]\nimport a\n[file a.py]\nfrom typing import Generic\nimport c\nclass G(Generic[c.T]):\n    def f(self, x: c.T) -> None:\n        x.x = int()\n[file c.py]\nfrom typing import TypeVar\nclass A:\n    x: int\nclass B:\n    x: int\nclass C:\n    x: str\nT = TypeVar('T', A, B, C)\n[file c.py.2]\nfrom typing import TypeVar\nclass A:\n    x: int\nclass B:\n    x: int\nclass C:\n    x: str\nT = TypeVar('T', A, B)\n[out]\na.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n==\n\n[case testTypeVarValuesMethod2]\nimport a\n[file a.py]\nfrom typing import Generic\nimport c\nclass G(Generic[c.T]):\n    def f(self, x: c.T) -> None:\n        x.x = int()\n[file c.py]\nfrom typing import TypeVar\nclass A:\n    x: int\nclass B:\n    x: int\nT = TypeVar('T', A, B)\n[file c.py.2]\nfrom typing import TypeVar\nclass A:\n    x: int\nclass B:\n    x: str\nT = TypeVar('T', A, B)\n[out]\n==\na.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testTypeVarBoundFunction]\nimport a\n[file a.py]\nfrom typing import TypeVar\nfrom c import B\nT = TypeVar('T', bound=B)\n\ndef f(x: T) -> T:\n    x.x = int()\n    return x\n[file c.py]\nclass B:\n    x: int\n[file c.py.2]\nclass B:\n    x: str\n[out]\n==\na.py:6: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testTypeVarBoundClass]\nimport a\n[file a.py]\nimport c\nclass C:\n    x: c.D[c.A]\n[file c.py]\nfrom typing import TypeVar, Generic\nclass A: pass\nclass B: pass\nT = TypeVar('T', bound=A)\nclass D(Generic[T]):\n    pass\n[file c.py.2]\nfrom typing import TypeVar, Generic\nclass A: pass\nclass B: pass\nT = TypeVar('T', bound=B)\nclass D(Generic[T]):\n    pass\n[out]\n==\na.py:3: error: Type argument \"A\" of \"D\" must be a subtype of \"B\"\n\n[case testTypeVarValuesRuntime]\nfrom mod import I, S, D\nA = I\nx = D[S, A]()\n[file mod.py]\nimport submod\nfrom typing import Generic\nclass D(Generic[submod.T, submod.U]): pass\nclass I: pass\nclass S: pass\n[file submod.py]\nfrom typing import TypeVar\nT = TypeVar('T')\nU = TypeVar('U')\n[file submod.py.2]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\nU = TypeVar('U', int, str)\n[out]\n==\nmain:3: error: Value of type variable \"submod.T\" of \"D\" cannot be \"S\"\nmain:3: note: \"submod.T\" of \"D\" is a constrained type variable, it is not generic\nmain:3: error: Value of type variable \"submod.U\" of \"D\" cannot be \"I\"\nmain:3: note: \"submod.U\" of \"D\" is a constrained type variable, it is not generic\n\n\n[case testTypeVarBoundRuntime]\nfrom mod import I, S, D\nA = I\nx = D[S, A]()\n[file mod.py]\nimport submod\nfrom typing import Generic\nclass D(Generic[submod.T, submod.U]): pass\nclass I: pass\nclass S: pass\n[file submod.py]\nfrom typing import TypeVar\nT = TypeVar('T', bound=int)\nU = TypeVar('U', bound=int)\n[file submod.py.2]\nfrom typing import TypeVar\nT = TypeVar('T')\nU = TypeVar('U')\n[out]\nmain:3: error: Value of type variable \"submod.T\" of \"D\" cannot be \"S\"\nmain:3: error: Value of type variable \"submod.U\" of \"D\" cannot be \"I\"\n==\n\n[case testGenericFineCallableNormal]\nimport a\n[file a.py]\nimport b\nx: int = b.f(int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import TypeVar\nclass B: pass\nT = TypeVar('T')\ndef g(x: T) -> T:\n    pass\n[file c.py.2]\nfrom typing import TypeVar\nclass B: pass\nT = TypeVar('T', str, B)\ndef g(x: T) -> T:\n    pass\n[out]\n==\na.py:2: error: Value of type variable \"T\" of function cannot be \"int\"\na.py:2: note: \"T\" of function is a constrained type variable, it is not generic\n\n[case testGenericFineCallableNamed]\nimport a\n[file a.py]\nimport b\nx: int = b.f(x=int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import TypeVar\nclass B: pass\nT = TypeVar('T')\ndef g(x: T) -> T:\n    pass\n[file c.py.2]\nfrom typing import TypeVar\nclass B: pass\nT = TypeVar('T')\ndef g(y: T) -> T:\n    pass\n[out]\n==\na.py:2: error: Unexpected keyword argument \"x\"\nc.py:4: note: Called function defined here\n\n[case testGenericFineCallableInBound]\nimport a\n[file a.py]\nimport b\nx: int = b.f()(int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import Callable, TypeVar\nclass B: pass\nT = TypeVar('T')\ndef g() -> Callable[[T], T]:\n    pass\n[file c.py.2]\nfrom typing import Callable, TypeVar\nclass B: pass\nT = TypeVar('T', str, B)\ndef g() -> Callable[[T], T]:\n    pass\n[out]\n==\na.py:2: error: Value of type variable \"T\" of function cannot be \"int\"\na.py:2: note: \"T\" of function is a constrained type variable, it is not generic\n\n[case testGenericFineCallableAddedBound]\nimport a\n[file a.py]\nimport b\nx: int = b.f(int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import TypeVar\nclass B: pass\nT = TypeVar('T')\ndef g(x: T) -> T:\n    pass\n[file c.py.2]\nfrom typing import TypeVar\nclass B: pass\nT = TypeVar('T', bound=B)\ndef g(x: T) -> T:\n    pass\n[out]\n==\na.py:2: error: Value of type variable \"T\" of function cannot be \"int\"\n\n[case testGenericFineCallableBoundDeleted-only_when_cache]\n# See https://github.com/python/mypy/issues/4783\nimport a\n[file a.py]\nimport b\nx: int = b.f(int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import TypeVar\nimport d\nT = TypeVar('T', bound=d.B)\ndef g(x: T) -> T:\n    pass\n[file d.py]\nclass B:\n    pass\n[file d.py.2]\n# empty\n[out]\na.py:2: error: Value of type variable \"T\" of function cannot be \"int\"\n==\nc.py:3: error: Name \"d.B\" is not defined\n\n[case testGenericFineCallableToNonGeneric]\nimport a\n[file a.py]\nimport b\nx: int = b.f(x=int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef g(x: T) -> T:\n    pass\n[file c.py.2]\nfrom typing import TypeVar\nclass T: pass\ndef g(x: T) -> T:\n    pass\n[out]\n==\na.py:2: error: Incompatible types in assignment (expression has type \"T\", variable has type \"int\")\na.py:2: error: Argument \"x\" has incompatible type \"int\"; expected \"T\"\n\n[case testGenericFineCallableToGenericClass]\nimport a\n[file a.py]\nimport b\nx: int = b.f(x=int())\n[file b.py]\nfrom c import g\nf = g\n[file c.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef g(x: T) -> T:\n    pass\n[file c.py.2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass g(Generic[T]):\n    def __init__(self, x: T) -> None:\n        pass\n[out]\n==\na.py:2: error: Incompatible types in assignment (expression has type \"g[int]\", variable has type \"int\")\n\n[case testMakeClassNoLongerAbstract1]\n[file z.py]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n[file b.py]\nfrom typing import Optional\nfrom z import I\nclass Foo(I):\n    pass\ndef x() -> Optional[Foo]: return None\n[file z.py.2]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    pass\n[file b.py.2]\nfrom z import I\nclass Foo(I):\n    pass\ndef x() -> Foo: return Foo()\n[out]\n==\n\n[case testMakeClassNoLongerAbstract2]\n-- this version never failed, but it is just a file-renaming\n-- away from the above test that did\n[file a.py]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n[file b.py]\nfrom typing import Optional\nfrom a import I\nclass Foo(I):\n    pass\ndef x() -> Optional[Foo]: return None\n[file a.py.2]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    pass\n[file b.py.2]\nfrom a import I\nclass Foo(I):\n    pass\ndef x() -> Foo: return Foo()\n[out]\n==\n\n[case testRefreshClassBasedEnum]\nimport aa\n[file aa.py]\nimport a\n[file a.py]\nfrom enum import Enum\nimport b\nb.x\nclass C(Enum):\n    X = 0\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[file aa.py.3]\nfrom a import C\nc: C\nc = C.X\nif int():\n    c = 1\n[builtins fixtures/enum.pyi]\n[out]\n==\n==\naa.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"C\")\n\n[case testRefreshClassBasedIntEnum]\nimport aa\n[file aa.py]\nimport a\n[file a.py]\nfrom enum import IntEnum\nimport b\nb.x\nclass C(IntEnum):\n    X = 0\nx: int\nx = C.X\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[file aa.py.3]\nfrom a import C\nc: C\nc = C.X\nif int():\n    c = 1\n    n: int\n    n = C.X\n    if int():\n        n = c\n[builtins fixtures/enum.pyi]\n[out]\n==\n==\naa.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"C\")\n\n[case testClassBasedEnumPropagation1]\nimport a\n[file a.py]\nfrom b import C\n\ndef f(x: C) -> None: pass\nf(C.X)\nf(C.Y)\n[file b.py]\nfrom enum import Enum\n\nclass C(Enum):\n    X = 0\n    Y = 1\n[file b.py.2]\nfrom enum import Enum\n\nclass C(Enum):\n    X = 0\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n==\na.py:5: error: \"Type[C]\" has no attribute \"Y\"\n\n[case testClassBasedEnumPropagation2]\nimport a\n[file a.py]\nfrom b import C\n\ndef f(x: int) -> None: pass\nf(C.X)\nf(C.Y)\n[file b.py]\nclass C:\n    X = 0\n    Y = 1\n[file b.py.2]\nfrom enum import Enum\nclass C(Enum):\n    X = 0\n    Y = 1\n[builtins fixtures/enum.pyi]\n[out]\n==\na.py:4: error: Argument 1 to \"f\" has incompatible type \"C\"; expected \"int\"\na.py:5: error: Argument 1 to \"f\" has incompatible type \"C\"; expected \"int\"\n\n[case testRefreshFuncBasedEnum]\nimport aa\n[file aa.py]\nimport a\n[file a.py]\nfrom enum import Enum\nimport b\nb.x\nC = Enum('C', [('X', 0)])\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[file aa.py.3]\nfrom a import C\nc: C\nc = C.X\nif int():\n   c = 1\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\naa.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"C\")\n\n[case testRefreshFuncBasedIntEnum]\nimport aa\n[file aa.py]\nimport a\n[file a.py]\nfrom enum import IntEnum\nimport b\nb.x\nC = IntEnum('C', 'X')\nx: int\nx = C.X\n[file b.py]\nx = 0\n[file b.py.2]\nx = ''\n[file aa.py.3]\nfrom a import C\nc: C\nc = C.X\nif int():\n    c = 1  # Error\n    n: int\n    n = C.X\nn = c\n[builtins fixtures/enum.pyi]\n[out]\n==\n==\naa.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"C\")\n\n[case testFuncBasedEnumPropagation1]\nimport a\n[file a.py]\nfrom b import C\n\ndef f(x: C) -> None: pass\nf(C.X)\nf(C.Y)\n[file b.py]\nfrom enum import Enum\n\nC = Enum('C', 'X Y')\n[file b.py.2]\nfrom enum import Enum\n\nC = Enum('C', 'X')\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n==\na.py:5: error: \"Type[C]\" has no attribute \"Y\"\n\n[case testFuncBasedEnumPropagation2]\nimport a\n[file a.py]\nfrom b import C\n\ndef f(x: int) -> None: pass\nf(C.X)\nf(C.Y)\n[file b.py]\nclass C:\n    X = 0\n    Y = 1\n[file b.py.2]\nfrom enum import Enum\nC = Enum('C', [('X', 0), ('Y', 1)])\n[builtins fixtures/tuple.pyi]\n[out]\n==\na.py:4: error: Argument 1 to \"f\" has incompatible type \"C\"; expected \"int\"\na.py:5: error: Argument 1 to \"f\" has incompatible type \"C\"; expected \"int\"\n\n[case testChangeTypeVarToFunction]\n\nimport a\nfrom typing import Generic\n\nclass C(Generic[a.T]):\n    def meth(self, x: a.T) -> None:\n        pass\n\nAlias = C[C[a.T]]\n\ndef outer() -> None:\n    def func(x: a.T) -> Alias[a.T]:\n        pass\n[file a.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[file a.py.2]\nfrom typing import TypeVar\ndef T() -> None:\n    pass\n[out]\n==\nmain:5: error: Free type variable expected in Generic[...]\nmain:6: error: Function \"a.T\" is not valid as a type\nmain:6: note: Perhaps you need \"Callable[...]\" or a callback protocol?\nmain:9: error: \"C\" expects no type arguments, but 1 given\nmain:9: error: \"C\" expects no type arguments, but 1 given\nmain:9: error: Function \"a.T\" is not valid as a type\nmain:9: note: Perhaps you need \"Callable[...]\" or a callback protocol?\nmain:12: error: Function \"a.T\" is not valid as a type\nmain:12: note: Perhaps you need \"Callable[...]\" or a callback protocol?\nmain:12: error: Bad number of arguments for type alias, expected 0, given 1\n\n[case testChangeTypeVarToModule]\n\nimport a\nfrom typing import Generic\n\nclass C(Generic[a.T]):\n    def meth(self, x: a.T) -> None:\n        pass\n\nAlias = C[C[a.T]]\n\ndef outer() -> None:\n    def func(x: a.T) -> Alias[a.T]:\n        pass\n[file a.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[file T.py.2]\n[file a.py.3]\nfrom typing import TypeVar\nimport T\n[out]\n==\n==\nmain:5: error: Free type variable expected in Generic[...]\nmain:6: error: Module \"T\" is not valid as a type\nmain:6: note: Perhaps you meant to use a protocol matching the module structure?\nmain:9: error: \"C\" expects no type arguments, but 1 given\nmain:9: error: \"C\" expects no type arguments, but 1 given\nmain:9: error: Module \"T\" is not valid as a type\nmain:9: note: Perhaps you meant to use a protocol matching the module structure?\nmain:12: error: Module \"T\" is not valid as a type\nmain:12: note: Perhaps you meant to use a protocol matching the module structure?\nmain:12: error: Bad number of arguments for type alias, expected 0, given 1\n\n[case testChangeClassToModule]\n\nimport a\nx: a.C\ndef f() -> None:\n    a.C()\nclass A:\n    def meth(self) -> None:\n        def inner() -> a.C:\n            pass\n[file a.py]\nclass C:\n    pass\n[file C.py.2]\n[file a.py.3]\nimport C\n[builtins fixtures/module.pyi]\n[out]\n==\n==\nmain:3: error: Module \"C\" is not valid as a type\nmain:3: note: Perhaps you meant to use a protocol matching the module structure?\nmain:5: error: Module not callable\nmain:8: error: Module \"C\" is not valid as a type\nmain:8: note: Perhaps you meant to use a protocol matching the module structure?\n\n[case testChangeTypeVarToTypeAlias]\n\nimport a\nfrom typing import Generic\n\nclass C(Generic[a.T]):\n    def meth(self, x: a.T) -> None:\n        pass\n\nAlias = C[C[a.T]]\n\ndef outer() -> None:\n    def func(x: a.T) -> Alias[a.T]:\n        pass\n[file a.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[file a.py.2]\nfrom typing import TypeVar\nT = int\n[out]\n==\nmain:5: error: Free type variable expected in Generic[...]\nmain:9: error: \"C\" expects no type arguments, but 1 given\nmain:9: error: \"C\" expects no type arguments, but 1 given\nmain:12: error: Bad number of arguments for type alias, expected 0, given 1\n\n[case testChangeTypeAliasToModule]\n\nimport a\nx: a.C\ndef f() -> None:\n    a.C()\nclass A:\n    def meth(self) -> None:\n        def inner() -> a.C:\n            pass\n[file a.py]\nimport b\nC = b.D\n[file b.py]\nclass D:\n    pass\n[file D.py.2]\n[file b.py.3]\nimport D\n[builtins fixtures/module.pyi]\n[out]\n==\n==\nmain:3: error: Module \"D\" is not valid as a type\nmain:3: note: Perhaps you meant to use a protocol matching the module structure?\nmain:5: error: Module not callable\nmain:8: error: Module \"D\" is not valid as a type\nmain:8: note: Perhaps you meant to use a protocol matching the module structure?\n\n[case testChangeTypeAliasToModuleUnqualified]\n\nfrom a import C\nx: C\ndef f() -> None:\n    C()\nclass A:\n    def meth(self) -> None:\n        def inner() -> C:\n            pass\n[file a.py]\nfrom b import D\nC = D\n[file b.py]\nclass D:\n    pass\n[file D.py.2]\n[file b.py.3]\nimport D\n[builtins fixtures/module.pyi]\n[out]\n==\n==\nmain:3: error: Module \"D\" is not valid as a type\nmain:3: note: Perhaps you meant to use a protocol matching the module structure?\nmain:5: error: Module not callable\nmain:8: error: Module \"D\" is not valid as a type\nmain:8: note: Perhaps you meant to use a protocol matching the module structure?\n\n[case testChangeFunctionToVariableAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nf = 1\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testChangeFunctionToTypeVarAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nfrom typing import TypeVar\nf = TypeVar('f')\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testChangeFunctionToModuleAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nimport c as f\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testChangeFunctionToTypeAliasAndRefreshUsingStaleDependency1]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nf = int\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testChangeFunctionToTypeAliasAndRefreshUsingStaleDependency2]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nfrom typing import List\nf = List[int]\n[file c.py]\nclass A: pass\n[file c.py.3]\n[builtins fixtures/list.pyi]\n[out]\n==\n==\n\n[case testChangeFunctionToClassAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nclass f: pass\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testClassToVariableAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\nclass A:\n    def f(self) -> c.A: pass\n[file a.py.2]\nA = 0\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testFunctionToImportedFunctionAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\ndef f() -> c.A: pass\n[file a.py.2]\nfrom d import f\n[file c.py]\nclass A: pass\n[file c.py.3]\n[file d.py]\ndef g() -> None: pass\ndef f() -> None:\n    g()\n[out]\n==\n==\n\n[case testMethodToVariableAndRefreshUsingStaleDependency]\nimport a\nimport c\n[file a.py]\nimport c\nclass B:\n    def f(self) -> c.A: pass\n[file a.py.2]\nclass B:\n    f = 0\n[file c.py]\nclass A: pass\n[file c.py.3]\n[out]\n==\n==\n\n[case testChangeGenericFunctionToVariable]\nimport a\nx: int\ny: int = a.f(x)\nclass Dummy:\n    def g(self) -> None:\n        a.f(x)\n[file a.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(x: T) -> T:\n    pass\n[file a.py.2]\nfrom typing import TypeVar\nT = TypeVar('T')\nf = 42\n[out]\n==\nmain:3: error: \"int\" not callable\nmain:6: error: \"int\" not callable\n\n[case testChangeGenericClassToVariable]\nimport a\nx: int\na.A(x)\nclass Dummy:\n    def g(self) -> None:\n        a.A(x)\n[file a.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def __init__(self, x: T) -> None:\n        pass\n[file a.py.2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nA = 'no way'\n[out]\n==\nmain:3: error: \"str\" not callable\nmain:6: error: \"str\" not callable\n\n[case testChangeGenericMethodToVariable]\nimport a\nx: int\ny: int = a.A(x).f()\nclass Dummy:\n    def g(self) -> None:\n        a.A(x).f()\n[file a.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def __init__(self, x: T) -> None:\n        pass\n    def f(self) -> T:\n        pass\n[file a.py.2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    f: T\n    def __init__(self, x: T) -> None:\n        pass\n[out]\n==\nmain:3: error: \"int\" not callable\nmain:6: error: \"int\" not callable\n\n[case testRefreshNestedClassWithSelfReference]\nimport a\n[file a.py]\nimport b\n\ndef f(self) -> None:\n    b.y\n    class C:\n        z: C\n[file b.py]\ny = 0\n[file b.py.2]\ny = ''\n[file b.py.3]\ny = 0\n[out]\n==\n==\n\n[case testMultipleAssignment]\nimport a\n[file a.py]\nfrom b import f\n\ndef h(x: str) -> None: pass\n\nclass C:\n    def __init__(self) -> None:\n        self.a, self.b = f()\n\n    def g(self) -> None:\n        h(self.a)\n[file b.py]\nfrom typing import Tuple\ndef f() -> Tuple[str, int]: pass\n[file b.py.2]\nfrom typing import Tuple\ndef f() -> Tuple[int, object]: pass\n[file b.py.3]\nfrom typing import Tuple\ndef f() -> Tuple[str, int]: pass\n[builtins fixtures/tuple.pyi]\n[out]\n==\na.py:10: error: Argument 1 to \"h\" has incompatible type \"int\"; expected \"str\"\n==\n\n[case testMultipleLvalues]\nimport a\n[file a.py]\nfrom b import f\n\ndef h(x: str) -> None: pass\n\nclass C:\n    def __init__(self) -> None:\n        self.a = self.b = f()\n\n    def g(self) -> None:\n        h(self.a)\n        h(self.b)\n[file b.py]\ndef f() -> str: pass\n[file b.py.2]\ndef f() -> int: pass\n[file b.py.3]\ndef f() -> str: pass\n[out]\n==\na.py:10: error: Argument 1 to \"h\" has incompatible type \"int\"; expected \"str\"\na.py:11: error: Argument 1 to \"h\" has incompatible type \"int\"; expected \"str\"\n==\n\n[case testNoOpUpdateFineGrainedIncremental1]\n# cmd: mypy a.py\n[file a.py]\n1()\n[file b.py.2]\n# Note: this file is not part of the build\n[file a.py.3]\nx = 1\n[out]\na.py:1: error: \"int\" not callable\n==\na.py:1: error: \"int\" not callable\n==\n\n[case testNoOpUpdateFineGrainedIncremental2]\n# cmd: mypy a.py\n[file a.py]\n1()\n[file a.py.2]\n1()\n[file a.py.3]\nx = 1\n[file a.py.4]\nx = 1\n[out]\na.py:1: error: \"int\" not callable\n==\na.py:1: error: \"int\" not callable\n==\n==\n\n[case testNonExistentFileOnCommandLine1]\n# cmd: mypy a.py nonexistent.py\n[file a.py]\n[file a.py.2]\n1()\n[out]\nmypy: can't read file 'tmp/nonexistent.py': No such file or directory\n==\nmypy: can't read file 'tmp/nonexistent.py': No such file or directory\n\n[case testNonExistentFileOnCommandLine2]\n# cmd: mypy a.py\n# cmd2: mypy a.py nonexistent.py\n[file a.py]\n[file a.py.2]\n1()\n[out]\n==\na.py:1: error: \"int\" not callable\n\n[case testNonExistentFileOnCommandLine3]\n# cmd: mypy a.py\n# cmd2: mypy a.py nonexistent.py\n[file a.py]\n[file nonexistent.py]\n[delete nonexistent.py.2]\n[out]\n==\n\n[case testNonExistentFileOnCommandLine4]\n# cmd: mypy a.py nonexistent.py\n[file a.py]\n[file nonexistent.py]\n[delete nonexistent.py.2]\n[out]\n==\n\n[case testNonExistentFileOnCommandLine5]\n# cmd: mypy a.py nonexistent_stub.pyi\n# TODO: Should generate an error for missing file\n[file a.py]\n[file nonexistent_stub.pyi]\n[delete nonexistent_stub.pyi.2]\n[out]\n==\n\n[case testDunderNewUpdatedMethod]\nimport a\n[file a.py]\nimport b\nclass A:\n    def func(self) -> None:\n        b.C(int())\n[file b.py]\nclass C:\n    def __new__(cls, x: str) -> C:\n        pass\n[file b.py.2]\nclass C:\n    def __new__(cls, x: int) -> C:\n        pass\n[out]\na.py:4: error: Argument 1 to \"C\" has incompatible type \"int\"; expected \"str\"\n==\n\n[case testDunderNewUpdatedSubclass]\nimport a\n[file a.py]\nimport b\n\nb.D(int())\n[file b.py]\nfrom c import C\nclass D(C): pass\n[file c.py]\nclass C:\n    def __new__(cls, x: str) -> C:\n        pass\n[file c.py.2]\nclass C:\n    def __new__(cls, x: int) -> C:\n        pass\n[out]\na.py:3: error: Argument 1 to \"D\" has incompatible type \"int\"; expected \"str\"\n==\n\n[case testDunderNewUpdatedAlias]\nimport a\n[file a.py]\nimport b\n\nb.D(int())\n[file b.py]\nfrom c import C\nD = C\n[file c.py]\nclass C:\n    def __new__(cls, x: int) -> C:\n        pass\n[file c.py.2]\nclass C:\n    def __new__(cls, x: str) -> C:\n        pass\n[out]\n==\na.py:3: error: Argument 1 to \"C\" has incompatible type \"int\"; expected \"str\"\n\n[case testDunderNewUpdatedCallable]\nimport a\n[file a.py]\nfrom typing import Callable, Any\nimport b\n\ndef func(arg: Callable[[int], Any]) -> None:\n    pass\nfunc(b.C)\n[file b.py]\nclass C:\n    def __new__(cls, x: int) -> C:\n        pass\n[file b.py.2]\nclass C:\n    def __new__(cls, x: str) -> C:\n        pass\n[out]\n==\na.py:6: error: Argument 1 to \"func\" has incompatible type \"Type[C]\"; expected \"Callable[[int], Any]\"\n\n[case testDunderNewDefine]\nimport a\n[file a.py]\nimport b\nclass A:\n    def func(self) -> None:\n        b.C()\n[file b.py]\nclass C:\n    pass\n[file b.py.2]\nclass C:\n    def __new__(cls, x: int) -> C:\n        pass\n[out]\n==\na.py:4: error: Missing positional argument \"x\" in call to \"C\"\n\n[case testDunderNewInsteadOfInit]\nimport a\n[file a.py]\nimport b\nclass A:\n    def func(self) -> None:\n        b.C(int())\n[file b.py]\nclass C:\n    def __init__(cls, x: int) -> None:\n        pass\n[file b.py.2]\nclass C:\n    def __new__(cls, x: int) -> C:\n        pass\n[file b.py.3]\nclass C:\n    pass\n[out]\n==\n==\na.py:4: error: Too many arguments for \"C\"\n\n-- Protocol tests\n\n[case testProtocolUpdateTypeInVariable]\nimport a\n[file a.py]\nimport b\nclass C:\n    x: int\nx: b.P = C()\n[file b.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[file b.py.2]\nfrom typing import Protocol\nclass P(Protocol):\n    x: str\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\na.py:4: note: Following member(s) of \"C\" have conflicts:\na.py:4: note:     x: expected \"str\", got \"int\"\n\n[case testProtocolUpdateTypeInFunction]\nimport a\n[file a.py]\nimport b\nclass C:\n    x: int\nc: C\ndef f() -> None:\n    def g(x: b.P) -> None:\n        pass\n    g(c)\n[file b.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[file b.py.2]\nfrom typing import Protocol\nclass P(Protocol):\n    x: str\n[out]\n==\na.py:8: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:8: note: Following member(s) of \"C\" have conflicts:\na.py:8: note:     x: expected \"str\", got \"int\"\n\n[case testProtocolUpdateTypeInClass]\nimport a\n[file a.py]\nimport b\nclass C:\n    x: int\nclass A:\n    class B:\n        x: b.P\n    y: B\nA().y.x = C()\n[file b.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[file b.py.2]\nfrom typing import Protocol\nclass P(Protocol):\n    x: str\n[out]\n==\na.py:8: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\na.py:8: note: Following member(s) of \"C\" have conflicts:\na.py:8: note:     x: expected \"str\", got \"int\"\n\n[case testProtocolAddAttrInFunction]\nimport a\n[file a.py]\nimport b\nclass C:\n    x: int\ndef f() -> None:\n    c: C\n    def g(x: b.P) -> None:\n        pass\n    g(c)\n[file b.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[file b.py.2]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n    y: str\n[out]\n==\na.py:8: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:8: note: \"C\" is missing following \"P\" protocol member:\na.py:8: note:     y\n\n[case testProtocolRemoveAttrInClass]\nimport a\n[file a.py]\nimport b\nclass C:\n    x: int\nclass A:\n    class B:\n        x: b.P\n    y: B\nA().y.x = C()\n[file b.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n    y: str\n[file b.py.2]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[out]\na.py:8: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\na.py:8: note: \"C\" is missing following \"P\" protocol member:\na.py:8: note:     y\n==\n\n[case testProtocolConcreteUpdateTypeFunction]\nimport a\n[file a.py]\nimport b\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\ndef f() -> None:\n    def g(x: P) -> None:\n        pass\n    g(b.C())\n[file b.py]\nclass C:\n    x: int\n[file b.py.2]\nclass C:\n    x: str\n[out]\n==\na.py:8: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:8: note: Following member(s) of \"C\" have conflicts:\na.py:8: note:     x: expected \"int\", got \"str\"\n\n[case testProtocolConcreteUpdateTypeMethodGeneric]\nimport a\n[file a.py]\nimport b\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\nclass P(Protocol[T]):\n    x: T\nclass C:\n    def g(self, x: P[int]) -> None:\n        pass\n    def do(self) -> None:\n        self.g(b.C())\n[file b.py]\nclass C:\n    x: int\n[file b.py.2]\nclass C:\n    x: str\n[out]\n==\na.py:10: error: Argument 1 to \"g\" of \"C\" has incompatible type \"C\"; expected \"P[int]\"\na.py:10: note: Following member(s) of \"C\" have conflicts:\na.py:10: note:     x: expected \"int\", got \"str\"\n\n[case testProtocolConcreteRemoveAttrVariable]\nimport a\n[file a.py]\nimport b, c\ncc: c.C\nx: b.P = cc\n[file b.py]\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\n[file c.py]\nclass C:\n    x: int\n[file c.py.2]\nclass C:\n    pass\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\n\n[case testProtocolUpdateBaseGeneric]\nimport a\n[file a.py]\nimport b, c\ndef g(x: c.P) -> None:\n    pass\ng(b.C())\n[file b.py]\nclass C:\n    x: int\n[file c.py]\nfrom typing import Protocol\nimport d\nclass P(d.PBase[int], Protocol):\n    pass\n[file c.py.2]\nfrom typing import Protocol\nimport d\nclass P(d.PBase[str], Protocol):\n    pass\n[file d.py]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\nclass PBase(Protocol[T]):\n    x: T\n[out]\n==\na.py:4: error: Argument 1 to \"g\" has incompatible type \"C\"; expected \"P\"\na.py:4: note: Following member(s) of \"C\" have conflicts:\na.py:4: note:     x: expected \"str\", got \"int\"\n\n[case testProtocolConcreteUpdateBaseGeneric]\nimport a\n[file a.py]\nimport b\nfrom typing import Protocol\nclass P(Protocol):\n    x: int\ndef f(x: P) -> None:\n    pass\nf(b.B())\n[file b.py]\nimport c\nclass B(c.C[int]):\n    pass\n[file b.py.2]\nimport c\nclass B(c.C[str]):\n    pass\n[file c.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]):\n    x: T\n[out]\n==\na.py:7: error: Argument 1 to \"f\" has incompatible type \"B\"; expected \"P\"\na.py:7: note: Following member(s) of \"B\" have conflicts:\na.py:7: note:     x: expected \"int\", got \"str\"\n\n[case testProtocolChangeGeneric]\nimport a\n[file a.py]\nimport b, c\nx: b.P = c.C()\n[file b.py]\nimport b2\nfrom typing import Protocol\nclass P(b2.P2[str], Protocol):\n    pass\n[file b2.py]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\nclass P2(Protocol[T]):\n    x: T\n[file b2.py.2]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\nclass P2(Protocol):\n    x: int\n[file c.py]\nclass C:\n    x: int\n[out]\na.py:2: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\na.py:2: note: Following member(s) of \"C\" have conflicts:\na.py:2: note:     x: expected \"str\", got \"int\"\n==\nb.py:3: error: \"P2\" expects no type arguments, but 1 given\n\n[case testProtocolToNonProtocol]\nimport a\n[file a.py]\nimport b, c\nb.f(c.C())\n[file b.py]\nimport d\ndef f(x: d.D) -> None:\n    pass\n[file c.py]\nimport d\nclass C:\n    x: int\n[file d.py]\nfrom typing import Protocol\nclass D(Protocol):\n    x: int\n[file d.py.2]\nclass D:\n    x: int\n[file c.py.3]\nimport d\nclass C(d.D):\n    pass\n[out]\n==\na.py:2: error: Argument 1 to \"f\" has incompatible type \"C\"; expected \"D\"\n==\n\n[case testNonProtocolToProtocol]\nimport a\n[file a.py]\nimport b, c\nb.f(c.C())\n[file b.py]\nimport d\ndef f(x: d.D) -> None:\n    pass\n[file c.py]\nimport d\nclass C(d.D):\n    pass\n[file d.py]\nclass D:\n    x: int\n[file d.py.2]\nfrom typing import Protocol\nclass D(Protocol):\n    x: int\n[file c.py.3]\nimport d\nclass C:\n    x: int\n[out]\n==\na.py:2: error: Cannot instantiate abstract class \"C\" with abstract attribute \"x\"\n==\n\n[case testInvalidateProtocolViaSuperClass]\nimport a\n[file a.py]\nimport b, c\ndef func(x: c.P) -> None:\n    pass\nfunc(b.B())\n[file b.py]\nclass B:\n    x: int\n    y: str\n[file c.py]\nfrom typing import Protocol\nimport d\nclass P(d.PBase, Protocol):\n    x: int\n[file d.py]\nfrom typing import Protocol\nclass PBase(Protocol):\n    y: str\n[file d.py.2]\nfrom typing import Protocol\nclass PBase(Protocol):\n    y: int\n[out]\n==\na.py:4: error: Argument 1 to \"func\" has incompatible type \"B\"; expected \"P\"\na.py:4: note: Following member(s) of \"B\" have conflicts:\na.py:4: note:     y: expected \"int\", got \"str\"\n\n[case testProtocolInvalidateConcreteViaSuperClassUpdateType]\nimport a\n[file a.py]\nimport b\ndef func(x: b.P) -> None:\n    pass\nfunc(b.B())\n[file b.py]\nfrom typing import Protocol\nimport c\nclass P(Protocol):\n    x: int\nclass B(c.C):\n    pass\n[file c.py]\nclass C:\n    x: int\n[file c.py.2]\nclass C:\n    x: str\n[out]\n==\na.py:4: error: Argument 1 to \"func\" has incompatible type \"B\"; expected \"P\"\na.py:4: note: Following member(s) of \"B\" have conflicts:\na.py:4: note:     x: expected \"int\", got \"str\"\n\n[case testProtocolInvalidateConcreteViaSuperClassAddAttr]\nimport a\n[file a.py]\nimport b\ndef func(x: b.P) -> None:\n    pass\nbb: b.B\nfunc(bb)\n[file b.py]\nfrom typing import Protocol\nimport c\nclass P(Protocol):\n    x: int\nclass B(c.C):\n    pass\n[file c.py]\nclass C:\n    pass\n[file c.py.2]\nclass C:\n    x: int\n[out]\na.py:5: error: Argument 1 to \"func\" has incompatible type \"B\"; expected \"P\"\n==\n\n[case testProtocolInvalidateConcreteViaSuperClassRemoveAttr]\nimport a\n[file a.py]\nimport b\ndef func(x: b.P) -> None:\n    pass\nfunc(b.B())\n[file b.py]\nfrom typing import Protocol\nimport c\nclass P(Protocol):\n    x: int\nclass B(c.C):\n    pass\n[file c.py]\nclass C:\n    x: int\n[file c.py.2]\nclass C:\n    pass\n[out]\n==\na.py:4: error: Argument 1 to \"func\" has incompatible type \"B\"; expected \"P\"\n\n[case testTwoProtocolsTwoFilesCrossedUpdateType-only_when_nocache]\n# this test and the next one (TwoProtocolsTwoFilesCrossedDeleteAttr) has errors ordered\n# opposite way with and without cache, therefore skip one of each.\nimport a\n[file a.py]\nimport b1\nimport b2\n[file b1.py]\nimport b2, d\nfrom typing import Protocol\nclass P1(Protocol):\n    x: int\ndef f(x: b2.P2) -> None:\n    pass\nf(d.D())\n[file b2.py]\nimport b1, d\nfrom typing import Protocol\nclass P2(Protocol):\n    x: int\ndef f(x: b1.P1) -> None:\n    pass\nf(d.D())\n[file d.py]\nclass D:\n    x: int\n[file d.py.2]\nclass D:\n    x: str\n[out]\n==\nb1.py:7: error: Argument 1 to \"f\" has incompatible type \"D\"; expected \"P2\"\nb1.py:7: note: Following member(s) of \"D\" have conflicts:\nb1.py:7: note:     x: expected \"int\", got \"str\"\nb2.py:7: error: Argument 1 to \"f\" has incompatible type \"D\"; expected \"P1\"\nb2.py:7: note: Following member(s) of \"D\" have conflicts:\nb2.py:7: note:     x: expected \"int\", got \"str\"\n\n[case testTwoProtocolsTwoFilesCrossedDeleteAttr-only_when_cache]\nimport a\n[file a.py]\nimport b1\nimport b2\n[file b1.py]\nimport b2, d\nfrom typing import Protocol\nclass P1(Protocol):\n    x: int\ndef f(x: b2.P2) -> None:\n    pass\nf(d.D())\n[file b2.py]\nimport b1, d\nfrom typing import Protocol\nclass P2(Protocol):\n    x: int\ndef f(x: b1.P1) -> None:\n    pass\nf(d.D())\n[file d.py]\nclass D:\n    x: int\n[file d.py.2]\nclass D:\n    y: int\n[out]\nb2.py:7: error: Argument 1 to \"f\" has incompatible type \"D\"; expected \"P2\" (diff)\nb1.py:7: error: Argument 1 to \"f\" has incompatible type \"D\"; expected \"P1\"\n\n[case testProtocolsInvalidateByRemovingBase]\nimport a\n[file a.py]\nimport b\ndef func(x: b.P) -> None:\n    pass\nfunc(b.B())\n[file b.py]\nfrom typing import Protocol\nimport c\nclass P(Protocol):\n    x: int\nclass B(c.C):\n    pass\n[file c.py]\nimport d\nclass C(d.D):\n    pass\n[file c.py.2]\nimport d\nclass C:\n    pass\n[file d.py]\nclass D:\n    x: int\n[out]\n==\na.py:4: error: Argument 1 to \"func\" has incompatible type \"B\"; expected \"P\"\n\n[case testProtocolsInvalidateByRemovingMetaclass]\nimport a\n[file a.py]\nimport b\ndef func(x: b.P) -> None:\n    pass\nfunc(b.B)\n[file b.py]\nfrom typing import Protocol\nimport c\nclass P(Protocol):\n    x: int\nclass B(c.C):\n    pass\n[file c.py]\nimport d\nclass C(metaclass=d.M):\n    pass\n[file c.py.2]\nimport d\nclass C:\n    pass\n[file d.py]\nclass M(type):\n    x: int\n[out]\n==\na.py:4: error: Argument 1 to \"func\" has incompatible type \"Type[B]\"; expected \"P\"\n\n[case testProtocolVsProtocolSubUpdated]\nimport a\n[file a.py]\nimport b, c\nx: b.SuperP\ny: c.SubP\nx = y\n[file b.py]\nfrom typing import Protocol\nclass SuperP(Protocol):\n    x: int\n[file c.py]\nfrom typing import Protocol\nimport d\nclass SubP(d.PBase, Protocol):\n    y: str\n[file d.py]\nfrom typing import Protocol\nclass PBase(Protocol):\n    x: int\n[file d.py.2]\nfrom typing import Protocol\nclass PBase(Protocol):\n    x: str\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"SubP\", variable has type \"SuperP\")\na.py:4: note: Following member(s) of \"SubP\" have conflicts:\na.py:4: note:     x: expected \"int\", got \"str\"\n\n[case testProtocolVsProtocolSuperUpdated]\nimport a\n[file a.py]\nimport b, c\nx: b.SuperP\ny: c.SubP\nx = y\n[file b.py]\nfrom typing import Protocol\nimport d\nclass SuperP(d.PBase, Protocol):\n    pass\n[file c.py]\nfrom typing import Protocol\nclass SubP(Protocol):\n    x: int\n[file d.py]\nfrom typing import Protocol\nclass PBase(Protocol):\n    x: int\n[file d.py.2]\nfrom typing import Protocol\nclass PBase(Protocol):\n    y: int\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"SubP\", variable has type \"SuperP\")\n\n[case testProtocolVsProtocolSuperUpdated2]\nimport a\n[file a.py]\nimport b, c\nx: b.SuperP\ny: c.SubP\nx = y\n[file b.py]\nfrom typing import Protocol\nimport d\nclass SuperP(d.PBase, Protocol):\n    x: int\n[file c.py]\nfrom typing import Protocol\nclass SubP(Protocol):\n    x: int\n    y: int\n[file d.py]\nfrom typing import Protocol\nclass PBase(Protocol):\n    y: int\n[file d.py.2]\nfrom typing import Protocol\nclass PBase(Protocol):\n    y: int\n    z: int\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"SubP\", variable has type \"SuperP\")\na.py:4: note: \"SubP\" is missing following \"SuperP\" protocol member:\na.py:4: note:     z\n\n[case testProtocolVsProtocolSuperUpdated3]\nimport a\n[file a.py]\nimport b, c\nx: b.SuperP\ny: c.SubP\nx = y\n[file b.py]\nfrom typing import Protocol\nimport d\nclass SuperP(d.PBase, Protocol):\n    x: int\n[file c.py]\nfrom typing import Protocol\nclass SubP(Protocol):\n    x: int\n    y: int\n[file d.py]\nfrom typing import Protocol\nimport e\nclass PBase(Protocol):\n    y: int\n[file d.py.2]\nfrom typing import Protocol\nimport e\nclass PBase(e.NewP, Protocol):\n    y: int\n[file e.py]\nfrom typing import Protocol\nclass NewP(Protocol):\n    z: int\n[out]\n==\na.py:4: error: Incompatible types in assignment (expression has type \"SubP\", variable has type \"SuperP\")\na.py:4: note: \"SubP\" is missing following \"SuperP\" protocol member:\na.py:4: note:     z\n\n[case testProtocolMultipleUpdates]\nimport a\n[file a.py]\nimport b, c\nx: b.P = c.C()\n[file b.py]\nfrom typing import Protocol\nimport b2\nclass P(b2.P2, Protocol):\n    x: int\n[file b2.py]\nfrom typing import Protocol\nclass P2(Protocol):\n    y: int\n[file c.py]\nimport c2\nclass C(c2.C2):\n    x: int\n[file c2.py]\nclass C2:\n    y: int\n[file b2.py.2]\nfrom typing import Protocol\nclass P2(Protocol):\n    y: int\n    z: int\n[file c2.py.3]\nclass C2:\n    y: int\n    z: int\n[file c2.py.4]\nclass C2:\n    y: int\n    z: str\n[out]\n==\na.py:2: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\na.py:2: note: \"C\" is missing following \"P\" protocol member:\na.py:2: note:     z\n==\n==\na.py:2: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\na.py:2: note: Following member(s) of \"C\" have conflicts:\na.py:2: note:     z: expected \"int\", got \"str\"\n\n[case testWeAreCarefulWithBuiltinProtocols]\nimport a\nx: a.A\nfor i in x:\n    pass\n[file a.py]\nfrom typing import Iterator\nclass A:\n    def __iter__(self) -> Iterator[int]:\n        pass\n[file a.py.2]\nclass A:\n    pass\n[out]\n==\nmain:3: error: \"A\" has no attribute \"__iter__\" (not iterable)\n\n[case testWeAreCarefulWithBuiltinProtocolsBase]\nimport a\nx: a.A\nfor i in x:\n    pass\n[file a.py]\nimport b\nclass A(b.B):\n    pass\n[file a.py.2]\nclass A:\n    pass\n[file b.py]\nfrom typing import Iterator\nclass B:\n    def __iter__(self) -> Iterator[int]:\n        pass\n[out]\n==\nmain:3: error: \"A\" has no attribute \"__iter__\" (not iterable)\n\n[case testOverloadsSimpleFrom]\nimport a\n[file a.py]\nimport mod\ndef f() -> None:\n    x: str = mod.f(str())\n[file mod.py]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\ndef f(x):\n    pass\n[file mod.py.2]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> int: pass\ndef f(x):\n    pass\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testOverloadsSimpleToNested]\nfrom typing import overload, Any\nimport mod\ndef outer() -> None:\n    @overload\n    def f(x: int) -> None: pass\n    @overload\n    def f(x: str) -> str: pass\n    def f(x: Any) -> Any:\n        y: int = mod.f()\n        return y\n[file mod.py]\ndef f() -> int:\n    pass\n[file mod.py.2]\ndef f() -> str:\n    pass\n[out]\n==\nmain:9: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testOverloadsRemovedOverload]\nimport mod\ndef f() -> None:\n    x: str = mod.f(str())\n[file mod.py]\nclass C: pass\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\n@overload\ndef f(x: C) -> int: pass\ndef f(x):\n    pass\n[file mod.py.2]\nclass C: pass\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: C) -> int: pass\ndef f(x):\n    pass\n[out]\n==\nmain:3: error: No overload variant of \"f\" matches argument type \"str\"\nmain:3: note: Possible overload variants:\nmain:3: note:     def f(x: int) -> None\nmain:3: note:     def f(x: C) -> int\n\n[case testOverloadsDeleted]\nimport mod\ndef f() -> None:\n    x: str = mod.f(str())\n[file mod.py]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\ndef f(x):\n    pass\n[file mod.py.2]\nfrom typing import overload\n[builtins fixtures/module.pyi]\n[out]\n==\nmain:3: error: Module has no attribute \"f\"\n\n[case testOverloadsUpdatedTypeRecheckImplementation]\nfrom typing import overload\nimport mod\nclass Outer:\n    @overload\n    def f(self, x: mod.D) -> mod.D: pass\n    @overload\n    def f(self, x: mod.E) -> mod.E: pass\n    def f(self, x: mod.C) -> mod.C:\n        x.x = int()\n        return x\n[file mod.py]\nimport submod\nclass C(submod.B):\n    pass\nclass D(C):\n    pass\nclass E(C):\n    pass\n[file submod.py]\nimport base\nclass B(base.AI):\n    pass\n[file submod.py.2]\nimport base\nclass B(base.AS):\n    pass\n[file base.py]\nclass AI:\n    x: int\nclass AS:\n    x: str\n[out]\n==\nmain:9: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testOverloadsUpdatedTypeRecheckConsistency]\nfrom typing import overload\nimport mod\nclass Outer:\n    @overload\n    def f(self, x: mod.D) -> mod.D: pass\n    @overload\n    def f(self, x: mod.E) -> mod.E: pass\n    def f(self, x: mod.C) -> mod.C:\n        pass\n[file mod.py]\nclass C:\n    pass\nclass D(C):\n    pass\nclass E(C):\n    pass\n[file mod.py.2]\nclass C:\n    pass\nclass D(C):\n    pass\nclass E:\n    pass\n[out]\n==\nmain:8: error: Overloaded function implementation does not accept all possible arguments of signature 2\nmain:8: error: Overloaded function implementation cannot produce return type of signature 2\n\n[case testOverloadsGenericTypevarUpdated]\nimport a\n[file a.py]\nimport b\nb.f(int())\n[file b.py]\nfrom typing import overload\nimport c\nclass C: pass\n@overload\ndef f(x: C) -> None: pass\n@overload\ndef f(x: c.T) -> c.T: pass\ndef f(x):\n    pass\n[file c.py]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\n[file c.py.2]\nfrom typing import TypeVar\nT = TypeVar('T', bound=str)\n[out]\n==\na.py:2: error: No overload variant of \"f\" matches argument type \"int\"\na.py:2: note: Possible overload variants:\na.py:2: note:     def f(x: C) -> None\na.py:2: note:     def [c.T: str] f(x: c.T) -> c.T\n\n[case testOverloadsGenericToNonGeneric]\nimport a\n[file a.py]\nimport b\nb.f(int())\n[file b.py]\nfrom typing import overload\nimport c\nclass C: pass\n@overload\ndef f(x: C) -> None: pass\n@overload\ndef f(x: c.T) -> c.T: pass\ndef f(x):\n    pass\n[file c.py]\nfrom typing import TypeVar\nT = TypeVar('T', bound=int)\n[file c.py.2]\nfrom typing import TypeVar\nclass T: pass\n[out]\n==\na.py:2: error: No overload variant of \"f\" matches argument type \"int\"\na.py:2: note: Possible overload variants:\na.py:2: note:     def f(x: C) -> None\na.py:2: note:     def f(x: T) -> T\n\n[case testOverloadsToNonOverloaded]\nimport a\n[file a.py]\nimport mod\ndef f() -> None:\n    x: str = mod.f(str())\n[file mod.py]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\ndef f(x):\n    pass\n[file mod.py.2]\nfrom typing import overload\ndef f(x: int) -> int:\n    pass\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\na.py:3: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testOverloadsUpdateFunctionToOverloaded]\nimport a\n[file a.py]\nimport mod\ndef f() -> None:\n    x: str = mod.f(str())\n[file mod.py]\nfrom typing import overload\ndef f(x: str) -> str:\n    pass\n[file mod.py.2]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> int: pass\ndef f(x):\n    pass\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testOverloadedUpdateToClass]\nimport a\n[file a.py]\nimport mod\ndef f() -> None:\n    x: str = mod.f(str())\n[file mod.py]\nfrom typing import overload\n@overload\ndef f(x: int) -> None: pass\n@overload\ndef f(x: str) -> str: pass\ndef f(x):\n    pass\n[file mod.py.2]\nfrom typing import overload\nclass f:\n    def __init__(self, x: str) -> None:\n        pass\n[out]\n==\na.py:3: error: Incompatible types in assignment (expression has type \"f\", variable has type \"str\")\n\n[case testDepsFromOverloadUpdatedAttrRecheckImpl]\nimport mod\nx = mod.f\n[file mod.py]\nfrom typing import overload, Any\nimport submod\n@overload\ndef f(x: int) -> submod.A: pass\n@overload\ndef f(x: str) -> submod.B: pass\ndef f(x) -> Any:\n    y: submod.C\n    y.x = int()\n    return y\n[file submod.py]\nimport other\nclass A: pass\nclass B: pass\nC = other.C\n[file other.py]\nclass C:\n    x: int\n[file other.py.2]\nclass C:\n    x: str\n[out]\n==\nmod.py:9: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testOverloadedMethodSupertype-only_when_cache]\n-- Different cache/no-cache tests because\n-- CallableType.def_extras.first_arg differs (\"self\"/None)\nfrom typing import overload, Any\nimport b\nclass Child(b.Parent):\n    @overload                           # Fail\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n[file b.py]\nfrom typing import overload, Any\nclass C: pass\nclass Parent:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n[file b.py.2]\nfrom typing import overload, Any\nclass C: pass\nclass Parent:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> C: ...\n    def f(self, arg: Any) -> Any: ...\n[out]\n==\nmain:4: error: Signature of \"f\" incompatible with supertype \"Parent\"\nmain:4: note:      Superclass:\nmain:4: note:          @overload\nmain:4: note:          def f(self, arg: int) -> int\nmain:4: note:          @overload\nmain:4: note:          def f(self, arg: str) -> C\nmain:4: note:      Subclass:\nmain:4: note:          @overload\nmain:4: note:          def f(self, arg: int) -> int\nmain:4: note:          @overload\nmain:4: note:          def f(self, arg: str) -> str\n\n[case testOverloadedMethodSupertype2-only_when_nocache]\n-- Different cache/no-cache tests because\n-- CallableType.def_extras.first_arg differs (\"self\"/None)\nfrom typing import overload, Any\nimport b\nclass Child(b.Parent):\n    @overload                           # Fail\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n[file b.py]\nfrom typing import overload, Any\nclass C: pass\nclass Parent:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> str: ...\n    def f(self, arg: Any) -> Any: ...\n[file b.py.2]\nfrom typing import overload, Any\nclass C: pass\nclass Parent:\n    @overload\n    def f(self, arg: int) -> int: ...\n    @overload\n    def f(self, arg: str) -> C: ...\n    def f(self, arg: Any) -> Any: ...\n[out]\n==\nmain:4: error: Signature of \"f\" incompatible with supertype \"Parent\"\nmain:4: note:      Superclass:\nmain:4: note:          @overload\nmain:4: note:          def f(self, arg: int) -> int\nmain:4: note:          @overload\nmain:4: note:          def f(self, arg: str) -> C\nmain:4: note:      Subclass:\nmain:4: note:          @overload\nmain:4: note:          def f(arg: int) -> int\nmain:4: note:          @overload\nmain:4: note:          def f(arg: str) -> str\n\n[case testOverloadedInitSupertype]\nimport a\n[file a.py]\nfrom b import B\nB(int())\n[file b.py]\nimport c\nclass B(c.C):\n    pass\n[file c.py]\nfrom typing import overload\nclass C:\n    def __init__(self, x: int) -> None:\n        pass\n[file c.py.2]\nfrom typing import overload\nclass C:\n    @overload\n    def __init__(self, x: str) -> None: pass\n    @overload\n    def __init__(self, x: str, y: int) -> None: pass\n    def __init__(self, *args, **kwargs) -> None:\n        pass\n[builtins fixtures/dict.pyi]\n[out]\n==\na.py:2: error: No overload variant of \"B\" matches argument type \"int\"\na.py:2: note: Possible overload variants:\na.py:2: note:     def __init__(self, x: str) -> B\na.py:2: note:     def __init__(self, x: str, y: int) -> B\n\n[case testOverloadedToNormalMethodMetaclass]\nimport a\n[file a.py]\nimport b\nb.B.f(int())\n[file b.py]\nimport c\nclass B(metaclass=c.M):\n    pass\n[file c.py]\nfrom typing import overload\nclass M(type):\n    @overload\n    def f(cls, x: str) -> str: pass\n    @overload\n    def f(cls, x: int) -> None: pass\n    def f(cls, x):\n        pass\n[file c.py.2]\nfrom typing import overload\nclass M(type):\n    def f(cls, x: str) -> str:\n        pass\n[out]\n==\na.py:2: error: Argument 1 to \"f\" of \"M\" has incompatible type \"int\"; expected \"str\"\n\n[case testYieldFrom]\nfrom typing import Iterator\nfrom a import f\n\ndef g() -> Iterator[int]:\n    a = \"string\"\n    if int():\n        a = yield from f()\n\n[file a.py]\nfrom typing import Generator\n\ndef f() -> Generator[int, None, str]:\n    yield 5\n    return \"ham\"\n\n[file a.py.2]\nfrom typing import Generator\n\nclass A: pass\n\ndef f() -> Generator[int, None, A]:\n    yield 5\n    return A()\n\n[out]\n==\nmain:7: error: Incompatible types in assignment (expression has type \"A\", variable has type \"str\")\n\n[case testFString]\nfrom a import g\nf'{g(1)}'\n[file a.py]\ndef g(x: int) -> str: pass\n[file a.py.2]\ndef g(x: str) -> str: pass\n[builtins fixtures/f_string.pyi]\n[out]\n==\nmain:2: error: Argument 1 to \"g\" has incompatible type \"int\"; expected \"str\"\n\n[case testExtendedUnpacking-only_when_nocache]\nfrom typing import List\nfrom a import g\ndef f() -> List[int]:\n    a, *b = g()\n    return b\n\n[file a.py]\nfrom typing import Tuple\ndef g() -> Tuple[str, int, int]: pass\n\n[file a.py.2]\nfrom typing import Tuple\ndef g() -> Tuple[str, str]: pass\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:5: error: Incompatible return value type (got \"List[str]\", expected \"List[int]\")\n\n[case testUnpackInExpression1-only_when_nocache]\nfrom typing import Tuple, List\nfrom a import t\n\ndef f() -> Tuple[int, int]:\n    return (1, *t())\n\ndef g() -> List[int]:\n    return [1, *t()]\n\n[file a.py]\nfrom typing import Tuple\ndef t() -> Tuple[int]: ...\n\n[file a.py.2]\nfrom typing import Tuple\ndef t() -> Tuple[str]: ...\n\n[builtins fixtures/list.pyi]\n[out]\n==\nmain:5: error: Incompatible return value type (got \"Tuple[int, str]\", expected \"Tuple[int, int]\")\nmain:8: error: List item 1 has incompatible type \"Tuple[str]\"; expected \"int\"\n\n[case testUnpackInExpression2-only_when_nocache]\nfrom typing import Set\nfrom a import t\n\ndef f() -> Set[int]:\n    return {1, *t()}\n\n[file a.py]\nfrom typing import Tuple\ndef t() -> Tuple[int]: pass\n\n[file a.py.2]\nfrom typing import Tuple\ndef t() -> Tuple[str]: pass\n\n[builtins fixtures/set.pyi]\n[out]\n==\nmain:5: error: Argument 2 to <set> has incompatible type \"*Tuple[str]\"; expected \"int\"\n\n[case testUnpackInExpression3-only_when_nocache]\nfrom typing import Dict\nfrom a import d\n\ndef f() -> Dict[int, str]:\n    return {1: '', **d()}\n\n[file a.py]\nfrom typing import Dict\ndef d() -> Dict[int, str]: pass\n\n[file a.py.2]\nfrom typing import Dict\ndef d() -> Dict[int, int]: pass\n\n[builtins fixtures/dict.pyi]\n[out]\n==\nmain:5: error: Unpacked dict entry 1 has incompatible type \"Dict[int, int]\"; expected \"SupportsKeysAndGetItem[int, str]\"\n\n[case testAwaitAndAsyncDef-only_when_nocache]\nfrom a import g\n\nasync def f() -> int:\n    return await g()\n\n[file a.py]\nasync def g() -> int:\n    return 0\n\n[file a.py.2]\nasync def g() -> str:\n    return ''\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n==\nmain:4: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testAwaitAnd__await__-only_when_nocache]\nfrom a import C\n\nasync def f(c: C) -> int:\n    return await c\n\n[file a.py]\nfrom typing import Any, Generator\nclass C:\n    def __await__(self) -> Generator[Any, None, int]:\n        yield\n        return 0\n\n[file a.py.2]\nfrom typing import Any, Generator\nclass C:\n    def __await__(self) -> Generator[Any, None, str]:\n        yield\n        return ''\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n==\nmain:4: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case test__aiter__and__anext__]\nfrom a import C\n\nasync def f() -> int:\n    async for x in C():\n        pass\n    return x\n\n[file a.py]\nclass C:\n    def __aiter__(self) -> D: pass\nclass D:\n    def __aiter__(self) -> D: pass\n    async def __anext__(self) -> int: return 0\n\n[file a.py.2]\nclass C:\n    def __aiter__(self) -> D: pass\nclass D:\n    def __aiter__(self) -> D: pass\n    async def __anext__(self) -> str: return ''\n\n[file a.py.3]\nclass C:\n    def __aiter__(self) -> E: pass\nclass E:\n    def __aiter__(self) -> E: pass\n    async def __anext__(self) -> object: return 0\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n==\nmain:6: error: Incompatible return value type (got \"str\", expected \"int\")\n==\nmain:6: error: Incompatible return value type (got \"object\", expected \"int\")\n\n[case testAsyncWith2-only_when_nocache]\nfrom a import C\n\nasync def f() -> int:\n    async with C() as x:\n        return x\n\nasync def g() -> None:\n    async with C(): pass\n\n[file a.py]\nclass C:\n    async def __aenter__(self) -> int: pass\n    async def __aexit__(self, x, y, z) -> None: pass\n\n[file a.py.2]\nclass C:\n    async def __aenter__(self) -> str: pass\n    async def __aexit__(self, x, y, z) -> None: pass\n\n[file a.py.3]\nfrom typing import Awaitable\nclass C:\n    async def __aenter__(self) -> int: pass\n    async def __aexit__(self, x, y, z) -> None: pass\n\n[file a.py.4]\nfrom typing import Awaitable\nclass C:\n    async def __aenter__(self) -> int: pass\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n==\nmain:5: error: Incompatible return value type (got \"str\", expected \"int\")\n==\n==\nmain:4: error: \"C\" has no attribute \"__aexit__\"\nmain:8: error: \"C\" has no attribute \"__aexit__\"\n\n[case testLiskovFineVariable]\nimport b\nclass A(b.B):\n    x: str\ndef f(x: b.B) -> None:\n    x.x + int()\nf(A())\n[file b.py]\nclass B:\n    x: str\n[file b.py.2]\nclass B:\n    x: int\n[builtins fixtures/primitives.pyi]\n[out]\nmain:5: error: Unsupported operand types for + (\"str\" and \"int\")\n==\nmain:3: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testLiskovFineVariableInFunction]\nfrom b import B\ndef outer() -> None:\n    class A(B):\n        x: str\n    def f(x: B) -> None:\n        x.x + int()\n[file b.py]\nclass B:\n    x: str\n[file b.py.2]\nclass B:\n    x: int\n[builtins fixtures/primitives.pyi]\n[out]\nmain:6: error: Unsupported operand types for + (\"str\" and \"int\")\n==\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testLiskovFineDecorator]\nimport b\nfrom c import deco\nclass A(b.B):\n    @deco\n    def m(self) -> str: pass\ndef f(x: b.B) -> None:\n    x.m() + int()\nf(A())\n[file b.py]\nfrom c import deco\nclass B:\n    @deco\n    def m(self) -> str: pass\n[file b.py.2]\nfrom c import deco\nclass B:\n    @deco\n    def m(self) -> int: pass\n[file c.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\ndef deco(f: F) -> F:\n    pass\n[builtins fixtures/primitives.pyi]\n[out]\nmain:7: error: Unsupported operand types for + (\"str\" and \"int\")\n==\nmain:5: error: Return type \"str\" of \"m\" incompatible with return type \"int\" in supertype \"B\"\n\n[case testLiskovFineVariableClean-only_when_nocache]\nimport b\nclass A(b.B):\n    x: str\n[file b.py]\nclass B:\n    x: str\n[file b.py.2]\nclass B:\n    x: int\n[out]\n==\nmain:3: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testLiskovFineVariableCleanDefInMethod-only_when_nocache]\nimport b\nclass A(b.B):\n    def meth(self) -> None:\n        self.x: str\n[file b.py]\nclass B:\n    x: str\n[file b.py.2]\nclass B:\n    x: int\n[out]\n==\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testLiskovFineVariableCleanDefInMethodStar-only_when_nocache]\nfrom typing import List\nimport b\nclass A(b.B):\n    def meth(self) -> None:\n        self.x: str\n        self.y: List[str]\n[file b.py]\nfrom typing import List\nclass B:\n    y: List[str]\n[file b.py.2]\nfrom typing import List\nclass B:\n    y: List[int]\n[builtins fixtures/list.pyi]\n[out]\n==\nmain:6: error: Incompatible types in assignment (expression has type \"List[str]\", base class \"B\" defined the type as \"List[int]\")\n\n[case testLiskovFineVariableCleanDefInMethodNested-only_when_nocache]\nfrom b import B\ndef outer() -> None:\n    class A(B):\n        def meth(self) -> None:\n            self.x: str\n[file b.py]\nclass B:\n    x: str\n[file b.py.2]\nclass B:\n    x: int\n[out]\n==\nmain:5: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testLiskovFineVariableInFunctionClean-only_when_nocache]\nfrom b import B\ndef outer() -> None:\n    class A(B):\n        x: str\n[file b.py]\nclass B:\n    x: str\n[file b.py.2]\nclass B:\n    x: int\n[out]\n==\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testLiskovFineDecoratorClean-only_when_nocache]\nimport b\nfrom c import deco\nclass A(b.B):\n    @deco\n    def m(self) -> str: pass\n[file b.py]\nfrom c import deco\nclass B:\n    @deco\n    def m(self) -> str: pass\n[file b.py.2]\nfrom c import deco\nclass B:\n    @deco\n    def m(self) -> int: pass\n[file c.py]\nfrom typing import Callable, TypeVar\nF = TypeVar('F', bound=Callable)\ndef deco(f: F) -> F:\n    pass\n[out]\n==\nmain:5: error: Return type \"str\" of \"m\" incompatible with return type \"int\" in supertype \"B\"\n\n[case testAddAbstractMethod]\nfrom b import D\nD()\n[file b.py]\nfrom a import C\nclass D(C):\n    def f(self) -> None: pass\n[file a.py]\nfrom abc import abstractmethod\nclass C:\n    @abstractmethod\n    def f(self) -> None: pass\n[file a.py.2]\nfrom abc import abstractmethod\nclass C:\n    @abstractmethod\n    def f(self) -> None: pass\n    @abstractmethod\n    def g(self) -> None: pass\n[file a.py.3]\nfrom abc import abstractmethod\nclass C:\n    @abstractmethod\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n[out]\n==\nmain:2: error: Cannot instantiate abstract class \"D\" with abstract attribute \"g\"\n==\n\n[case testMakeClassAbstract]\nfrom a import C\nc = C()\n[file a.py]\nfrom abc import abstractmethod\nclass C: pass\n[file a.py.2]\nfrom abc import abstractmethod\nclass C:\n    @abstractmethod\n    def f(self) -> None: pass\n[out]\n==\nmain:2: error: Cannot instantiate abstract class \"C\" with abstract attribute \"f\"\n\n[case testMakeMethodNoLongerAbstract1]\n[file z.py]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n    @abstractmethod\n    def g(self) -> None: pass\n[file b.py]\nimport z\ndef x() -> Foo: return Foo()\nclass Foo(z.I):\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n\n[file z.py.2]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    def f(self) -> None: pass\n    @abstractmethod\n    def g(self) -> None: pass\n\n[file b.py.2]\nimport z\ndef x() -> Foo: return Foo()\nclass Foo(z.I):\n    def g(self) -> None: pass\n[out]\n==\n\n[case testMakeMethodNoLongerAbstract2]\n-- this version never failed, but it is just a file-renaming\n-- away from the above test that did\n[file a.py]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n    @abstractmethod\n    def g(self) -> None: pass\n[file b.py]\nimport a\ndef x() -> Foo: return Foo()\nclass Foo(a.I):\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n\n[file a.py.2]\nfrom abc import abstractmethod, ABCMeta\nclass I(metaclass=ABCMeta):\n    def f(self) -> None: pass\n    @abstractmethod\n    def g(self) -> None: pass\n\n[file b.py.2]\nimport a\ndef x() -> Foo: return Foo()\nclass Foo(a.I):\n    def g(self) -> None: pass\n[out]\n==\n\n[case testImplicitOptionalRefresh1]\n# flags: --implicit-optional\nfrom x import f\ndef foo(x: int = None) -> None:\n    f()\n[file x.py]\ndef f() -> int: return 0\n[file x.py.2]\ndef f() -> str: return '0'\n[out]\n==\n\n[case testRefreshIgnoreErrors1]\n[file mypy.ini]\n\\[mypy]\n\\[mypy-b]\nignore_errors = True\n[file a.py]\ny = '1'\n[file a.py.2]\ny = 1\n[file b.py]\nfrom a import y\ndef fu() -> None:\n    1+'lurr'\n    y\n[out]\n==\n\n[case testRefreshIgnoreErrors2]\n[file mypy.ini]\n\\[mypy]\n\\[mypy-b]\nignore_errors = True\n[file b.py]\ndef fu() -> int:\n    1+'lurr'\n    return 1\n[file b.py.2]\ndef fu() -> int:\n    1+'lurr'\n    return 2\n[out]\n==\n\n[case testRefreshOptions]\n[file mypy.ini]\n\\[mypy]\ndisallow_any_generics = True\n\\[mypy-b]\ndisallow_any_generics = False\n[file a.py]\ny = '1'\n[file a.py.2]\ny = 1\n[file b.py]\nfrom typing import List\nfrom a import y\nx = []  # type: List\n[builtins fixtures/list.pyi]\n[out]\n==\n\n[case testNamedTupleFallbackModule]\nimport b\n[file b.py]\nfrom a import A\ndef f(a: A):\n    pass\n[file b.py.2]\nfrom a import A\ndef f(a: A):\n    reveal_type(a)\n[file a.py]\nfrom typing import NamedTuple\n\nF = [('x', int)]\nA = NamedTuple('A', F)  # type: ignore\n[builtins fixtures/list.pyi]\n[out]\n==\nb.py:3: note: Revealed type is \"Tuple[(), fallback=a.A]\"\n\n[case testImportOnTopOfAlias1]\nfrom a import A\nx: A\n[file a.py]\nfrom typing import TypeVar, List\nT = TypeVar('T')\nA = List[T]\n[file a.py.2]\nfrom typing import TypeVar, List\nT = TypeVar('T')\nA = List[T]\nfrom b import A\n[file b.py]\n# empty\n[builtins fixtures/list.pyi]\n[out]\n==\na.py:4: error: Module \"b\" has no attribute \"A\"\na.py:4: error: Name \"A\" already defined on line 3\n\n-- the order of errors is different with cache\n[case testImportOnTopOfAlias2]\nfrom a import A\nx: A\n[file a.py]\nfrom typing import TypeVar, List\nT = TypeVar('T')\nA = List[T]\n[file a.py.2]\nfrom typing import TypeVar, List\nT = TypeVar('T')\nA = List[T]\nfrom b import A as A\n[file b.py]\ndef A(x: str) -> str: pass\n[builtins fixtures/list.pyi]\n[out]\n==\na.py:4: error: Incompatible import of \"A\" (imported name has type \"Callable[[str], str]\", local name has type \"Type[List[Any]]\")\n\n[case testFakeOverloadCrash]\nimport b\n[file a.py]\ndef dec(fun):\n    pass\na = 1\n[file a.py.2]\ndef dec(fun):\n    pass\na = 2\n[file b.py]\nfrom a import dec\n@dec\ndef a():\n    pass\n@dec\ndef a():\n    pass\n[out]\nb.py:5: error: Name \"a\" already defined on line 2\n==\nb.py:5: error: Name \"a\" already defined on line 2\n\n[case testFakeOverloadCrash2]\n\n# this test just should not crash\nimport a\n[file a.py]\nT = TypeVar(\"T\")\n\ndef foo(func):\n    return func\n\n@foo\ndef bar(x: T) -> T:\n    pass\n\n@foo\ndef bar(x: T) -> T:\n    pass\n[file a.py.2]\nT = TypeVar(\"T\")\n\ndef foo(func):\n    return func\n\n@foo\ndef bar(x: T) -> T:\n    pass\n\n@foo\ndef bar(x: T) -> T:\n    pass\nx = 1\n[out]\na.py:1: error: Name \"TypeVar\" is not defined\na.py:1: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import TypeVar\")\na.py:7: error: Variable \"a.T\" is not valid as a type\na.py:7: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:7: error: Variable \"a.T\" is not valid as a type\na.py:7: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:10: error: Name \"bar\" already defined on line 6\na.py:11: error: Variable \"a.T\" is not valid as a type\na.py:11: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:11: error: Variable \"a.T\" is not valid as a type\na.py:11: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n==\na.py:1: error: Name \"TypeVar\" is not defined\na.py:1: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import TypeVar\")\na.py:7: error: Variable \"a.T\" is not valid as a type\na.py:7: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:7: error: Variable \"a.T\" is not valid as a type\na.py:7: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:10: error: Name \"bar\" already defined on line 6\na.py:11: error: Variable \"a.T\" is not valid as a type\na.py:11: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:11: error: Variable \"a.T\" is not valid as a type\na.py:11: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testRefreshForWithTypeComment1]\n[file a.py]\nfrom typing import List\nimport b\ndef foo(l: List[int]) -> None:\n    for x in l:  # type: object\n        pass\n    x = object()\n    b.x\n[file b.py]\nx = 1\n[file b.py.2]\nx = '1'\n[builtins fixtures/list.pyi]\n[out]\n==\n\n[case testRefreshForWithTypeComment2]\nfrom typing import List, Any\nimport m\ndef f(x: List[Any]) -> None:\n    for a in x:  # type: m.A\n        pass\n[file m.py]\nclass A: pass\n[file m.py.2]\n[builtins fixtures/list.pyi]\n[out]\n==\nmain:4: error: Name \"m.A\" is not defined\n\n[case testIdLikeDecoForwardCrash]\nimport b\n[file b.py]\nfrom typing import Callable, Any, TypeVar\n\nF = TypeVar('F_BadName', bound=Callable[..., Any])  # type: ignore\ndef deco(func: F) -> F:  # type: ignore\n    pass\n\n@deco\ndef test(x: int, y: int) -> str:\n    pass\n[file b.py.2]\nfrom typing import Callable, Any, TypeVar\n\nF = TypeVar('F_BadName', bound=Callable[..., Any])  # type: ignore\ndef deco(func: F) -> F:  # type: ignore\n    pass\n\n@deco\ndef test(x: int, y: int) -> str:\n    pass\nx = 1\n[builtins fixtures/tuple.pyi]\n[out]\n==\n\n[case testIdLikeDecoForwardCrashAlias]\n# flags: --disable-error-code used-before-def\nimport b\n[file b.py]\nfrom typing import Callable, Any, TypeVar\n\nF = TypeVar('F', bound=Func)\ndef deco(func: F) -> F:\n    pass\n\n@deco\ndef test(x: int, y: int) -> str:\n    pass\nFunc = Callable[..., Any]\n[file b.py.2]\nfrom typing import Callable, Any, TypeVar\n\nF = TypeVar('F', bound=Func)\ndef deco(func: F) -> F:\n    pass\n\n@deco\ndef test(x: int, y: int) -> str:\n    pass\nx = 1\nFunc = Callable[..., Any]\n[out]\n==\n\n-- Test cases for final qualifier\n\n[case testFinalAddFinalVarAssignFine]\nimport mod\nfrom a import D\nfrom mod import x\n\nx = 2\ndef outer() -> None:\n    mod.x = 2\n    x = 2  # This is OK because it creates a local variable\n    d: D\n    d.y = 2\n    d.z = 2\n    D.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==\nmain:5: error: Cannot assign to final name \"x\"\nmain:7: error: Cannot assign to final name \"x\"\nmain:10: error: Cannot assign to final attribute \"y\"\nmain:11: error: Cannot assign to final attribute \"z\"\nmain:12: error: Cannot assign to final attribute \"y\"\n\n[case testFinalAddFinalVarOverrideFine]\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==\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 testFinalAddFinalMethodOverrideFine]\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==\nmain:4: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\n\n[case testFinalAddFinalMethodOverrideWithVarFine]\nfrom mod import C\nfrom typing import Any\n\nclass D(C):\n    meth: Any = 2\n    def __init__(self) -> None:\n        self.other: Any = 2\n\n[file mod.py]\nclass C:\n    def meth(self) -> int: ...\n    def other(self) -> int: ...\n\n[file mod.py.2]\nfrom typing import final\n\nclass C:\n    @final\n    def meth(self) -> int: ...\n    @final\n    def other(self) -> int: ...\n[out]\n==\nmain:5: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\nmain:7: error: Cannot assign to final attribute \"other\"\nmain:7: error: Cannot override final attribute \"other\" (previously declared in base class \"C\")\n\n[case testFinalAddFinalMethodOverrideOverloadFine]\nfrom typing import overload\nfrom mod import C\n\ndef outer() -> None:\n    class D(C):\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\n[file mod.pyi]\nfrom typing import overload\nclass C:\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n\n[file mod.pyi.2]\nfrom typing import final, overload\n\nclass C:\n    @final\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n[out]\n==\nmain:6: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\n\n[case testFinalAddFinalPropertyWithVarFine]\nfrom mod import C\n\ndef outer() -> None:\n    class D(C):\n        p = 2\n    class E(C):\n        def __init__(self) -> None:\n            self.p: int = 2\n\n[file mod.py]\nclass C:\n    @property\n    def p(self) -> int:\n        pass\n\n[file mod.py.2]\nfrom typing import final\n\nclass C:\n    @final\n    @property\n    def p(self) -> int:\n        pass\n[builtins fixtures/property.pyi]\n[out]\n==\nmain:5: error: Cannot override final attribute \"p\" (previously declared in base class \"C\")\nmain:8: error: Cannot assign to final attribute \"p\"\nmain:8: error: Cannot override final attribute \"p\" (previously declared in base class \"C\")\n\n[case testFinalBodyReprocessedAndStillFinal]\nimport a\n[file a.py]\nfrom c import C\nclass A:\n    def meth(self) -> None: ...\n\n[file a.py.3]\nfrom c import C\nclass A(C):\n    def meth(self) -> None: ...\n\n[file c.py]\nfrom typing import final\nfrom d import D\n\nclass C:\n    @final\n    def meth(self) -> None:\n        D(int())\n[file d.py]\nclass D:\n    def __init__(self, x: int) -> None: ...\n[file d.py.2]\nfrom typing import Optional\nclass D:\n    def __init__(self, x: Optional[int]) -> None: ...\n[out]\n==\n==\na.py:3: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\n\n[case testFinalBodyReprocessedAndStillFinalOverloaded-only_when_cache]\n-- Different cache/no-cache tests because\n-- CallableType.def_extras.first_arg differs (\"self\"/None)\nimport a\n[file a.py]\nfrom c import C\nclass A:\n    def meth(self) -> None: ...\n\n[file a.py.3]\nfrom c import C\nclass A(C):\n    def meth(self) -> None: ...\n\n[file c.py]\nfrom typing import final, overload, Union\nfrom d import D\n\nclass C:\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    @final\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        D(int())\n        return x\n[file d.py]\nclass D:\n    def __init__(self, x: int) -> None: ...\n[file d.py.2]\nfrom typing import Optional\nclass D:\n    def __init__(self, x: Optional[int]) -> None: ...\n[out]\n==\n==\na.py:3: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\na.py:3: error: Signature of \"meth\" incompatible with supertype \"C\"\na.py:3: note:      Superclass:\na.py:3: note:          @overload\na.py:3: note:          def meth(self, x: int) -> int\na.py:3: note:          @overload\na.py:3: note:          def meth(self, x: str) -> str\na.py:3: note:      Subclass:\na.py:3: note:          def meth(self) -> None\n\n[case testFinalBodyReprocessedAndStillFinalOverloaded2-only_when_nocache]\n-- Different cache/no-cache tests because\n-- CallableType.def_extras.first_arg differs (\"self\"/None)\nimport a\n[file a.py]\nfrom c import C\nclass A:\n    def meth(self) -> None: ...\n\n[file a.py.3]\nfrom c import C\nclass A(C):\n    def meth(self) -> None: ...\n\n[file c.py]\nfrom typing import final, overload, Union\nfrom d import D\n\nclass C:\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    @final\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        D(int())\n        return x\n[file d.py]\nclass D:\n    def __init__(self, x: int) -> None: ...\n[file d.py.2]\nfrom typing import Optional\nclass D:\n    def __init__(self, x: Optional[int]) -> None: ...\n[out]\n==\n==\na.py:3: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\na.py:3: error: Signature of \"meth\" incompatible with supertype \"C\"\na.py:3: note:      Superclass:\na.py:3: note:          @overload\na.py:3: note:          def meth(x: int) -> int\na.py:3: note:          @overload\na.py:3: note:          def meth(x: str) -> str\na.py:3: note:      Subclass:\na.py:3: note:          def meth(self) -> None\n\n[case testIfMypyUnreachableClass]\nfrom a import x\n\nMYPY = False\nif MYPY:\n    pass\nelse:\n    class A:\n        pass\ny: int = x\n[file a.py]\nx = 1\n[file a.py.2]\nx = 2\n[builtins fixtures/bool.pyi]\n[out]\n==\n\n[case testIfTypeCheckingUnreachableClass]\nfrom a import x\nfrom typing import TYPE_CHECKING\n\nif not TYPE_CHECKING:\n    class A(int):\n        pass\nelse:\n    A = int\n\ny: A = x\n[file a.py]\nx = 1\n[file a.py.2]\nx = 2\n[file a.py.3]\nx = 'no way'\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n==\n==\nmain:10: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testNamedTupleForwardFunctionDirect]\n# flags: --ignore-missing-imports\nfrom typing import NamedTuple\nfrom b import B\n\nNT = NamedTuple('NT', [('x', B)])\n[file b.py.2]\ndef func(x): pass\nB = func\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:5: error: Variable \"b.B\" is not valid as a type\nmain:5: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testNamedTupleForwardFunctionIndirect]\n# flags: --ignore-missing-imports\nfrom typing import NamedTuple\nfrom a import A\n\nNT = NamedTuple('NT', [('x', A)])\n[file a.py]\nfrom b import B\nA = B\n[file b.py.2]\ndef func(x): pass\nB = func\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:5: error: Variable \"a.A\" is not valid as a type\nmain:5: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testNamedTupleForwardFunctionIndirectReveal]\n# flags: --ignore-missing-imports\nimport m\n[file m.py]\nfrom typing import NamedTuple\nfrom a import A\n\nNT = NamedTuple('NT', [('x', A)])\n[file m.py.3]\nfrom typing import NamedTuple\nfrom a import A\n\nNT = NamedTuple('NT', [('x', A)])\nreveal_type(NT.x)\nx: NT\nreveal_type(x.x)\n[file a.py]\nfrom b import B\nA = B\n[file b.py.2]\ndef func(x): pass\nB = func\n[builtins fixtures/tuple.pyi]\n[out]\n==\nm.py:4: error: Variable \"a.A\" is not valid as a type\nm.py:4: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n==\nm.py:4: error: Variable \"a.A\" is not valid as a type\nm.py:4: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\nm.py:5: note: Revealed type is \"Any\"\nm.py:7: note: Revealed type is \"Any\"\n\n[case testAliasForwardFunctionDirect]\n# flags: --ignore-missing-imports\nfrom typing import Optional\nfrom b import B\n\nAlias = Optional[B]\n[file b.py.2]\ndef func(x): pass\nB = int()\n[out]\n==\nmain:5: error: Variable \"b.B\" is not valid as a type\nmain:5: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testAliasForwardFunctionIndirect]\n# flags: --ignore-missing-imports\nfrom typing import Optional\nfrom a import A\n\nAlias = Optional[A]\n[file a.py]\nfrom b import B\nA = B\n[file b.py.2]\ndef func(x): pass\nB = func\n[out]\n==\nmain:5: error: Variable \"a.A\" is not valid as a type\nmain:5: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testLiteralFineGrainedVarConversion]\nimport mod\nreveal_type(mod.x)\n[file mod.py]\nx = 1\n[file mod.py.2]\nfrom typing_extensions import Literal\nx: Literal[1] = 1\n[file mod.py.3]\nfrom typing_extensions import Literal\nx: Literal[1] = 2\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\n==\nmain:2: note: Revealed type is \"Literal[1]\"\n==\nmain:2: note: Revealed type is \"Literal[1]\"\nmod.py:2: error: Incompatible types in assignment (expression has type \"Literal[2]\", variable has type \"Literal[1]\")\n\n[case testLiteralFineGrainedFunctionConversion]\nfrom mod import foo\nfoo(3)\n[file mod.py]\ndef foo(x: int) -> None: pass\n[file mod.py.2]\nfrom typing_extensions import Literal\ndef foo(x: Literal[3]) -> None: pass\n[file mod.py.3]\nfrom typing_extensions import Literal\ndef foo(x: Literal[4]) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\nmain:2: error: Argument 1 to \"foo\" has incompatible type \"Literal[3]\"; expected \"Literal[4]\"\n\n[case testLiteralFineGrainedAlias]\nfrom mod import Alias\na: Alias = 1\n[file mod.py]\nAlias = int\n[file mod.py.2]\nfrom typing_extensions import Literal\nAlias = Literal[1]\n[file mod.py.3]\nfrom typing_extensions import Literal\nAlias = Literal[2]\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\nmain:2: error: Incompatible types in assignment (expression has type \"Literal[1]\", variable has type \"Literal[2]\")\n\n[case testLiteralFineGrainedOverload]\nfrom mod import foo\nreveal_type(foo(4))\n[file mod.py]\nfrom typing import overload\nfrom typing_extensions import Literal\n@overload\ndef foo(x: int) -> str: ...\n@overload\ndef foo(x: Literal['bar']) -> int: ...\ndef foo(x): pass\n[file mod.py.2]\nfrom typing import overload\nfrom typing_extensions import Literal\n@overload\ndef foo(x: Literal[4]) -> Literal['foo']: ...\n@overload\ndef foo(x: int) -> str: ...\n@overload\ndef foo(x: Literal['bar']) -> int: ...\ndef foo(x): pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.str\"\n==\nmain:2: note: Revealed type is \"Literal['foo']\"\n\n[case testLiteralFineGrainedChainedDefinitions]\nfrom mod1 import foo\nfrom typing_extensions import Literal\ndef expect_3(x: Literal[3]) -> None: pass\nexpect_3(foo)\n[file mod1.py]\nfrom mod2 import bar\nfoo = bar\n[file mod2.py]\nfrom mod3 import qux as bar\n[file mod3.py]\nfrom typing_extensions import Literal\nqux: Literal[3]\n[file mod3.py.2]\nfrom typing_extensions import Literal\nqux: Literal[4]\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:4: error: Argument 1 to \"expect_3\" has incompatible type \"Literal[4]\"; expected \"Literal[3]\"\n\n[case testLiteralFineGrainedChainedAliases]\nfrom mod1 import Alias1\nfrom typing_extensions 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_extensions import Literal\nAlias3 = Literal[3]\n[file mod3.py.2]\nfrom typing_extensions import Literal\nAlias3 = Literal[4]\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:5: error: Argument 1 to \"expect_3\" has incompatible type \"Literal[4]\"; expected \"Literal[3]\"\n\n[case testLiteralFineGrainedChainedFunctionDefinitions]\nfrom mod1 import func1\nfrom typing_extensions import Literal\ndef expect_3(x: Literal[3]) -> None: pass\nexpect_3(func1())\n[file mod1.py]\nfrom mod2 import func2 as func1\n[file mod2.py]\nfrom mod3 import func3\nfunc2 = func3\n[file mod3.py]\nfrom typing_extensions import Literal\ndef func3() -> Literal[3]: pass\n[file mod3.py.2]\nfrom typing_extensions import Literal\ndef func3() -> Literal[4]: pass\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:4: error: Argument 1 to \"expect_3\" has incompatible type \"Literal[4]\"; expected \"Literal[3]\"\n\n[case testLiteralFineGrainedChainedTypeVarInference]\nfrom mod1 import foo\nreveal_type(foo)\n[file mod1.py]\nfrom typing import TypeVar\nfrom mod2 import bar\nT = TypeVar('T', bound=int)\ndef func(x: T) -> T: return x\nfoo = func(bar)\n[file mod2.py]\nbar = 3\n[file mod2.py.2]\nfrom typing_extensions import Literal\nbar: Literal[3] = 3\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\n==\nmain:2: note: Revealed type is \"Literal[3]\"\n\n[case testLiteralFineGrainedChainedViaFinal]\nfrom mod1 import foo\nfrom typing_extensions import Literal\ndef expect_3(x: Literal[3]) -> None: pass\nexpect_3(foo)\n[file mod1.py]\nfrom typing_extensions import Final\nfrom mod2 import bar\nfoo: Final = bar\n[file mod2.py]\nfrom mod3 import qux as bar\n[file mod3.py]\nfrom typing_extensions import Final\nqux: Final = 3\n[file mod3.py.2]\nfrom typing_extensions import Final\nqux: Final = 4\n[file mod3.py.3]\nfrom typing_extensions import Final\nqux: Final[int] = 4\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:4: error: Argument 1 to \"expect_3\" has incompatible type \"Literal[4]\"; expected \"Literal[3]\"\n==\nmain:4: error: Argument 1 to \"expect_3\" has incompatible type \"Literal[4]\"; expected \"Literal[3]\"\n\n[case testLiteralFineGrainedStringConversionPython3]\nfrom mod1 import foo\nreveal_type(foo)\n[file mod1.py]\nfrom mod2 import bar\nfoo = bar()\n[file mod2.py]\nfrom typing_extensions import Literal\ndef bar() -> Literal[\"foo\"]: pass\n[file mod2.py.2]\nfrom typing_extensions import Literal\ndef bar() -> Literal[u\"foo\"]: pass\n[file mod2.py.3]\nfrom typing_extensions import Literal\ndef bar() -> Literal[b\"foo\"]: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: note: Revealed type is \"Literal['foo']\"\n==\nmain:2: note: Revealed type is \"Literal['foo']\"\n==\nmain:2: note: Revealed type is \"Literal[b'foo']\"\n\n[case testReprocessModuleTopLevelWhileMethodDefinesAttr]\nimport a\n[file a.py]\nfrom b import B\n\nB().x\n\n[file a.py.3]\nfrom b import B\n\nx = B().x\n\n[file b.py]\nfrom c import f\nf(int())\n\nclass B:\n    def meth(self) -> None:\n        self.x: int\n\n[file c.py]\ndef f(x: int) -> None: ...\n\n[file c.py.2]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n\n[targets2 c, b]\n[targets3 a]\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\n\n[case testCheckReprocessedTargets-only_when_nocache]\nfrom b import B\n\nclass C(B):\n    def meth(self) -> None:\n        from b import f\n        f()\n\n[file b.py]\nclass B: ...\ndef f() -> int: ...\n\n[file b.py.2]\nclass A: ...\nclass B(A): ...\ndef f() -> int: ...\n\n[file b.py.3]\nclass A: ...\nclass B(A): ...\ndef f() -> str: ...\n\n[targets2 b, __main__, __main__.C.meth, __main__, __main__.C.meth]\n[targets3 b, __main__.C.meth]\n[out]\n==\n==\n\n[case testReprocessModuleTopLevelWhileMethodDefinesAttrExplicit]\nimport a\n[file a.py]\nfrom b import B\n\nB().x\n\n[file b.py]\nfrom c import f\nf(int())\n\nclass A:\n    x: int\n\nclass B(A):\n    def meth(self) -> None:\n        self.x: int\n\n[file c.py]\ndef f(x: int) -> None: ...\n\n[file c.py.2]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n\n[file a.py.3]\nfrom b import B\n\n# Double-check the variable is still accessible.\nB().x\n\n[targets2 c, b]\n[targets3 a]\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\n\n[case testReprocessModuleTopLevelWhileMethodDefinesAttrBothExplicitAndInClass]\nimport a\n[file a.py]\nfrom b import B\n\nB().x\n\n[file b.py]\nfrom c import f\nf(int())\n\nclass A:\n    x: int\n\nclass B(A):\n    x: int\n    def meth(self) -> None:\n        self.x: int\n\n[file c.py]\ndef f(x: int) -> None: ...\n\n[file c.py.2]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n\n[file a.py.3]\nfrom b import B\n\n# Double-check the variable is still accessible.\nB().x\n\n[targets2 c, b]\n[targets3 a]\n[builtins fixtures/tuple.pyi]\n[out]\n==\n==\n\n[case testReprocessModuleTopLevelWhileMethodDefinesAttrProtocol]\nimport a\n[file a.py]\nfrom b import B\n\nB().x\n\n[file b.py]\nfrom typing import Protocol\nfrom c import f\nf(int())\n\nclass A(Protocol):\n    x: int\n\nclass B(A):\n    def meth(self) -> None:\n        self.x = 42\n\n[file c.py]\ndef f(x: int) -> None: ...\n\n[file c.py.2]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n\n[file a.py.3]\nfrom b import B\n\n# Double-check the variable is still accessible.\nB().x\n\n[targets2 c, b]\n[targets3 a]\n[out]\n==\n==\n\n[case testNewSemanticAnalyzerUpdateMethodAndClass]\n\nimport m\n\nm.x\n\nclass A:\n    def f(self) -> None:\n        self.x = 0\n        m.y\n\n    def g(self) -> None:\n        m.x\n\n[file m.py]\nx = 0\ny = 0\n\n[file m.py.2]\nx = ''\ny = 0\n\n[file m.py.3]\nx = ''\ny = ''\n\n[out]\n==\n==\n\n[case testInlineConfigFineGrained1]\n\nimport a\n[file a.py]\n# mypy: no-warn-no-return\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:\n    20\n\n[file a.py.2]\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.3]\n# mypy: no-warn-no-return\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:\n    20\n\n[file a.py.4]\nfrom typing import List, Optional\ndef foo() -> Optional[List]:\n    20\n[out]\n==\na.py:4: error: Missing type parameters for generic type \"List\"\n==\n==\na.py:2: error: Missing return statement\n\n[builtins fixtures/list.pyi]\n\n[case testInlineConfigFineGrained2]\nimport a\n[file a.py]\n# mypy: bogus-flag\n\n[file b.py.2]\n\n[out]\na.py:1: error: Unrecognized option: bogus_flag = True\n==\na.py:1: error: Unrecognized option: bogus_flag = True\n\n[case testWrongNumberOfArguments]\n\n[file a.py]\ndef bar(x):\n    # type: () -> None\n    pass\n\ndef baz(x):\n    # type: () -> None\n    pass\n\ndef f():\n    # type: () -> None\n    def g(x):\n        # type: () -> None\n        pass\n\n[file c.py]\ndef bar(x):\n    # type: () -> None\n    pass\n\n[file b.py]\nx = ''\n\n[file b.py.2]\nx = 1\n\n[out]\nc.py:1: error: Type signature has too few arguments\na.py:1: error: Type signature has too few arguments\na.py:5: error: Type signature has too few arguments\na.py:11: error: Type signature has too few arguments\n==\nc.py:1: error: Type signature has too few arguments\na.py:1: error: Type signature has too few arguments\na.py:5: error: Type signature has too few arguments\na.py:11: error: Type signature has too few arguments\n\n[case testErrorReportingNewAnalyzer]\n# flags: --disallow-any-generics\nfrom a import A\n\ndef f() -> None:\n    x: A\n[file a.py]\nclass A: ...\n\n[file a.py.2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): ...\n[out]\n==\nmain:5: error: Missing type parameters for generic type \"A\"\n\n[case testStripNewAnalyzer]\n# flags: --ignore-missing-imports\nimport a\n[file a.py]\nfrom typing import List\nfrom b import B\n\nclass A:\n    def __init__(self) -> None:\n        self.x: List[int] = []\n\n    def method(self) -> None:\n        B()\n        self.x = []\n\n[file b.py]\nclass B: ...\n[delete b.py.2]\n\n[builtins fixtures/list.pyi]\n[out]\n==\n\n[case testClassVariableOrderingRefresh]\n\nfrom b import bar\n\ndef foo(x: str) -> None: pass\n\nclass Something:\n    def run(self) -> None:\n        bar()\n        foo(self.IDS[0])\n\n    IDS = [87]\n\n[file b.py]\ndef bar() -> int: return 0\n[file b.py.2]\ndef bar() -> str: return '0'\n[builtins fixtures/list.pyi]\n[out]\nmain:9: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\n==\nmain:9: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testInfiniteLoop]\n\n[file a.py]\nfrom b import f\nfrom typing import Callable, TypeVar\n\nF = TypeVar('F', bound=Callable)\ndef dec(x: F) -> F: return x\n\n@dec\ndef foo(self):\n    class A:\n        @classmethod\n        def asdf(cls, x: 'A') -> None: pass\n\n@dec\ndef bar(self):\n    class B:\n        @classmethod\n        def asdf(cls, x: 'B') -> None: pass\n    f()\n\n[file b.py]\ndef f() -> int: pass\n[file b.py.2]\ndef f() -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n==\n\n[case testInfiniteLoop2]\n\n[file a.py]\nfrom b import f\nfrom typing import Callable, TypeVar, NamedTuple\n\nF = TypeVar('F', bound=Callable)\ndef dec(x: F) -> F: return x\n\n@dec\ndef foo(self):\n    N = NamedTuple('N', [('x', int)])\n    def g(x: N) -> None: pass\n\n@dec\ndef bar(self):\n    N = NamedTuple('N', [('x', int)])\n    def g(x: N) -> None: pass\n    f()\n\n[file b.py]\ndef f() -> int: pass\n[file b.py.2]\ndef f() -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n==\n\n[case testFileAddedAndImported]\n# flags: --ignore-missing-imports --follow-imports=skip\n# cmd: mypy a.py\n# cmd2: mypy a.py b.py\n\n[file a.py]\nfrom b import bad\nx = 42\n\n[file b.py.2]\ndef good() -> None: ...\n[out]\n==\na.py:1: error: Module \"b\" has no attribute \"bad\"\n\n[case testFileAddedAndImported2]\n# flags: --ignore-missing-imports --follow-imports=skip\n# cmd: mypy -m a\n# cmd2: mypy -m a b\n[file a.py]\nx = 42\n\n[file a.py.2]\nfrom b import bad\nx = 42\n\n[file b.py.2]\ndef good() -> None: ...\n[out]\n==\na.py:1: error: Module \"b\" has no attribute \"bad\"\n\n[case testTypedDictCrashFallbackAfterDeletedMeet]\n# flags: --ignore-missing-imports\n\nfrom z import get_data\nfrom a import Data\n\nfor it in get_data()['things']:\n    it['id']\n\n[file z.py]\nfrom a import Data\n\ndef get_data() -> Data: ...\n\n[file a.py]\nfrom typing import TypedDict, List, Union\n\nclass File(TypedDict):\n    id: int\n    name: str\n\nclass User(TypedDict):\n    id: int\n    path: str\n\nclass Data(TypedDict):\n    things: List[Union[File, User]]\n\n[delete a.py.2]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n==\n\n[case testTypedDictCrashFallbackAfterDeletedJoin]\n# flags: --ignore-missing-imports\n\nfrom z import get_data\nfrom a import Data\n\nx = [get_data()[0], get_data()[1]]\n\n[file z.py]\nfrom a import Data\n\ndef get_data() -> Data: ...\n\n[file a.py]\nfrom typing import TypedDict, Tuple\n\nclass File(TypedDict):\n    id: int\n    name: str\n\nclass User(TypedDict):\n    id: int\n    path: str\n\nData = Tuple[User, File]\n\n[delete a.py.2]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n==\n\n[case testClassRedef]\n# An issue involved serializing these caused crashes in the past\n\n[file a.py]\nclass A:\n    pass\n\nx = 0\n\n[file a.py.2]\nclass A:\n    a = A()\n\nx = '0'\n\n[file b.py]\nfrom a import A, x\n\nclass A: # type: ignore\n    pass\n\n[out]\n==\n\n[case testAddAttributeThroughNewBaseClass]\nimport a\n\n[file a.py]\nclass C:\n    def __init__(self) -> None:\n        self.x = 0\n\n[file a.py.2]\nfrom b import B\n\nclass C(B):\n    def __init__(self) -> None:\n        self.x = 0\n\n[file b.py.2]\nclass B:\n    def __init__(self) -> None:\n        self.x = 0\n[out]\n==\n\n[case testGenericChange1]\nimport a\n[file a.py]\nimport b\ndef f() -> b.C: pass\n[file b.py]\nimport a\nclass C: pass\n[file b.py.2]\nfrom typing import TypeVar, Generic, List\nimport a\n\nT = TypeVar('T')\nclass C(Generic[T]): pass\n\nreveal_type(a.f)\nc: C[int]\nl = a.f() if True else c\nd = a.f()\nd = c\nc = d\n\nx: List[C] = [a.f(), a.f()]\n\n[out]\n==\nb.py:7: note: Revealed type is \"def () -> b.C[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testGenericChange2]\nimport a\n[file a.py]\nimport b\ndef f() -> b.C[int]: pass\n[file b.py]\nfrom typing import TypeVar, Generic\nimport a\nT = TypeVar('T')\nclass C(Generic[T]): pass\n[file b.py.2]\nfrom typing import List\nimport a\n\nclass C(): pass\n\nc: C\nl = a.f() if True else c\nd = a.f()\nd = c\nc = d\n\nx: List[C] = [a.f(), a.f()]\n\n[builtins fixtures/list.pyi]\n[out]\n==\na.py:2: error: \"C\" expects no type arguments, but 1 given\n\n[case testGenericChange3]\nimport a\n[file a.py]\nimport b\ndef f() -> b.C[int]: pass\n[file b.py]\nfrom typing import TypeVar, Generic\nimport a\nT = TypeVar('T')\nclass C(Generic[T]): pass\n[file b.py.2]\nfrom typing import TypeVar, Generic, List\nimport a\n\nT = TypeVar('T')\nS = TypeVar('S')\nclass C(Generic[S, T]): pass\n\nc: C[int, str]\nl = a.f() if True else c\nd = a.f()\nd = c\nc = d\n\nx: List[C] = [a.f(), a.f()]\n\n[out]\n==\na.py:2: error: \"C\" expects 2 type arguments, but 1 given\n[builtins fixtures/list.pyi]\n\n[case testIsInstanceAdHocIntersectionFineGrainedIncrementalNoChange]\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==\nb.py:2: note: Revealed type is \"a.A & a.B\"\n\n[case testIsInstanceAdHocIntersectionFineGrainedIncrementalIsInstanceChange]\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]\nc.py:2: note: Revealed type is \"a.A & a.B\"\n==\nc.py:2: note: Revealed type is \"a.A & a.C\"\n\n[case testIsInstanceAdHocIntersectionFineGrainedIncrementalUnderlyingObjChang]\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]\nc.py:2: note: Revealed type is \"a.A & a.B\"\n==\nc.py:2: note: Revealed type is \"a.A & a.C\"\n\n[case testIsInstanceAdHocIntersectionFineGrainedIncrementalIntersectionToUnreachable]\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]\nc.py:2: note: Revealed type is \"a.A & a.B\"\n==\nc.py:2: note: Revealed type is \"Any\"\nb.py:2: error: Cannot determine type of \"y\"\n\n[case testIsInstanceAdHocIntersectionFineGrainedIncrementalUnreachaableToIntersection]\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]\nb.py:2: error: Cannot determine type of \"y\"\nc.py:2: note: Revealed type is \"Any\"\n==\nc.py:2: note: Revealed type is \"a.A & a.B\"\n\n[case testStubFixupIssues]\n[file a.py]\nimport p\n[file a.py.2]\nimport p\n# a change\n\n[file p/__init__.pyi]\nfrom p.util import *\n\n[file p/util.pyi]\nfrom p.params import N\nclass Test: ...\n\n[file p/params.pyi]\nimport p.util\nclass N(p.util.Test):\n    ...\n\n[builtins fixtures/list.pyi]\n[out]\n==\n\n[case testDunderCall1]\nfrom a import C\n\nc = C()\nc(1)\n\n[file a.py]\nclass C:\n    def __call__(self, x: int) -> None: ...\n\n[file a.py.2]\nclass C:\n    def __call__(self, x: str) -> None: ...\n\n[out]\n==\nmain:4: error: Argument 1 to \"__call__\" of \"C\" has incompatible type \"int\"; expected \"str\"\n\n[case testDunderCall2]\nfrom a import C\n\nC()(1)\n\n[file a.py]\nclass C:\n    def __call__(self, x: int) -> None: ...\n\n[file a.py.2]\nclass C:\n    def __call__(self, x: str) -> None: ...\n\n[out]\n==\nmain:3: error: Argument 1 to \"__call__\" of \"C\" has incompatible type \"int\"; expected \"str\"\n\n[case testDunderCallAddition]\nfrom a import C\n\nc = C()\nx = c()  # type: ignore\nx + 42\n\n[file a.py]\nclass C: ...\n\n[file a.py.2]\nclass C:\n    def __call__(self) -> str: ...\n\n[out]\n==\nmain:5: error: Unsupported left operand type for + (\"str\")\n\n[case testNoneAttribute]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T', int, str)\n\nclass ExampleClass(Generic[T]):\n    def __init__(\n        self\n    ) -> None:\n        self.example_attribute = None\n[out]\n==\n[case testStrictNoneAttribute]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T', int, str)\n\nclass ExampleClass(Generic[T]):\n    def __init__(\n        self\n    ) -> None:\n        self.example_attribute = None\n[out]\n==\n\n[case testDataclassCheckTypeVarBoundsInReprocess]\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Protocol, Dict, TypeVar, Generic\nfrom m import x\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\n[file m.py]\nx: int\n[file m.py.2]\nx: str\n\n[builtins fixtures/dataclasses.pyi]\n[out]\n==\n\n[case testParamSpecCached]\nimport a\n\n[file a.py]\nimport b\n\ndef f(x: int) -> str: return 'x'\n\nb.foo(f)\n\n[file a.py.2]\nimport b\n\ndef f(x: int) -> str: return 'x'\n\nreveal_type(b.foo(f))\n\n[file b.py]\nfrom typing import TypeVar, Callable, Union\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef foo(f: Callable[P, T]) -> Callable[P, Union[T, None]]:\n    return f\n\n[file b.py.2]\nfrom typing import TypeVar, Callable, Union\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef foo(f: Callable[P, T]) -> Callable[P, Union[T, None]]:\n    return f\n\nx = 0  # Arbitrary change to trigger reprocessing\n\n[builtins fixtures/dict.pyi]\n[out]\n==\na.py:5: note: Revealed type is \"def (x: builtins.int) -> Union[builtins.str, None]\"\n\n[case testTypeVarTupleCached]\nimport a\n\n[file a.py]\nimport b\n\ndef f(x: int) -> str: return 'x'\n\nb.foo((1, 'x'))\n\n[file a.py.2]\nimport b\n\nreveal_type(b.foo((1, 'x')))\n\n[file b.py]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\n\ndef foo(t: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]:\n    return t\n\n[file b.py.2]\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\n\ndef foo(t: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]:\n    return t\n\nx = 0  # Arbitrary change to trigger reprocessing\n[builtins fixtures/dict.pyi]\n[out]\n==\na.py:3: note: Revealed type is \"Tuple[Literal[1]?, Literal['x']?]\"\n\n[case testVariadicClassFineUpdateRegularToVariadic]\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[out]\n==\n\n[case testVariadicClassFineUpdateVariadicToRegular]\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[out]\n==\nmain:4: error: \"C\" expects 2 type arguments, but 3 given\n\n-- Order of error messages is different, so we repeat the test twice.\n[case testVariadicClassFineUpdateValidToInvalidCached-only_when_cache]\nfrom typing import Any\nfrom lib import C\n\nx: C[int, str]\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\n[file lib.py.2]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[Ts]): ...\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:4: error: \"C\" expects no type arguments, but 2 given\nlib.py:5: error: Free type variable expected in Generic[...]\n\n[case testVariadicClassFineUpdateValidToInvalid-only_when_nocache]\nfrom typing import Any\nfrom lib import C\n\nx: C[int, str]\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\n[file lib.py.2]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[Ts]): ...\n[builtins fixtures/tuple.pyi]\n[out]\n==\nlib.py:5: error: Free type variable expected in Generic[...]\nmain:4: error: \"C\" expects no type arguments, but 2 given\n\n[case testVariadicClassFineUpdateInvalidToValid]\nfrom typing import Any\nfrom lib import C\n\nx: C[int, str]\n\n[file lib.py]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[Ts]): ...\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[out]\nlib.py:5: error: Free type variable expected in Generic[...]\nmain:4: error: \"C\" expects no type arguments, but 2 given\n==\n\n[case testUnpackKwargsUpdateFine]\nimport m\n[file shared.py]\nfrom typing_extensions import TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\n[file shared.py.2]\nfrom typing_extensions import TypedDict\n\nclass Person(TypedDict):\n    name: str\n    age: str\n\n[file lib.py]\nfrom typing_extensions import Unpack\nfrom shared import Person\n\ndef foo(**kwargs: Unpack[Person]):\n    ...\n[file m.py]\nfrom lib import foo\nfoo(name='Jennifer', age=38)\n\n[builtins fixtures/dict.pyi]\n[out]\n==\nm.py:2: error: Argument \"age\" to \"foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testModuleAsProtocolImplementationFine]\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==\nm.py:9: error: Argument 1 to \"setup\" has incompatible type Module; expected \"Options\"\nm.py:9: note: Following member(s) of Module \"default_config\" have conflicts:\nm.py:9: note:     Expected:\nm.py:9: note:         def update() -> bool\nm.py:9: note:     Got:\nm.py:9: note:         def update() -> str\n\n[case testBoundGenericMethodFine]\nimport main\n[file main.py]\nimport lib\n[file main.py.3]\nimport lib\nreveal_type(lib.foo(42))\n[file lib/__init__.pyi]\nfrom lib import context\nfoo = context.test.foo\n[file lib/context.pyi]\nfrom typing import TypeVar\nimport lib.other\n\nT = TypeVar(\"T\")\nclass Test:\n    def foo(self, x: T, n: lib.other.C = ...) -> T: ...\ntest: Test\n\n[file lib/other.pyi]\nclass C: ...\n[file lib/other.pyi.2]\nclass B: ...\nclass C(B): ...\n[out]\n==\n==\nmain.py:2: note: Revealed type is \"builtins.int\"\n\n[case testBoundGenericMethodParamSpecFine]\nimport main\n[file main.py]\nimport lib\n[file main.py.3]\nfrom typing import Callable\nimport lib\nf: Callable[[], int]\nreveal_type(lib.foo(f))\n[file lib/__init__.pyi]\nfrom lib import context\nfoo = context.test.foo\n[file lib/context.pyi]\nfrom typing_extensions import ParamSpec\nfrom typing import Callable\nimport lib.other\n\nP = ParamSpec(\"P\")\nclass Test:\n    def foo(self, x: Callable[P, int], n: lib.other.C = ...) -> Callable[P, str]: ...\ntest: Test\n\n[file lib/other.pyi]\nclass C: ...\n[file lib/other.pyi.2]\nclass B: ...\nclass C(B): ...\n[builtins fixtures/dict.pyi]\n[out]\n==\n==\nmain.py:4: note: Revealed type is \"def () -> builtins.str\"\n\n[case testAbstractBodyTurnsEmpty]\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==\nmain:5: error: Call to abstract method \"meth\" of \"Base\" with trivial body via super() is unsafe\n\n[case testAbstractBodyTurnsEmptyProtocol]\nfrom b import Base\n\nclass Sub(Base):\n    def meth(self) -> int:\n        return super().meth()\n\n[file b.py]\nfrom typing import Protocol\nclass Base(Protocol):\n    def meth(self) -> int: return 0\n[file b.py.2]\nfrom typing import Protocol\nclass Base(Protocol):\n    def meth(self) -> int: ...\n[out]\n==\nmain:5: error: Call to abstract method \"meth\" of \"Base\" with trivial body via super() is unsafe\n\n[case testPrettyMessageSorting]\n# flags: --python-version 3.8 --pretty\nimport a\n\n[file a.py]\n1 + ''\nimport b\n\n[file b.py]\nobject + 1\n\n[file b.py.2]\nobject + 1\n1()\n\n[out]\nb.py:1: error: Unsupported left operand type for + (\"Type[object]\")\n    object + 1\n    ^~~~~~~~~~\na.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n    1 + ''\n        ^~\n==\nb.py:1: error: Unsupported left operand type for + (\"Type[object]\")\n    object + 1\n    ^~~~~~~~~~\nb.py:2: error: \"int\" not callable\n    1()\n    ^~~\na.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n    1 + ''\n        ^~\n\n[case testTypingSelfFine]\nimport m\n[file lib.py]\nfrom typing import Any\n\nclass C:\n    def meth(self, other: Any) -> C: ...\n[file lib.py.2]\nfrom typing import Self\n\nclass C:\n    def meth(self, other: Self) -> Self: ...\n\n[file n.py]\nimport lib\nclass D(lib.C): ...\n[file m.py]\nfrom n import D\nd = D()\ndef test() -> None:\n    d.meth(42)\n[out]\n==\nm.py:4: error: Argument 1 to \"meth\" of \"C\" has incompatible type \"int\"; expected \"D\"\n\n[case testNoNestedDefinitionCrash]\nimport m\n[file m.py]\nfrom typing import Any, TYPE_CHECKING\n\nclass C:\n    if TYPE_CHECKING:\n        def __init__(self, **kw: Any): ...\n\nC\n[file m.py.2]\nfrom typing import Any, TYPE_CHECKING\n\nclass C:\n    if TYPE_CHECKING:\n        def __init__(self, **kw: Any): ...\n\nC\n# change\n[builtins fixtures/dict.pyi]\n[out]\n==\n\n[case testNoNestedDefinitionCrash2]\nimport m\n[file m.py]\nfrom typing import Any\n\nclass C:\n    try:\n        def __init__(self, **kw: Any): ...\n    except:\n        pass\n\nC\n[file m.py.2]\nfrom typing import Any\n\nclass C:\n    try:\n        def __init__(self, **kw: Any): ...\n    except:\n        pass\n\nC\n# change\n[builtins fixtures/dict.pyi]\n[out]\n==\n\n[case testNamedTupleNestedCrash]\nimport m\n[file m.py]\nfrom typing import NamedTuple\n\nclass NT(NamedTuple):\n    class C: ...\n    x: int\n    y: int\n\n[file m.py.2]\nfrom typing import NamedTuple\n\nclass NT(NamedTuple):\n    class C: ...\n    x: int\n    y: int\n# change\n[builtins fixtures/tuple.pyi]\n[out]\nm.py:4: error: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n==\nm.py:4: error: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n\n[case testNamedTupleNestedClassRecheck]\nimport n\n[file n.py]\nimport m\nx: m.NT\n[file m.py]\nfrom typing import NamedTuple\nfrom f import A\n\nclass NT(NamedTuple):\n    class C: ...\n    x: int\n    y: A\n\n[file f.py]\nA = int\n[file f.py.2]\nA = str\n[builtins fixtures/tuple.pyi]\n[out]\nm.py:5: error: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n==\nm.py:5: error: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n\n[case testTypedDictNestedClassRecheck]\nimport n\n[file n.py]\nimport m\nx: m.TD\n[file m.py]\nfrom typing_extensions import TypedDict\nfrom f import A\n\nclass TD(TypedDict):\n    class C: ...\n    x: int\n    y: A\n\n[file f.py]\nA = int\n[file f.py.2]\nA = str\n[builtins fixtures/dict.pyi]\n[out]\nm.py:5: error: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n==\nm.py:5: error: Invalid statement in TypedDict definition; expected \"field_name: field_type\"\n\n[case testTypeAliasWithNewStyleUnionChangedToVariable]\n# flags: --python-version 3.10\nimport a\n\n[file a.py]\nfrom b import C, D\nA = C | D\na: A\nreveal_type(a)\n[builtins fixtures/type.pyi]\n\n[file b.py]\nC = int\nD = str\n\n[file b.py.2]\nC = \"x\"\nD = \"y\"\n\n[file b.py.3]\nC = str\nD = int\n[out]\na.py:4: note: Revealed type is \"Union[builtins.int, builtins.str]\"\n==\na.py:2: error: Unsupported left operand type for | (\"str\")\na.py:3: error: Variable \"a.A\" is not valid as a type\na.py:3: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\na.py:4: note: Revealed type is \"A?\"\n==\na.py:4: note: Revealed type is \"Union[builtins.str, builtins.int]\"\n\n[case testUnionOfSimilarCallablesCrash]\nimport b\n\n[file b.py]\nfrom a import x\n\n[file m.py]\nfrom typing import Union, TypeVar\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\ndef foo(x: T, y: S) -> Union[T, S]: ...\ndef f(x: int) -> int: ...\ndef g(*x: int) -> int: ...\n\n[file a.py]\nfrom m import f, g, foo\nx = foo(f, g)\n\n[file a.py.2]\nfrom m import f, g, foo\nx = foo(f, g)\nreveal_type(x)\n[builtins fixtures/tuple.pyi]\n[out]\n==\na.py:3: note: Revealed type is \"Union[def (x: builtins.int) -> builtins.int, def (*x: builtins.int) -> builtins.int]\"\n\n[case testErrorInReAddedModule]\n# flags: --disallow-untyped-defs --follow-imports=error\n# cmd: mypy a.py\n# cmd2: mypy b.py\n# cmd3: mypy a.py\n\n[file a.py]\ndef f(): pass\n[file b.py]\ndef f(): pass\n[file unrelated.txt.3]\n[out]\na.py:1: error: Function is missing a return type annotation\na.py:1: note: Use \"-> None\" if function does not return a value\n==\nb.py:1: error: Function is missing a return type annotation\nb.py:1: note: Use \"-> None\" if function does not return a value\n==\na.py:1: error: Function is missing a return type annotation\na.py:1: note: Use \"-> None\" if function does not return a value\n\n[case testModuleLevelGetAttrInStub]\nimport stub\nimport a\nimport b\n\n[file stub/__init__.pyi]\ns: str\ndef __getattr__(self): pass\n\n[file a.py]\n\n[file a.py.2]\nfrom stub import x\nfrom stub.pkg import y\nfrom stub.pkg.sub import z\n\n[file b.py]\n\n[file b.py.3]\nfrom stub import s\nreveal_type(s)\n\n[out]\n==\n==\nb.py:2: note: Revealed type is \"builtins.str\"\n\n[case testRenameSubModule]\nimport a\n\n[file a.py]\nimport pkg.sub\n\n[file pkg/__init__.py]\n[file pkg/sub/__init__.py]\nfrom pkg.sub import mod\n[file pkg/sub/mod.py]\n\n[file pkg/sub/__init__.py.2]\nfrom pkg.sub import modb\n[delete pkg/sub/mod.py.2]\n[file pkg/sub/modb.py.2]\n\n[out]\n==\n\n[case testFineGrainedFunctoolsPartial]\nimport m\n\n[file m.py]\nfrom typing import Callable\nfrom partial import p1\n\nreveal_type(p1)\np1(\"a\")\np1(\"a\", 3)\np1(\"a\", c=3)\np1(1, 3)\np1(1, \"a\", 3)\np1(a=1, b=\"a\", c=3)\n[builtins fixtures/dict.pyi]\n\n[file partial.py]\nfrom typing import Callable\nimport functools\n\ndef foo(a: int, b: str, c: int = 5) -> int: ...\np1 = foo\n\n[file partial.py.2]\nfrom typing import Callable\nimport functools\n\ndef foo(a: int, b: str, c: int = 5) -> int: ...\np1 = functools.partial(foo, 1)\n\n[out]\nm.py:4: note: Revealed type is \"def (a: builtins.int, b: builtins.str, c: builtins.int =) -> builtins.int\"\nm.py:5: error: Too few arguments\nm.py:5: error: Argument 1 has incompatible type \"str\"; expected \"int\"\nm.py:6: error: Argument 1 has incompatible type \"str\"; expected \"int\"\nm.py:6: error: Argument 2 has incompatible type \"int\"; expected \"str\"\nm.py:7: error: Too few arguments\nm.py:7: error: Argument 1 has incompatible type \"str\"; expected \"int\"\nm.py:8: error: Argument 2 has incompatible type \"int\"; expected \"str\"\n==\nm.py:4: note: Revealed type is \"functools.partial[builtins.int]\"\nm.py:8: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\nm.py:9: error: Too many arguments for \"foo\"\nm.py:9: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\nm.py:9: error: Argument 2 to \"foo\" has incompatible type \"str\"; expected \"int\"\nm.py:10: error: Unexpected keyword argument \"a\" for \"foo\"\npartial.py:4: note: \"foo\" defined here\n\n[case testReplaceFunctionWithDecoratedFunctionIndirect]\nfrom b import f\nx: int = f()\nimport b\ny: int = b.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\ndef f() -> int: ...\n\n[file a.py.2]\nfrom typing import Callable\ndef d(t: Callable[[], str]) -> Callable[[], str]: ...\n\n@d\ndef f() -> str: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testReplaceFunctionWithDecoratedFunctionIndirect2]\nfrom c import f\nx: int = f()\nimport c\ny: int = c.f()\n\n[file c.py]\nfrom b import f\n\n[file b.py]\nfrom a import f\n\n[file a.py]\ndef f() -> int: ...\n\n[file a.py.2]\nfrom typing import Callable\ndef d(t: Callable[[], str]) -> Callable[[], str]: ...\n\n@d\ndef f() -> str: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testReplaceFunctionWithClassIndirect]\nfrom b import f\nx: int = f()\nimport b\ny: int = b.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\ndef f() -> int: ...\n\n[file a.py.2]\nclass f: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type \"f\", variable has type \"int\")\nmain:4: error: Incompatible types in assignment (expression has type \"f\", variable has type \"int\")\n\n[case testReplaceFunctionWithClassIndirect2]\nfrom c import f\nx: int = f()\nimport c\ny: int = c.f()\n\n[file c.py]\nfrom b import f\n\n[file b.py]\nfrom a import f\n\n[file a.py]\ndef f() -> int: ...\n\n[file a.py.2]\nclass f: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: Incompatible types in assignment (expression has type \"f\", variable has type \"int\")\nmain:4: error: Incompatible types in assignment (expression has type \"f\", variable has type \"int\")\n\n\n[case testDeprecatedAddKeepChangeAndRemoveFunctionDeprecation]\n# flags: --enable-error-code=deprecated\n\nfrom a import f\nf()\nimport a\na.f()\n\n[file a.py]\ndef f() -> None: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\n[file a.py.3]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\n[file a.py.4]\nfrom typing_extensions import deprecated\n@deprecated(\"use f3 instead\")\ndef f() -> None: ...\n\n[file a.py.5]\ndef f() -> None: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:3: error: function a.f is deprecated: use f2 instead\nmain:6: error: function a.f is deprecated: use f2 instead\n==\nmain:3: error: function a.f is deprecated: use f2 instead\nmain:6: error: function a.f is deprecated: use f2 instead\n==\nmain:3: error: function a.f is deprecated: use f3 instead\nmain:6: error: function a.f is deprecated: use f3 instead\n==\n\n\n[case testDeprecatedRemoveFunctionDeprecation]\n# flags: --enable-error-code=deprecated\nfrom a import f\nf()\nimport a\na.f()\n\n[file a.py]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\n[file a.py.2]\ndef f() -> None: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: error: function a.f is deprecated: use f2 instead\nmain:5: error: function a.f is deprecated: use f2 instead\n==\n\n[case testDeprecatedKeepFunctionDeprecation]\n# flags: --enable-error-code=deprecated\nfrom a import f\nf()\nimport a\na.f()\n\n[file a.py]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: error: function a.f is deprecated: use f2 instead\nmain:5: error: function a.f is deprecated: use f2 instead\n==\nmain:2: error: function a.f is deprecated: use f2 instead\nmain:5: error: function a.f is deprecated: use f2 instead\n\n\n[case testDeprecatedAddFunctionDeprecationIndirectImport]\n# flags: --enable-error-code=deprecated\nfrom b import f\nf()\nimport b\nb.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\ndef f() -> int: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> int: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nb.py:1: error: function a.f is deprecated: use f2 instead\nmain:2: error: function a.f is deprecated: use f2 instead\nmain:5: error: function a.f is deprecated: use f2 instead\n\n\n[case testDeprecatedChangeFunctionDeprecationIndirectImport]\n# flags: --enable-error-code=deprecated\nfrom b import f\nf()\nimport b\nb.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\nfrom typing_extensions import deprecated\n@deprecated(\"use f1 instead\")\ndef f() -> int: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n@deprecated(\"use f2 instead\")\ndef f() -> int: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nb.py:1: error: function a.f is deprecated: use f1 instead\nmain:2: error: function a.f is deprecated: use f1 instead\nmain:5: error: function a.f is deprecated: use f1 instead\n==\nb.py:1: error: function a.f is deprecated: use f2 instead\nmain:2: error: function a.f is deprecated: use f2 instead\nmain:5: error: function a.f is deprecated: use f2 instead\n\n[case testDeprecatedRemoveFunctionDeprecationIndirectImport]\n# flags: --enable-error-code=deprecated\nfrom b import f\nf()\nimport b\nb.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\nfrom typing_extensions import deprecated\n@deprecated(\"use f1 instead\")\ndef f() -> int: ...\n\n[file a.py.2]\ndef f() -> int: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nb.py:1: error: function a.f is deprecated: use f1 instead\nmain:2: error: function a.f is deprecated: use f1 instead\nmain:5: error: function a.f is deprecated: use f1 instead\n==\n\n\n[case testDeprecatedFunctionAlreadyDecorated1-only_when_cache]\n# flags: --enable-error-code=deprecated\nfrom b import f\nx: str = f()\nimport b\ny: str = b.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\nfrom typing import Callable\n\ndef d(t: Callable[[], str]) -> Callable[[], str]: ...\n\n@d\ndef f() -> str: ...\n\n[file a.py.2]\nfrom typing import Callable\nfrom typing_extensions import deprecated\n\ndef d(t: Callable[[], str]) -> Callable[[], str]: ...\n\n@deprecated(\"deprecated decorated function\")\n@d\ndef f() -> str: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nb.py:1: error: function a.f is deprecated: deprecated decorated function\nmain:2: error: function a.f is deprecated: deprecated decorated function\nmain:5: error: function a.f is deprecated: deprecated decorated function\n\n\n[case testDeprecatedFunctionAlreadyDecorated2-only_when_nocache]\n# flags: --enable-error-code=deprecated\nfrom b import f\nx: str = f()\nimport b\ny: str = b.f()\n\n[file b.py]\nfrom a import f\n\n[file a.py]\nfrom typing import Callable\n\ndef d(t: Callable[[], str]) -> Callable[[], str]: ...\n\n@d\ndef f() -> str: ...\n\n[file a.py.2]\nfrom typing import Callable\nfrom typing_extensions import deprecated\n\ndef d(t: Callable[[], str]) -> Callable[[], str]: ...\n\n@deprecated(\"deprecated decorated function\")\n@d\ndef f() -> str: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: function a.f is deprecated: deprecated decorated function\nmain:5: error: function a.f is deprecated: deprecated decorated function\nb.py:1: error: function a.f is deprecated: deprecated decorated function\n\n\n[case testDeprecatedAddClassDeprecationIndirectImport1-only_when_cache]\n# flags: --enable-error-code=deprecated\nfrom b import C\nx: C\nC()\nimport b\ny: b.D\nb.D()\n\n[file b.py]\nfrom a import C\nfrom a import D\n\n[file a.py]\nclass C: ...\nclass D: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\n@deprecated(\"use D2 instead\")\nclass D: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nb.py:1: error: class a.C is deprecated: use C2 instead\nb.py:2: error: class a.D is deprecated: use D2 instead\nmain:2: error: class a.C is deprecated: use C2 instead\nmain:6: error: class a.D is deprecated: use D2 instead\nmain:7: error: class a.D is deprecated: use D2 instead\n\n\n[case testDeprecatedAddClassDeprecationIndirectImport2-only_when_nocache]\n# flags: --enable-error-code=deprecated\nfrom b import C\nx: C\nC()\nimport b\ny: b.D\nb.D()\n\n[file b.py]\nfrom a import C\nfrom a import D\n\n[file a.py]\nclass C: ...\nclass D: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\n@deprecated(\"use D2 instead\")\nclass D: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: class a.C is deprecated: use C2 instead\nmain:6: error: class a.D is deprecated: use D2 instead\nmain:7: error: class a.D is deprecated: use D2 instead\nb.py:1: error: class a.C is deprecated: use C2 instead\nb.py:2: error: class a.D is deprecated: use D2 instead\n\n\n[case testDeprecatedChangeClassDeprecationIndirectImport]\n# flags: --enable-error-code=deprecated\nfrom b import C\nx: C\nC()\nimport b\ny: b.D\nb.D()\n\n[file b.py]\nfrom a import C\nfrom a import D\n\n[file a.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C1 instead\")\nclass C: ...\n@deprecated(\"use D1 instead\")\nclass D: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\n@deprecated(\"use D2 instead\")\nclass D: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nb.py:1: error: class a.C is deprecated: use C1 instead\nb.py:2: error: class a.D is deprecated: use D1 instead\nmain:2: error: class a.C is deprecated: use C1 instead\nmain:6: error: class a.D is deprecated: use D1 instead\nmain:7: error: class a.D is deprecated: use D1 instead\n==\nb.py:1: error: class a.C is deprecated: use C2 instead\nb.py:2: error: class a.D is deprecated: use D2 instead\nmain:2: error: class a.C is deprecated: use C2 instead\nmain:6: error: class a.D is deprecated: use D2 instead\nmain:7: error: class a.D is deprecated: use D2 instead\n\n\n[case testDeprecatedRemoveClassDeprecationIndirectImport]\n# flags: --enable-error-code=deprecated\nfrom b import C\nx: C\nC()\nimport b\ny: b.D\nb.D()\n\n[file b.py]\nfrom a import C\nfrom a import D\n\n[file a.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C1 instead\")\nclass C: ...\n@deprecated(\"use D1 instead\")\nclass D: ...\n\n[file a.py.2]\nclass C: ...\nclass D: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\nb.py:1: error: class a.C is deprecated: use C1 instead\nb.py:2: error: class a.D is deprecated: use D1 instead\nmain:2: error: class a.C is deprecated: use C1 instead\nmain:6: error: class a.D is deprecated: use D1 instead\nmain:7: error: class a.D is deprecated: use D1 instead\n==\n\n\n[case testDeprecatedAddClassDeprecationIndirectImportAlreadyDecorated1-only_when_cache]\n# flags: --enable-error-code=deprecated\nfrom b import C\nx: C\nC()\nimport b\ny: b.D\nb.D()\n\n[file b.py]\nfrom a import C\nfrom a import D\n\n[file a.py]\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\ndef dec(x: T) -> T: ...\n\n@dec\nclass C: ...\n@dec\nclass D: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\n@deprecated(\"use D2 instead\")\nclass D: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nb.py:1: error: class a.C is deprecated: use C2 instead\nb.py:2: error: class a.D is deprecated: use D2 instead\nmain:2: error: class a.C is deprecated: use C2 instead\nmain:6: error: class a.D is deprecated: use D2 instead\nmain:7: error: class a.D is deprecated: use D2 instead\n\n\n[case testDeprecatedAddClassDeprecationIndirectImportAlreadyDecorated2-only_when_nocache]\n# flags: --enable-error-code=deprecated\nfrom b import C\nx: C\nC()\nimport b\ny: b.D\nb.D()\n\n[file b.py]\nfrom a import C\nfrom a import D\n\n[file a.py]\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\ndef dec(x: T) -> T: ...\n\n@dec\nclass C: ...\n@dec\nclass D: ...\n\n[file a.py.2]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\n@deprecated(\"use D2 instead\")\nclass D: ...\n\n[builtins fixtures/tuple.pyi]\n[out]\n==\nmain:2: error: class a.C is deprecated: use C2 instead\nmain:6: error: class a.D is deprecated: use D2 instead\nmain:7: error: class a.D is deprecated: use D2 instead\nb.py:1: error: class a.C is deprecated: use C2 instead\nb.py:2: error: class a.D is deprecated: use D2 instead\n"
  },
  {
    "path": "test-data/unit/fixtures/__init_subclass__.pyi",
    "content": "# builtins stub with object.__init_subclass__\n\nfrom typing import Mapping, Iterable  # needed for ArgumentInferContext\n\nclass object:\n    def __init_subclass__(cls) -> None: pass\n\nclass type: pass\n\nclass int: pass\nclass bool: pass\nclass str: pass\nclass function: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/__new__.pyi",
    "content": "# builtins stub with object.__new__\n\nfrom typing import Any\n\nclass object:\n    def __init__(self) -> None: pass\n\n    __class__ = object\n\n    def __new__(cls) -> Any: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass int: pass\nclass bool: pass\nclass str: pass\nclass function: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/alias.pyi",
    "content": "# Builtins test fixture with a type alias 'bytes'\n\nfrom typing import Mapping, Iterable  # needed for `ArgumentInferContext`\n\nclass object:\n    def __init__(self) -> None: pass\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass int: pass\nclass str: pass\nclass function: pass\n\nbytes = str\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/any.pyi",
    "content": "from typing import TypeVar, Iterable\n\nT = TypeVar('T')\n\nclass int: pass\nclass str: pass\n\ndef any(i: Iterable[T]) -> bool: pass\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/args.pyi",
    "content": "# Builtins stub used to support *args, **kwargs.\n\nimport _typeshed\nfrom typing import TypeVar, Generic, Iterable, Sequence, Tuple, Dict, Any, overload, Mapping\n\nTco = TypeVar('Tco', covariant=True)\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, o: object) -> bool: pass\n    def __ne__(self, o: object) -> bool: pass\n\nclass type:\n    @overload\n    def __init__(self, o: object) -> None: pass\n    @overload\n    def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: pass\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: pass\n\nclass tuple(Iterable[Tco], Generic[Tco]): pass\n\nclass dict(Mapping[T, S], Generic[T, S]): pass\n\nclass list(Sequence[T], Generic[T]): pass\n\nclass int:\n    def __eq__(self, o: object) -> bool: pass\nclass float: pass\nclass str: pass\nclass bytes: pass\nclass bool: pass\nclass function: pass\nclass ellipsis: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/async_await.pyi",
    "content": "import typing\n\nT = typing.TypeVar('T')\nU = typing.TypeVar('U')\nclass list(typing.Sequence[T]):\n    def __iter__(self) -> typing.Iterator[T]: ...\n    def __getitem__(self, i: int) -> T: ...\n    def __contains__(self, item: object) -> bool: ...\n\nclass object:\n    def __init__(self) -> None: pass\nclass type: pass\nclass function: pass\nclass int: pass\nclass float: pass\nclass str: pass\nclass bool(int): pass\nclass dict(typing.Generic[T, U]): pass\nclass set(typing.Generic[T]): pass\nclass tuple(typing.Generic[T]): pass\nclass BaseException: pass\nclass StopIteration(BaseException): pass\nclass StopAsyncIteration(BaseException): pass\ndef iter(obj: typing.Any) -> typing.Any: pass\ndef next(obj: typing.Any) -> typing.Any: pass\nclass ellipsis: ...\n"
  },
  {
    "path": "test-data/unit/fixtures/bool.pyi",
    "content": "# builtins stub used in boolean-related test cases.\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, other: object) -> bool: pass\n    def __ne__(self, other: object) -> bool: pass\n\nclass type: pass\nclass tuple(Generic[T]): pass\nclass function: pass\nclass int: pass\nclass bool(int): pass\nclass float: pass\nclass str: pass\nclass ellipsis: pass\nclass list(Generic[T]): pass\nclass property: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/callable.pyi",
    "content": "from typing import Generic, Tuple, TypeVar, Union\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass tuple(Generic[T]): pass\n\nclass classmethod: pass\nclass staticmethod: pass\nclass function: pass\n\ndef isinstance(x: object, t: Union[type, Tuple[type, ...]]) -> bool: pass\n\ndef callable(x: object) -> bool: pass\n\nclass int:\n    def __add__(self, other: 'int') -> 'int': pass\n    def __eq__(self, other: 'int') -> 'bool': pass\nclass float: pass\nclass bool(int): pass\nclass str:\n    def __add__(self, other: 'str') -> 'str': pass\n    def __eq__(self, other: 'str') -> bool: pass\nclass ellipsis: pass\nclass list: ...\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/classmethod.pyi",
    "content": "import typing\n\n_T = typing.TypeVar('_T')\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n    def mro(self) -> typing.Any: pass\n\nclass function: pass\n\n# Dummy definitions.\nclass classmethod: pass\nclass staticmethod: pass\n\nclass int:\n    @classmethod\n    def from_bytes(cls, bytes: bytes, byteorder: str) -> int: pass\n\nclass float: pass\nclass str: pass\nclass bytes: pass\nclass bool: pass\nclass ellipsis: pass\n\nclass tuple(typing.Generic[_T]): pass\n\nclass list: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/complex.pyi",
    "content": "# Builtins stub used for some float/complex test cases.\n# Please don't add tuple to this file, it is used to test incomplete fixtures.\n\nclass object:\n    def __init__(self): pass\n\nclass type: pass\nclass function: pass\nclass int: pass\nclass float: pass\nclass complex: pass\nclass str: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/complex_tuple.pyi",
    "content": "from typing import Generic, TypeVar\n_T = TypeVar('_T')\n\nclass object:\n    def __init__(self): pass\n\nclass tuple(Generic[_T]): pass\n\nclass type: pass\nclass function: pass\nclass int: pass\nclass float: pass\nclass complex: pass\nclass str: pass\nclass ellipsis: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/dataclasses.pyi",
    "content": "import _typeshed\nfrom typing import (\n    Generic, Iterator, Iterable, Mapping, Optional, Sequence, Tuple,\n    TypeVar, Union, overload,\n)\nfrom typing_extensions import override\n\n_T = TypeVar('_T')\n_U = TypeVar('_U')\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __init_subclass__(cls) -> None: pass\n    def __eq__(self, o: object) -> bool: pass\n    def __ne__(self, o: object) -> bool: pass\n\nclass type: pass\nclass ellipsis: pass\nclass tuple(Generic[_T]): pass\nclass int: pass\nclass float: pass\nclass complex: pass\nclass bytes: pass\nclass str: pass\nclass bool(int): pass\n\nclass dict(Mapping[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: pass\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass\n    @override\n    def __getitem__(self, key: KT) -> VT: pass\n    def __setitem__(self, k: KT, v: VT) -> None: pass\n    @override\n    def __iter__(self) -> Iterator[KT]: pass\n    def __contains__(self, item: object) -> int: pass\n    def update(self, a: Mapping[KT, VT]) -> None: pass\n    @overload\n    def get(self, k: KT) -> Optional[VT]: pass\n    @overload\n    def get(self, k: KT, default: Union[KT, _T]) -> Union[VT, _T]: pass\n    def __len__(self) -> int: ...\n\nclass list(Generic[_T], Sequence[_T]):\n    def __contains__(self, item: object) -> int: pass\n    @override\n    def __getitem__(self, key: int) -> _T: pass\n    @override\n    def __iter__(self) -> Iterator[_T]: pass\n\nclass function: pass\nclass classmethod: pass\nclass staticmethod: pass\nproperty = object()\n"
  },
  {
    "path": "test-data/unit/fixtures/dict-full.pyi",
    "content": "# Builtins stub used in dictionary-related test cases (more complete).\n\nfrom _typeshed import SupportsKeysAndGetItem\nimport _typeshed\nfrom typing import (\n    TypeVar, Generic, Iterable, Iterator, Mapping, Tuple, overload, Optional, Union, Sequence,\n    Self,\n)\n\nT = TypeVar('T')\nT2 = TypeVar('T2')\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __init_subclass__(cls) -> None: pass\n    def __eq__(self, other: object) -> bool: pass\n\nclass type:\n    __annotations__: Mapping[str, object]\n\nclass dict(Mapping[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: pass\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass\n    def __getitem__(self, key: KT) -> VT: pass\n    def __setitem__(self, k: KT, v: VT) -> None: pass\n    def __iter__(self) -> Iterator[KT]: pass\n    def __contains__(self, item: object) -> int: pass\n    def update(self, a: SupportsKeysAndGetItem[KT, VT]) -> None: pass\n    @overload\n    def get(self, k: KT) -> Optional[VT]: pass\n    @overload\n    def get(self, k: KT, default: Union[VT, T]) -> Union[VT, T]: pass\n    def __len__(self) -> int: ...\n\n    # This was actually added in 3.9:\n    @overload\n    def __or__(self, __value: dict[KT, VT]) -> dict[KT, VT]: ...\n    @overload\n    def __or__(self, __value: dict[T, T2]) -> dict[Union[KT, T], Union[VT, T2]]: ...\n    @overload\n    def __ror__(self, __value: dict[KT, VT]) -> dict[KT, VT]: ...\n    @overload\n    def __ror__(self, __value: dict[T, T2]) -> dict[Union[KT, T], Union[VT, T2]]: ...\n    # dict.__ior__ should be kept roughly in line with MutableMapping.update()\n    @overload  # type: ignore[misc]\n    def __ior__(self, __value: _typeshed.SupportsKeysAndGetItem[KT, VT]) -> Self: ...\n    @overload\n    def __ior__(self, __value: Iterable[Tuple[KT, VT]]) -> Self: ...\n\nclass int: # for convenience\n    def __add__(self, x: Union[int, complex]) -> int: pass\n    def __radd__(self, x: int) -> int: pass\n    def __sub__(self, x: Union[int, complex]) -> int: pass\n    def __neg__(self) -> int: pass\n    real: int\n    imag: int\n\nclass str: pass # for keyword argument key type\nclass bytes: pass\n\nclass list(Sequence[T]): # needed by some test cases\n    def __getitem__(self, x: int) -> T: pass\n    def __iter__(self) -> Iterator[T]: pass\n    def __mul__(self, x: int) -> list[T]: pass\n    def __contains__(self, item: object) -> bool: pass\n    def append(self, item: T) -> None: pass\n\nclass tuple(Generic[T]): pass\nclass function: pass\nclass float: pass\nclass complex: pass\nclass bool(int): pass\n\nclass ellipsis:\n    __class__: object\ndef isinstance(x: object, t: Union[type, Tuple[type, ...]]) -> bool: pass\nclass BaseException: pass\n\ndef iter(__iterable: Iterable[T]) -> Iterator[T]: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/dict.pyi",
    "content": "# Builtins stub used in dictionary-related test cases (stripped down).\n#\n# NOTE: Use dict-full.pyi if you need more builtins instead of adding here,\n#       if feasible.\n\nfrom _typeshed import SupportsKeysAndGetItem\nimport _typeshed\nfrom typing import (\n    TypeVar, Generic, Iterable, Iterator, Mapping, Tuple, overload, Optional, Union, Sequence,\n    Self,\n)\n\nT = TypeVar('T')\nT2 = TypeVar('T2')\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, other: object) -> bool: pass\n\nclass type: pass\n\nclass dict(Mapping[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: pass\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass\n    def __getitem__(self, key: KT) -> VT: pass\n    def __setitem__(self, k: KT, v: VT) -> None: pass\n    def __iter__(self) -> Iterator[KT]: pass\n    def __contains__(self, item: object) -> int: pass\n    def update(self, a: SupportsKeysAndGetItem[KT, VT]) -> None: pass\n    @overload\n    def get(self, k: KT) -> Optional[VT]: pass\n    @overload\n    def get(self, k: KT, default: Union[VT, T]) -> Union[VT, T]: pass\n    def __len__(self) -> int: ...\n\nclass int: # for convenience\n    def __add__(self, x: Union[int, complex]) -> int: pass\n    def __radd__(self, x: int) -> int: pass\n    def __sub__(self, x: Union[int, complex]) -> int: pass\n\nclass str: pass # for keyword argument key type\nclass bytes: pass\n\nclass list(Sequence[T]): # needed by some test cases\n    def __getitem__(self, x: int) -> T: pass\n    def __iter__(self) -> Iterator[T]: pass\n    def __mul__(self, x: int) -> list[T]: pass\n    def __contains__(self, item: object) -> bool: pass\n    def append(self, item: T) -> None: pass\n\nclass tuple(Generic[T]): pass\nclass function: pass\nclass float: pass\nclass complex: pass\nclass bool(int): pass\nclass ellipsis: pass\nclass BaseException: pass\n\ndef isinstance(x: object, t: Union[type, Tuple[type, ...]]) -> bool: pass\ndef iter(__iterable: Iterable[T]) -> Iterator[T]: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/divmod.pyi",
    "content": "from typing import TypeVar, Tuple, SupportsInt\nclass object:\n    def __init__(self): pass\n\nclass int(SupportsInt):\n    def __divmod__(self, other: int) -> Tuple[int, int]: pass\n    def __rdivmod__(self, other: int) -> Tuple[int, int]: pass\n\nclass float(SupportsInt):\n    def __divmod__(self, other: float) -> Tuple[float, float]: pass\n    def __rdivmod__(self, other: float) -> Tuple[float, float]: pass\n\n\nclass tuple: pass\nclass function: pass\nclass str: pass\nclass type: pass\nclass ellipsis: pass\n\n_N = TypeVar('_N', int, float)\ndef divmod(_x: _N, _y: _N) -> Tuple[_N, _N]: ...\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/enum.pyi",
    "content": "# Minimal set of builtins required to work with Enums\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self): pass\n\nclass type: pass\nclass tuple(Generic[T]):\n    def __getitem__(self, x: int) -> T: pass\n\nclass int: pass\nclass str:\n    def __len__(self) -> int: pass\n\nclass dict: pass\nclass ellipsis: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/exception.pyi",
    "content": "import sys\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass object:\n    def __init__(self): pass\n\nclass type: pass\nclass tuple(Generic[T]):\n    def __ge__(self, other: object) -> bool: ...\nclass list: pass\nclass dict: pass\nclass function: pass\nclass int: pass\nclass str: pass\nclass bool: pass\nclass ellipsis: pass\n\nclass BaseException:\n    def __init__(self, *args: object) -> None: ...\nclass Exception(BaseException): pass\nclass RuntimeError(Exception): pass\nclass NotImplementedError(RuntimeError): pass\n\nif sys.version_info >= (3, 11):\n    _BT_co = TypeVar(\"_BT_co\", bound=BaseException, covariant=True)\n    _T_co = TypeVar(\"_T_co\", bound=Exception, covariant=True)\n    class BaseExceptionGroup(BaseException, Generic[_BT_co]): ...\n    class ExceptionGroup(BaseExceptionGroup[_T_co], Exception): ...\n"
  },
  {
    "path": "test-data/unit/fixtures/f_string.pyi",
    "content": "# Builtins stub used for format-string-related test cases.\n# We need str and list, and str needs join and format methods.\n\nfrom typing import TypeVar, Generic, Iterable, Iterator, List, overload\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self): pass\n\nclass type:\n    def __init__(self, x: object) -> None: pass\n\nclass ellipsis: pass\n\nclass list(Iterable[T], Generic[T]):\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: Iterable[T]) -> None: pass\n    def append(self, x: T) -> None: pass\n\nclass tuple(Generic[T]): pass\n\nclass function: pass\nclass int:\n    def __add__(self, i: int) -> int: pass\n\nclass float: pass\nclass bool(int): pass\n\nclass str:\n    def __add__(self, s: str) -> str: pass\n    def format(self, *args: object) -> str: pass\n    def join(self, l: List[str]) -> str: pass\n\nclass bytes: pass\n\nclass complex: pass\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/fine_grained.pyi",
    "content": "# Small stub for fine-grained incremental checking test cases\n#\n# TODO: Migrate to regular stubs once fine-grained incremental is robust\n#       enough to handle them.\n\nimport types\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass Any: pass\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x: Any) -> None: pass\n\nclass int:\n    def __add__(self, other: 'int') -> 'int': pass\nclass str:\n    def __add__(self, other: 'str') -> 'str': pass\n\nclass float: pass\nclass bytes: pass\nclass tuple(Generic[T]): pass\nclass function: pass\nclass ellipsis: pass\nclass list(Generic[T]): pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/float.pyi",
    "content": "from typing import Generic, TypeVar\nT = TypeVar('T')\n\nAny = 0\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x: Any) -> None: pass\n\nclass str:\n    def __add__(self, other: 'str') -> 'str': pass\n    def __rmul__(self, n: int) -> str: ...\n\nclass bytes: pass\n\nclass tuple(Generic[T]): pass\nclass function: pass\n\nclass ellipsis: pass\n\n\nclass int:\n    def __abs__(self) -> int: ...\n    def __float__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __mul__(self, x: int) -> int: ...\n    def __neg__(self) -> int: ...\n    def __rmul__(self, x: int) -> int: ...\n\nclass float:\n    def __float__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __mul__(self, x: float) -> float: ...\n    def __rmul__(self, x: float) -> float: ...\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/floatdict.pyi",
    "content": "from typing import TypeVar, Generic, Iterable, Iterator, Mapping, Tuple, overload, Optional, Union\n\nT = TypeVar('T')\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nAny = 0\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x: Any) -> None: pass\n\nclass str:\n    def __add__(self, other: 'str') -> 'str': pass\n    def __rmul__(self, n: int) -> str: ...\n\nclass bytes: pass\n\nclass tuple(Generic[T]): pass\nclass slice: pass\nclass function: pass\n\nclass ellipsis: pass\n\nclass list(Iterable[T], Generic[T]):\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: Iterable[T]) -> None: pass\n    def __iter__(self) -> Iterator[T]: pass\n    def __add__(self, x: list[T]) -> list[T]: pass\n    def __mul__(self, x: int) -> list[T]: pass\n    def __getitem__(self, x: int) -> T: pass\n    def append(self, x: T) -> None: pass\n    def extend(self, x: Iterable[T]) -> None: pass\n\nclass dict(Mapping[KT, VT], Generic[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: pass\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass\n    def __setitem__(self, k: KT, v: VT) -> None: pass\n    def __getitem__(self, k: KT) -> VT: pass\n    def __iter__(self) -> Iterator[KT]: pass\n    def update(self, a: Mapping[KT, VT]) -> None: pass\n    @overload\n    def get(self, k: KT) -> Optional[VT]: pass\n    @overload\n    def get(self, k: KT, default: Union[KT, T]) -> Union[VT, T]: pass\n\n\nclass int:\n    def __float__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __mul__(self, x: int) -> int: ...\n    def __rmul__(self, x: int) -> int: ...\n    def __truediv__(self, x: int) -> int: ...\n    def __rtruediv__(self, x: int) -> int: ...\n\nclass float:\n    def __float__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __mul__(self, x: float) -> float: ...\n    def __rmul__(self, x: float) -> float: ...\n    def __truediv__(self, x: float) -> float: ...\n    def __rtruediv__(self, x: float) -> float: ...\n"
  },
  {
    "path": "test-data/unit/fixtures/for.pyi",
    "content": "# builtins stub used in for statement test cases\n\nfrom typing import TypeVar, Generic, Iterable, Iterator, Generator\nfrom abc import abstractmethod, ABCMeta\n\nt = TypeVar('t')\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type: pass\nclass tuple(Generic[t]):\n    def __iter__(self) -> Iterator[t]: pass\nclass function: pass\nclass ellipsis: pass\nclass bool: pass\nclass int: pass # for convenience\nclass str:  # for convenience\n    def upper(self) -> str: ...\n\nclass list(Iterable[t], Generic[t]):\n    def __iter__(self) -> Iterator[t]: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/function.pyi",
    "content": "class object:\n    def __init__(self): pass\n\nclass type: pass\nclass function: pass\nclass int: pass\nclass str: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/isinstance.pyi",
    "content": "from typing import Tuple, TypeVar, Generic, Union, cast, Any, Type\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n    def __or__(self, other: type) -> type: pass\n\nclass tuple(Generic[T]): pass\n\nclass function: pass\n\ndef isinstance(x: object, t: Union[Type[object], Tuple[Type[object], ...]]) -> bool: pass\ndef issubclass(x: object, t: Union[Type[object], Tuple[Type[object], ...]]) -> bool: pass\ndef hasattr(x: object, name: str) -> bool: pass\n\nclass int:\n    def __add__(self, other: 'int') -> 'int': pass\nclass float: pass\nclass bool(int): pass\nclass str:\n    def __add__(self, other: 'str') -> 'str': pass\nclass ellipsis: pass\n\nNotImplemented = cast(Any, None)\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/isinstance_python3_10.pyi",
    "content": "# For Python 3.10+ only\nfrom typing import Tuple, TypeVar, Generic, Union, cast, Any, Type\nimport types\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n    def __or__(self, x) -> types.UnionType: pass\n\nclass tuple(Generic[T]): pass\n\nclass function: pass\n\ndef isinstance(x: object, t: Union[Type[object], Tuple[Type[object], ...], types.UnionType]) -> bool: pass\ndef issubclass(x: object, t: Union[Type[object], Tuple[Type[object], ...]]) -> bool: pass\n\nclass int:\n    def __add__(self, other: 'int') -> 'int': pass\nclass float: pass\nclass bool(int): pass\nclass str:\n    def __add__(self, other: 'str') -> 'str': pass\nclass ellipsis: pass\n\nNotImplemented = cast(Any, None)\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/isinstancelist.pyi",
    "content": "from typing import (\n    Iterable, Iterator, TypeVar, List, Mapping, overload, Tuple, Set, Union, Generic, Sequence\n)\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, other: object) -> bool: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass function: pass\nclass classmethod: pass\n\nclass ellipsis: pass\nEllipsisType = ellipsis\nEllipsis = ellipsis()\n\ndef isinstance(x: object, t: Union[type, Tuple]) -> bool: pass\ndef issubclass(x: object, t: Union[type, Tuple]) -> bool: pass\n\nclass int:\n    def __add__(self, x: int) -> int: pass\nclass float: pass\nclass bool(int): pass\nclass str:\n    def __add__(self, x: str) -> str: pass\n    def __getitem__(self, x: int) -> str: pass\n\nT = TypeVar('T')\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nclass tuple(Generic[T]):\n    def __len__(self) -> int: pass\n\nclass list(Sequence[T]):\n    def __iter__(self) -> Iterator[T]: pass\n    def __mul__(self, x: int) -> list[T]: pass\n    def __setitem__(self, x: int, v: T) -> None: pass\n    def __getitem__(self, x: int) -> T: pass\n    def __add__(self, x: List[T]) -> T: pass\n    def __contains__(self, item: object) -> bool: pass\n    def append(self, x: T) -> None: pass\n    def extend(self, x: Iterable[T]) -> None: pass\n\nclass dict(Mapping[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: pass\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass\n    def __setitem__(self, k: KT, v: VT) -> None: pass\n    def __iter__(self) -> Iterator[KT]: pass\n    def update(self, a: Mapping[KT, VT]) -> None: pass\n\nclass set(Generic[T]):\n    def __iter__(self) -> Iterator[T]: pass\n    def add(self, x: T) -> None: pass\n    def discard(self, x: T) -> None: pass\n    def update(self, x: Set[T]) -> None: pass\n    def pop(self) -> T: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/len.pyi",
    "content": "from typing import Tuple, TypeVar, Generic, Union, Type, Sequence, Mapping\nfrom typing_extensions import Protocol\n\nT = TypeVar(\"T\")\nV = TypeVar(\"V\")\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass tuple(Sequence[T]):\n    def __len__(self) -> int: pass\n\nclass list(Sequence[T]): pass\nclass dict(Mapping[T, V]): pass\n\nclass function: pass\n\nclass Sized(Protocol):\n    def __len__(self) -> int: pass\n\ndef len(__obj: Sized) -> int: ...\ndef isinstance(x: object, t: Union[Type[object], Tuple[Type[object], ...]]) -> bool: pass\n\nclass int:\n    def __add__(self, other: int) -> int: pass\n    def __eq__(self, other: int) -> bool: pass\n    def __ne__(self, other: int) -> 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 __neg__(self) -> int: pass\nclass float: pass\nclass bool(int): pass\nclass str(Sequence[str]): pass\nclass ellipsis: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/list.pyi",
    "content": "# Builtins stub used in list-related test cases.\n\nfrom typing import TypeVar, Generic, Iterable, Iterator, Sequence, overload\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, other: object) -> bool: pass\n\nclass type: pass\nclass ellipsis: pass\n\nclass list(Sequence[T]):\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: Iterable[T]) -> None: pass\n    def __iter__(self) -> Iterator[T]: pass\n    def __len__(self) -> int: pass\n    def __contains__(self, item: object) -> bool: pass\n    def __add__(self, x: list[T]) -> list[T]: pass\n    def __mul__(self, x: int) -> list[T]: pass\n    def __getitem__(self, x: int) -> T: pass\n    def __setitem__(self, x: int, v: T) -> None: pass\n    def append(self, x: T) -> None: pass\n    def extend(self, x: Iterable[T]) -> None: pass\n\nclass tuple(Generic[T]): pass\nclass function: pass\nclass int:\n    def __bool__(self) -> bool: pass\nclass float:\n    def __bool__(self) -> bool: pass\nclass str:\n    def __len__(self) -> bool: pass\nclass bool(int): pass\n\nproperty = object() # Dummy definition.\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/module.pyi",
    "content": "from typing import Any, Dict, Generic, TypeVar, Sequence\nfrom types import ModuleType\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass list(Generic[T], Sequence[T]): pass\n\nclass object:\n    def __init__(self) -> None: pass\nclass type: pass\nclass function: pass\nclass int: pass\nclass str: pass\nclass bool: pass\nclass tuple(Generic[T]): pass\nclass dict(Generic[T, S]): pass\nclass ellipsis: pass\n\nclassmethod = object()\nstaticmethod = object()\nproperty = object()\ndef hasattr(x: object, name: str) -> bool: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/module_all.pyi",
    "content": "from typing import Generic, Sequence, TypeVar\nfrom types import ModuleType\n\n_T = TypeVar('_T')\n\nclass object:\n    def __init__(self) -> None: pass\nclass type: pass\nclass function: pass\nclass int: pass\nclass str: pass\nclass bool: pass\nclass list(Generic[_T], Sequence[_T]):\n    def append(self, x: _T): pass\n    def extend(self, x: Sequence[_T]): pass\n    def remove(self, x: _T): pass\n    def __add__(self, rhs: Sequence[_T]) -> list[_T]: pass\nclass tuple(Generic[_T]): pass\nclass ellipsis: pass\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/narrowing.pyi",
    "content": "# Builtins stub used in check-narrowing test cases.\nfrom typing import Generic, Sequence, Tuple, Type, TypeVar, Union\n\n\nTco = TypeVar('Tco', covariant=True)\nKT = TypeVar(\"KT\")\nVT = TypeVar(\"VT\")\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type: pass\nclass tuple(Sequence[Tco], Generic[Tco]): pass\nclass function: pass\nclass ellipsis: pass\nclass int: pass\nclass str: pass\nclass dict(Generic[KT, VT]): pass\n\ndef isinstance(x: object, t: Union[Type[object], Tuple[Type[object], ...]]) -> bool: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/notimplemented.pyi",
    "content": "# builtins stub used in NotImplemented related cases.\nfrom typing import Any\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type: pass\nclass function: pass\nclass bool: pass\nclass int: pass\nclass str: pass\nclass dict: pass\n\nclass _NotImplementedType(Any):\n    __call__: NotImplemented  # type: ignore\nNotImplemented: _NotImplementedType\n\nclass BaseException: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/object_hashable.pyi",
    "content": "class object:\n    def __hash__(self) -> int: ...\n\nclass type: ...\nclass int: ...\nclass float: ...\nclass str: ...\nclass ellipsis: ...\nclass tuple: ...\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/object_with_init_subclass.pyi",
    "content": "from typing import Sequence, Iterator, TypeVar, Mapping, Iterable, Optional, Union, overload, Tuple, Generic, List\n\nclass object:\n    def __init__(self) -> None: ...\n    def __init_subclass__(cls) -> None: ...\n\nT = TypeVar('T')\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n# copy pasted from primitives.pyi\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass int:\n    # Note: this is a simplification of the actual signature\n    def __init__(self, x: object = ..., base: int = ...) -> None: pass\n    def __add__(self, i: int) -> int: pass\nclass float:\n    def __float__(self) -> float: pass\nclass complex: pass\nclass bool(int): pass\nclass str(Sequence[str]):\n    def __add__(self, s: str) -> str: pass\n    def __iter__(self) -> Iterator[str]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> str: pass\n    def format(self, *args) -> str: pass\nclass bytes(Sequence[int]):\n    def __iter__(self) -> Iterator[int]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> int: pass\nclass bytearray: pass\nclass tuple(Generic[T]): pass\nclass function: pass\nclass ellipsis: pass\n\n# copy-pasted from list.pyi\nclass list(Sequence[T]):\n    def __iter__(self) -> Iterator[T]: pass\n    def __mul__(self, x: int) -> list[T]: pass\n    def __setitem__(self, x: int, v: T) -> None: pass\n    def __getitem__(self, x: int) -> T: pass\n    def __add__(self, x: List[T]) -> T: pass\n    def __contains__(self, item: object) -> bool: pass\n\n# copy-pasted from dict.pyi\nclass dict(Mapping[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: pass\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: pass\n    def __getitem__(self, key: KT) -> VT: pass\n    def __setitem__(self, k: KT, v: VT) -> None: pass\n    def __iter__(self) -> Iterator[KT]: pass\n    def __contains__(self, item: object) -> int: pass\n    def update(self, a: Mapping[KT, VT]) -> None: pass\n    @overload\n    def get(self, k: KT) -> Optional[VT]: pass\n    @overload\n    def get(self, k: KT, default: Union[KT, T]) -> Union[VT, T]: pass\n    def __len__(self) -> int: ...\n"
  },
  {
    "path": "test-data/unit/fixtures/ops.pyi",
    "content": "from typing import overload, Any, Generic, Sequence, Tuple, TypeVar, Optional\n\nTco = TypeVar('Tco', covariant=True)\n\n# This is an extension of transform builtins with additional operations.\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, o: 'object') -> 'bool': pass\n    def __ne__(self, o: 'object') -> 'bool': pass\n\nclass type: pass\n\nclass slice: pass\n\nclass tuple(Sequence[Tco]):\n    def __getitem__(self, x: int) -> Tco: pass\n    def __eq__(self, x: object) -> bool: pass\n    def __ne__(self, x: object) -> bool: pass\n    def __lt__(self, x: Tuple[Tco, ...]) -> bool: pass\n    def __le__(self, x: Tuple[Tco, ...]) -> bool: pass\n    def __gt__(self, x: Tuple[Tco, ...]) -> bool: pass\n    def __ge__(self, x: Tuple[Tco, ...]) -> bool: pass\n\nclass function: pass\n\nclass str:\n    def __init__(self, x: 'int') -> None: pass\n    def __add__(self, x: 'str') -> 'str': pass\n    def __eq__(self, x: object) -> bool: pass\n    def startswith(self, x: 'str') -> bool: pass\n    def strip(self) -> 'str': pass\n\nclass int:\n    def __add__(self, x: 'int') -> 'int': pass\n    def __radd__(self, x: 'int') -> 'int': pass\n    def __sub__(self, x: 'int') -> 'int': pass\n    def __mul__(self, x: 'int') -> 'int': pass\n    def __div__(self, x: 'int') -> 'int': pass\n    def __rdiv__(self, x: 'int') -> 'int': pass\n    def __truediv__(self, x: 'int') -> 'int': pass\n    def __rtruediv__(self, x: 'int') -> 'int': pass\n    def __mod__(self, x: 'int') -> 'int': pass\n    def __floordiv__(self, x: 'int') -> 'int': pass\n    def __pow__(self, x: 'int', __modulo: Optional[int] = ...) -> Any: pass\n    def __pos__(self) -> 'int': pass\n    def __neg__(self) -> 'int': pass\n    def __eq__(self, x: object) -> bool: pass\n    def __ne__(self, x: object) -> bool: pass\n    def __lt__(self, x: 'int') -> bool: pass\n    def __le__(self, x: 'int') -> bool: pass\n    def __gt__(self, x: 'int') -> bool: pass\n    def __ge__(self, x: 'int') -> bool: pass\n\nclass bool(int): pass\n\nclass float:\n    def __add__(self, x: 'float') -> 'float': pass\n    def __radd__(self, x: 'float') -> 'float': pass\n    def __div__(self, x: 'float') -> 'float': pass\n    def __rdiv__(self, x: 'float') -> 'float': pass\n    def __truediv__(self, x: 'float') -> 'float': pass\n    def __rtruediv__(self, x: 'float') -> 'float': pass\n\nclass complex:\n    def __add__(self, x: complex) -> complex: pass\n    def __radd__(self, x: complex) -> complex: pass\n\nclass BaseException: pass\n\ndef __print(a1: object = None, a2: object = None, a3: object = None,\n            a4: object = None) -> None: pass\n\nclass ellipsis: pass\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/paramspec.pyi",
    "content": "# builtins stub for paramspec-related test cases\n\nimport _typeshed\nfrom typing import (\n    Sequence, Generic, TypeVar, Iterable, Iterator, Tuple, Mapping, Optional, Union, Type, overload,\n    Protocol\n)\n\nT = TypeVar(\"T\")\nT_co = TypeVar('T_co', covariant=True)\nKT = TypeVar(\"KT\")\nVT = TypeVar(\"VT\")\n\nclass object:\n    def __init__(self) -> None: ...\n\nclass function: ...\nclass ellipsis: ...\nclass classmethod: ...\n\nclass type:\n    def __init__(self, *a: object) -> None: ...\n    def __call__(self, *a: object) -> object: ...\n\nclass list(Sequence[T], Generic[T]):\n    @overload\n    def __getitem__(self, i: int) -> T: ...\n    @overload\n    def __getitem__(self, s: slice) -> list[T]: ...\n    def __contains__(self, item: object) -> bool: ...\n    def __iter__(self) -> Iterator[T]: ...\n\nclass int:\n    def __neg__(self) -> int: ...\n    def __add__(self, other: int) -> int: ...\n\nclass bool(int): ...\nclass float: ...\nclass slice: ...\nclass str: ...\nclass bytes: ...\n\nclass tuple(Sequence[T_co], Generic[T_co]):\n    def __new__(cls: Type[T], iterable: Iterable[T_co] = ...) -> T: ...\n    def __iter__(self) -> Iterator[T_co]: ...\n    def __contains__(self, item: object) -> bool: ...\n    def __getitem__(self, x: int) -> T_co: ...\n    def __mul__(self, n: int) -> Tuple[T_co, ...]: ...\n    def __rmul__(self, n: int) -> Tuple[T_co, ...]: ...\n    def __add__(self, x: Tuple[T_co, ...]) -> Tuple[T_co, ...]: ...\n    def __len__(self) -> int: ...\n    def count(self, obj: object) -> int: ...\n\nclass _ItemsView(Iterable[Tuple[KT, VT]]): ...\n\nclass dict(Mapping[KT, VT]):\n    @overload\n    def __init__(self, **kwargs: VT) -> None: ...\n    @overload\n    def __init__(self, arg: Iterable[Tuple[KT, VT]], **kwargs: VT) -> None: ...\n    def __getitem__(self, key: KT) -> VT: ...\n    def __setitem__(self, k: KT, v: VT) -> None: ...\n    def __iter__(self) -> Iterator[KT]: ...\n    def __contains__(self, item: object) -> int: ...\n    def update(self, a: Mapping[KT, VT]) -> None: ...\n    @overload\n    def get(self, k: KT) -> Optional[VT]: ...\n    @overload\n    def get(self, k: KT, default: Union[KT, T]) -> Union[VT, T]: ...\n    def __len__(self) -> int: ...\n    def pop(self, k: KT) -> VT: ...\n    def items(self) -> _ItemsView[KT, VT]: ...\n\ndef isinstance(x: object, t: type) -> bool: ...\n\nclass _Sized(Protocol):\n    def __len__(self) -> int: ...\n\ndef len(x: _Sized) -> int: ...\n"
  },
  {
    "path": "test-data/unit/fixtures/plugin_attrs.pyi",
    "content": "# Builtins stub used to support attrs plugin tests.\nfrom typing import Union, overload, Generic, Sequence, TypeVar, Type, Iterable, Iterator\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, o: object) -> bool: pass\n    def __ne__(self, o: object) -> bool: pass\n    def __hash__(self) -> int: ...\n\nclass type: pass\nclass bytes: pass\nclass function: pass\nclass float: pass\nclass int:\n    @overload\n    def __init__(self, x: Union[str, bytes, int] = ...) -> None: ...\n    @overload\n    def __init__(self, x: Union[str, bytes], base: int) -> None: ...\nclass bool(int): pass\nclass complex:\n    @overload\n    def __init__(self, real: float = ..., im: float = ...) -> None: ...\n    @overload\n    def __init__(self, real: str = ...) -> None: ...\n\nclass str: pass\nclass ellipsis: pass\nclass list: pass\nclass dict: pass\n\nT = TypeVar(\"T\")\nTco = TypeVar('Tco', covariant=True)\nclass tuple(Sequence[Tco], Generic[Tco]):\n    def __new__(cls: Type[T], iterable: Iterable[Tco] = ...) -> T: ...\n    def __iter__(self) -> Iterator[Tco]: pass\n    def __contains__(self, item: object) -> bool: pass\n    def __getitem__(self, x: int) -> Tco: pass\n\nproperty = object()  # Dummy definition\n"
  },
  {
    "path": "test-data/unit/fixtures/primitives.pyi",
    "content": "# builtins stub with non-generic primitive types\nimport _typeshed\nfrom typing import Generic, TypeVar, Sequence, Iterator, Mapping, Iterable, Tuple, Union\n\nT = TypeVar('T')\nV = TypeVar('V')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __str__(self) -> str: pass\n    def __eq__(self, other: object) -> bool: pass\n    def __ne__(self, other: object) -> bool: pass\n\nclass type:\n    def __init__(self, x: object) -> None: pass\n\nclass int:\n    # Note: this is a simplification of the actual signature\n    def __init__(self, x: object = ..., base: int = ...) -> None: pass\n    def __add__(self, i: int) -> int: pass\n    def __rmul__(self, x: int) -> int: pass\nclass float:\n    def __float__(self) -> float: pass\n    def __add__(self, x: float) -> float: pass\n    def hex(self) -> str: pass\nclass complex:\n    def __add__(self, x: complex) -> complex: pass\nclass bool(int): pass\nclass str(Sequence[str]):\n    def __add__(self, s: str) -> str: pass\n    def __iter__(self) -> Iterator[str]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> str: pass\n    def format(self, *args: object, **kwargs: object) -> str: pass\nclass bytes(Sequence[int]):\n    def __iter__(self) -> Iterator[int]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> int: pass\nclass bytearray(Sequence[int]):\n    def __init__(self, x: bytes) -> None: pass\n    def __iter__(self) -> Iterator[int]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> int: pass\nclass memoryview(Sequence[int]):\n    def __init__(self, x: bytes) -> None: pass\n    def __iter__(self) -> Iterator[int]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> int: pass\nclass tuple(Generic[T]):\n    def __contains__(self, other: object) -> bool: pass\nclass list(Sequence[T]):\n    def append(self, v: T) -> None: pass\n    def __iter__(self) -> Iterator[T]: pass\n    def __contains__(self, other: object) -> bool: pass\n    def __getitem__(self, item: int) -> T: pass\nclass dict(Mapping[T, V]):\n    def __iter__(self) -> Iterator[T]: pass\nclass set(Iterable[T]):\n    def __iter__(self) -> Iterator[T]: pass\nclass frozenset(Iterable[T]):\n    def __iter__(self) -> Iterator[T]: pass\nclass function: pass\nclass ellipsis: pass\n\nclass range(Sequence[int]):\n    def __init__(self, __x: int, __y: int = ..., __z: int = ...) -> None: pass\n    def count(self, value: int) -> int: pass\n    def index(self, value: int) -> int: pass\n    def __getitem__(self, i: int) -> int: pass\n    def __iter__(self) -> Iterator[int]: pass\n    def __contains__(self, other: object) -> bool: pass\n\ndef isinstance(x: object, t: Union[type, Tuple]) -> bool: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/property.pyi",
    "content": "import typing\n\n_T = typing.TypeVar('_T')\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x: typing.Any) -> None: pass\n\nclass function: pass\n\nproperty = object()  # Dummy definition\nclass classmethod: pass\n\nclass list: pass\nclass dict: pass\nclass int: pass\nclass float: pass\nclass str: pass\nclass bytes: pass\nclass bool: pass\nclass ellipsis: pass\n\nclass tuple(typing.Generic[_T]): pass\n"
  },
  {
    "path": "test-data/unit/fixtures/set.pyi",
    "content": "# Builtins stub used in set-related test cases.\n\nfrom typing import TypeVar, Generic, Iterator, Iterable, Set\n\nT = TypeVar('T')\n\nclass object:\n    def __init__(self) -> None: pass\n    def __eq__(self, other): pass\n\nclass type: pass\nclass tuple(Generic[T]): pass\nclass function: pass\n\nclass int: pass\nclass str: pass\nclass bool: pass\nclass ellipsis: pass\n\nclass set(Iterable[T], Generic[T]):\n    def __init__(self, iterable: Iterable[T] = ...) -> None: ...\n    def __iter__(self) -> Iterator[T]: pass\n    def __contains__(self, item: object) -> bool: pass\n    def __ior__(self, x: Set[T]) -> None: pass\n    def add(self, x: T) -> None: pass\n    def discard(self, x: T) -> None: pass\n    def update(self, x: Set[T]) -> None: pass\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/slice.pyi",
    "content": "# Builtins stub used in slicing test cases.\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass object:\n    def __init__(self): pass\n\nclass type: pass\nclass tuple(Generic[T]): pass\nclass function: pass\n\nclass int: pass\nclass str: pass\n\nclass slice: pass\nclass ellipsis: pass\nclass dict: pass\nclass list(Generic[T]):\n    def __getitem__(self, x: slice) -> list[T]: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/staticmethod.pyi",
    "content": "import typing\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x) -> None: pass\n\nclass function: pass\n\nstaticmethod = object() # Dummy definition.\nproperty = object()  # Dummy definition\n\nclass int:\n    @staticmethod\n    def from_bytes(bytes: bytes, byteorder: str) -> int: pass\n\nclass str: pass\nclass bytes: pass\nclass ellipsis: pass\nclass dict: pass\nclass tuple: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/transform.pyi",
    "content": "# Builtins stubs used implicitly in program transformation test cases.\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type: pass\n\n# str is handy for debugging; allows outputting messages.\nclass str: pass\n\n# Primitive types int/float have special coercion behaviour (they may have\n# a different representation from ordinary values).\n\nclass int: pass\n\nclass float: pass\n\n\n# The functions below are special functions used in test cases; their\n# implementations are actually in the __dynchk module, but they are defined\n# here so that the semantic analyzer and the type checker are happy without\n# having to analyze the entire __dynchk module all the time.\n#\n# The transformation implementation has special case handling for these\n# functions; it's a bit ugly but it works for now.\n\ndef __print(a1=None, a2=None, a3=None, a4=None):\n    # Do not use *args since this would require list and break many test\n    # cases.\n    pass\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/tuple-simple.pyi",
    "content": "# Builtins stub used in some tuple-related test cases.\n#\n# This is a simpler version of tuple.py which is useful\n# and makes some test cases easier to write/debug.\n\nfrom typing import Iterable, TypeVar, Generic\n\nT = TypeVar('T', covariant=True)\n\nclass object:\n    def __init__(self): pass\n\nclass type: pass\nclass tuple(Generic[T]):\n    def __getitem__(self, x: int) -> T: pass\nclass function: pass\n\n# We need int for indexing tuples.\nclass int: pass\nclass str: pass # For convenience\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/tuple.pyi",
    "content": "# Builtins stub used in tuple-related test cases.\n\nimport _typeshed\nfrom typing import Iterable, Iterator, TypeVar, Generic, Sequence, Optional, overload, Tuple, Type\n\n_T = TypeVar(\"_T\")\n_Tco = TypeVar('_Tco', covariant=True)\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, *a: object) -> None: pass\n    def __call__(self, *a: object) -> object: pass\nclass tuple(Sequence[_Tco], Generic[_Tco]):\n    def __new__(cls: Type[_T], iterable: Iterable[_Tco] = ...) -> _T: ...\n    def __iter__(self) -> Iterator[_Tco]: pass\n    def __contains__(self, item: object) -> bool: pass\n    @overload\n    def __getitem__(self, x: int) -> _Tco: pass\n    @overload\n    def __getitem__(self, x: slice) -> Tuple[_Tco, ...]: ...\n    def __mul__(self, n: int) -> Tuple[_Tco, ...]: pass\n    def __rmul__(self, n: int) -> Tuple[_Tco, ...]: pass\n    def __add__(self, x: Tuple[_Tco, ...]) -> Tuple[_Tco, ...]: pass\n    def count(self, obj: object) -> int: pass\nclass function:\n    __name__: str\nclass ellipsis: pass\nclass classmethod: pass\n\nclass complex: pass\n# We need int and slice for indexing tuples.\nclass int:\n    def __neg__(self) -> 'int': pass\n    def __pos__(self) -> 'int': pass\nclass float: pass\nclass slice: pass\nclass bool(int): pass\nclass str: pass # For convenience\nclass bytes: pass\nclass bytearray: pass\n\nclass list(Sequence[_T], Generic[_T]):\n    @overload\n    def __getitem__(self, i: int) -> _T: ...\n    @overload\n    def __getitem__(self, s: slice) -> list[_T]: ...\n    def __contains__(self, item: object) -> bool: ...\n    def __iter__(self) -> Iterator[_T]: ...\n\ndef isinstance(x: object, t: type) -> bool: pass\n\nclass BaseException: pass\n\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/type.pyi",
    "content": "# builtins stub used in type-related test cases.\n\nfrom typing import Any, Generic, TypeVar, List, Union\nimport sys\nimport types\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass object:\n    def __init__(self) -> None: pass\n    def __str__(self) -> 'str': pass\n\nclass list(Generic[T]): pass\n\nclass type:\n    __name__: str\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: pass\n    def __or__(self, other: Union[type, None]) -> type: pass\n    def __ror__(self, other: Union[type, None]) -> type: pass\n    def mro(self) -> List['type']: pass\n\nclass tuple(Generic[T]): pass\nclass dict(Generic[T, S]): pass\nclass function: pass\nclass bool: pass\nclass int: pass\nclass str: pass\nclass ellipsis: pass\nclass float: pass\n\nif sys.version_info >= (3, 10):  # type: ignore\n    def isinstance(obj: object, class_or_tuple: type | types.UnionType, /) -> bool: ...\nelse:\n    def isinstance(obj: object, class_or_tuple: type, /) -> bool: ...\n"
  },
  {
    "path": "test-data/unit/fixtures/typing-async.pyi",
    "content": "# Test stub for typing module, with features for async/await related tests.\n#\n# Use [typing fixtures/typing-async.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\ncast = 0\noverload = 0\nAny = object()\nUnion = 0\nOptional = 0\nTypeVar = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\nNamedTuple = 0\nType = 0\nClassVar = 0\nFinal = 0\nLiteral = 0\nNoReturn = 0\nSelf = 0\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\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\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\nclass Iterable(Protocol[T_co]):\n    @abstractmethod\n    def __iter__(self) -> 'Iterator[T_co]': pass\n\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\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\nclass AsyncIterable(Protocol[T]):\n    @abstractmethod\n    def __aiter__(self) -> 'AsyncIterator[T]': pass\n\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\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\nclass AsyncContextManager(Generic[T]):\n    def __aenter__(self) -> Awaitable[T]: pass\n    # Use Any because not all the precise types are in the fixtures.\n    def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> Awaitable[Any]: pass\n\nclass _SpecialForm: pass\n"
  },
  {
    "path": "test-data/unit/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: ...\n    def __or__(self, other): ...\n    def __ror__(self, other): ...\nclass TypeVar:\n    def __init__(self, name, *args, bound=None): ...\n    def __or__(self, other): ...\nclass ParamSpec: ...\nclass TypeVarTuple: ...\n\ndef cast(t, o): ...\ndef assert_type(o, t): ...\noverload = 0\nAny = object()\nOptional = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\n_promote = 0\nType = 0\nno_type_check = 0\nClassVar = 0\nFinal = 0\nTypedDict = 0\nNoReturn = 0\nNewType = 0\nSelf = 0\nUnpack = 0\nTypeAlias = 0\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')\nP = ParamSpec(\"P\")\n\nclass Callable(Protocol[P, T_co]):\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\ndef final(x: T) -> T: ...\n\nclass NamedTuple(tuple[Any, ...]): ...\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 Hashable(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __hash__(self) -> int: pass\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 MutableSequence(Sequence[T]):\n    @abstractmethod\n    def __setitem__(self, n: Any, o: T) -> None: 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 __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\nclass SupportsAbs(Protocol[T_co]):\n    def __abs__(self) -> T_co: pass\n\ndef runtime_checkable(cls: T) -> T:\n    return cls\n\nclass ContextManager(Generic[T_co]):\n    def __enter__(self) -> T_co: 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\ndef dataclass_transform(\n    *,\n    eq_default: bool = ...,\n    order_default: bool = ...,\n    kw_only_default: bool = ...,\n    field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ...,\n    **kwargs: Any,\n) -> Callable[[T], T]: ...\ndef override(__arg: T) -> T: ...\n\n# Was added in 3.11\ndef reveal_type(__obj: T) -> T: ...\n\n# Only exists in type checking time:\ndef type_check_only(__func_or_class: T) -> T: ...\n\n# Was added in 3.12\n@final\nclass TypeAliasType:\n    def __init__(\n        self, name: str, value: Any, *, type_params: Tuple[Union[TypeVar, ParamSpec, TypeVarTuple], ...] = ()\n    ) -> None: ...\n\n    def __or__(self, other: Any) -> Any: ...\n    def __ror__(self, other: Any) -> Any: ...\n"
  },
  {
    "path": "test-data/unit/fixtures/typing-medium.pyi",
    "content": "# More complete stub for typing module.\n#\n# Use [typing fixtures/typing-medium.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\ncast = 0\noverload = 0\nAny = object()\nUnion = 0\nOptional = 0\nTypeVar = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\n_promote = 0\nNamedTuple = 0\nType = 0\nno_type_check = 0\nClassVar = 0\nFinal = 0\nLiteral = 0\nTypedDict = 0\nNoReturn = 0\nNewType = 0\nTypeAlias = 0\nLiteralString = 0\nSelf = 0\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\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\nclass Sized(Protocol):\n    def __len__(self) -> int: pass\n\nclass Iterable(Protocol[T_co]):\n    def __iter__(self) -> 'Iterator[T_co]': pass\n\nclass Iterator(Iterable[T_co], Protocol):\n    def __next__(self) -> T_co: pass\n\nclass Generator(Iterator[T], Generic[T, U, V]):\n    def __iter__(self) -> 'Generator[T, U, V]': pass\n\nclass Sequence(Iterable[T_co]):\n    def __getitem__(self, n: Any) -> T_co: pass\n\nclass Mapping(Iterable[T], Generic[T, T_co]):\n    def keys(self) -> Iterable[T]: pass  # Approximate return type\n    def __getitem__(self, key: T) -> T_co: pass\n\nclass SupportsInt(Protocol):\n    def __int__(self) -> int: pass\n\nclass SupportsFloat(Protocol):\n    def __float__(self) -> float: pass\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\n\nclass _SpecialForm: pass\n\nTYPE_CHECKING = 1\n"
  },
  {
    "path": "test-data/unit/fixtures/typing-namedtuple.pyi",
    "content": "TypeVar = 0\nGeneric = 0\nAny = object()\noverload = 0\nType = 0\nLiteral = 0\nOptional = 0\nSelf = 0\nTuple = 0\nClassVar = 0\nFinal = 0\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nKT = TypeVar('KT')\n\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\nclass Iterable(Generic[T_co]): pass\nclass Iterator(Iterable[T_co]): pass\nclass Sequence(Iterable[T_co]): pass\nclass Mapping(Iterable[KT], Generic[KT, T_co]):\n    def keys(self) -> Iterable[T]: pass  # Approximate return type\n    def __getitem__(self, key: T) -> T_co: pass\n\nclass NamedTuple(tuple[Any, ...]):\n    _fields: ClassVar[tuple[str, ...]]\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\nclass _SpecialForm: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/typing-override.pyi",
    "content": "TypeVar = 0\nGeneric = 0\nAny = object()\noverload = 0\nType = 0\nLiteral = 0\nOptional = 0\nSelf = 0\nTuple = 0\nClassVar = 0\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nKT = TypeVar('KT')\n\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\nclass Iterable(Generic[T_co]): pass\nclass Iterator(Iterable[T_co]): pass\nclass Sequence(Iterable[T_co]): pass\nclass Mapping(Iterable[KT], Generic[KT, T_co]):\n    def keys(self) -> Iterable[T]: pass  # Approximate return type\n    def __getitem__(self, key: T) -> T_co: pass\n\ndef override(__arg: T) -> T: ...\n\nclass _SpecialForm: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/typing-typeddict-iror.pyi",
    "content": "# Test stub for typing module that includes TypedDict `|` operator.\n# It only covers `__or__`, `__ror__`, and `__ior__`.\n#\n# We cannot define these methods in `typing-typeddict.pyi`,\n# because they need `dict` with two type args,\n# and not all tests using `[typing typing-typeddict.pyi]` have the proper\n# `dict` stub.\n#\n# Keep in sync with `typeshed`'s definition.\nfrom abc import ABCMeta\n\ncast = 0\nassert_type = 0\noverload = 0\nAny = object()\nUnion = 0\nOptional = 0\nTypeVar = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\nNamedTuple = 0\nFinal = 0\nLiteral = 0\nTypedDict = 0\nNoReturn = 0\nRequired = 0\nNotRequired = 0\nSelf = 0\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nV = TypeVar('V')\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\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\nclass Sized(Protocol):\n    def __len__(self) -> int: pass\n\nclass Iterable(Protocol[T_co]):\n    def __iter__(self) -> 'Iterator[T_co]': pass\n\nclass Iterator(Iterable[T_co], Protocol):\n    def __next__(self) -> T_co: pass\n\nclass Sequence(Iterable[T_co]):\n    # misc is for explicit Any.\n    def __getitem__(self, n: Any) -> T_co: pass # type: ignore[misc]\n\nclass Mapping(Iterable[T], Generic[T, T_co], metaclass=ABCMeta):\n    pass\n\n# Fallback type for all typed dicts (does not exist at runtime).\nclass _TypedDict(Mapping[str, object]):\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 __or__ and __ior__\n    def __ior__(self, __value: Self) -> Self: ...  # type: ignore[misc]\n\nclass _SpecialForm: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/typing-typeddict.pyi",
    "content": "# Test stub for typing module that includes TypedDict related things.\n#\n# Use [typing fixtures/typing-typeddict.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 ABCMeta\n\ncast = 0\nassert_type = 0\noverload = 0\nAny = object()\nUnion = 0\nOptional = 0\nTypeVar = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\nNamedTuple = 0\nFinal = 0\nLiteral = 0\nTypedDict = 0\nNoReturn = 0\nRequired = 0\nNotRequired = 0\nReadOnly = 0\nSelf = 0\nClassVar = 0\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nV = TypeVar('V')\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\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\nclass Sized(Protocol):\n    def __len__(self) -> int: pass\n\nclass Iterable(Protocol[T_co]):\n    def __iter__(self) -> 'Iterator[T_co]': pass\n\nclass Iterator(Iterable[T_co], Protocol):\n    def __next__(self) -> T_co: pass\n\nclass Sequence(Iterable[T_co]):\n    def __getitem__(self, n: Any) -> T_co: pass # type: ignore[explicit-any]\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 __len__(self) -> int: ...\n    def __contains__(self, arg: object) -> int: pass\n\nclass MutableMapping(Mapping[T, T_co], Generic[T, T_co], metaclass=ABCMeta):\n    # Other methods are not used in tests.\n    def clear(self) -> None: ...\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 _SpecialForm: pass\n"
  },
  {
    "path": "test-data/unit/fixtures/union.pyi",
    "content": "# Builtins stub used in tuple-related test cases.\n\nfrom isinstance import isinstance\nfrom typing import Iterable, TypeVar, Generic\nT = TypeVar('T')\n\nclass object:\n    def __init__(self): pass\n\nclass type: pass\nclass function: pass\n\nclass tuple(Generic[T]): pass\n\n# We need int for indexing tuples.\nclass int: pass\nclass str: pass # For convenience\nclass dict: pass\n"
  },
  {
    "path": "test-data/unit/hacks.txt",
    "content": "Weird legacy stuff in test cases\n================================\n\nDue to historical reasons, test cases contain things that may appear\nbaffling without extra context. This file attempts to describe most of\nthem.\n\nDummy if statements to prevent redefinition\n-------------------------------------------\n\nMany test cases use if statements to prevent an assignment from creating\na new variable. This in anticipation of allowing assignments to redefine\nvariables by default. Conditional assignments will continue to refine\na previously defined variable instead of defining a new one. When the\ntest cases were written, we didn't anticipate that variables could be\nallowed to be redefined, and adding if statements was the easiest way\nto migrate these tests.\n\nExample:\n\n```\nx = 0\nif int():\n    x = ''  # Always generates an error since this is not a redefinition\n\ny = 0\ny = ''  # This could be valid if a new 'y' is defined here\n```\n\nNote that some of the checks may turn out to be redundant, as the\nexact rules for what constitutes a redefinition are still up for\ndebate. This is okay since the extra if statements generally don't\notherwise affect semantics.\n\nThere are a few ways this is used, depending on the context:\n\n* `if int():` is the most common one. Assignments in the if body won't\n  redefine variables defined before the if statement.\n* `if 1:` is used if the body of the if statement returns a value, and\n  mypy would complain about a missing return statement otherwise. This\n  works since `if 1:` is treated as an always taken condition, whereas\n  `if int():` is not recognized as such.\n* `if str():` is used if the builtins fixture doesn't define `int` for\n  some reason.\n\nFunction definition to prevent redefinition\n-------------------------------------------\n\nSometimes test cases assume that a variable is not redefined, and we\ninsert a dummy function definition to prevent this, since variables won't\nbe able to be redefined across a function definition. Example:\n\n```\nx = 0\n\ndef f(): pass\n\nx = ''  # Does not redefine x because of the definition of f() above\n```\n\nDummy variable reference to allow redefinition\n----------------------------------------------\n\nThe plan is to only allow a variable to be redefined if the value has\nbeen accessed. This wouldn't count as redefinition, since `x` is never\nread:\n\n```\nx = 0\nx = ''  # Not a redefinition\n```\n\nSometimes we add a dummy variable access to allow redefinition in the\nfuture, or to trigger the redefinition machinery even if redefinition\nshould not be okay:\n\n```\nx = 0\nx\nx = ''  # Could be a redefinition\n```\n\nThe reason for this special case is type comments with dummy\ninitializers, where the second assignment should never be treated\nas a redefinition:\n\n```\nx = None  # type: int\nx = ''  # Should not redefine x, since it has only been declared\n```\n\nSimilarly, if there is only a variable annotation, the first\nassignment won't redefine the variable, as this would override\nthe declared type:\n\n```\nx: int\nx = ''  # Should not redefine x\n```\n"
  },
  {
    "path": "test-data/unit/lib-stub/_decimal.pyi",
    "content": "# Very simplified decimal stubs for use in tests\n\nclass Decimal:\n    def __new__(cls, value: str = ...) -> Decimal: ...\n    def __format__(self, spec: str) -> str: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/_typeshed.pyi",
    "content": "from typing import Protocol, TypeVar, Iterable\n\n_KT = TypeVar(\"_KT\")\n_VT_co = TypeVar(\"_VT_co\", covariant=True)\n\nclass SupportsKeysAndGetItem(Protocol[_KT, _VT_co]):\n    def keys(self) -> Iterable[_KT]: pass\n    def __getitem__(self, __key: _KT) -> _VT_co: pass\n"
  },
  {
    "path": "test-data/unit/lib-stub/abc.pyi",
    "content": "from typing import Type, Any, TypeVar\n\nT = TypeVar('T', bound=Type[Any])\n\nclass ABCMeta(type):\n    def register(cls, tp: T) -> T: pass\nclass ABC(metaclass=ABCMeta): pass\nabstractmethod = object()\nabstractproperty = object()\n"
  },
  {
    "path": "test-data/unit/lib-stub/attr/__init__.pyi",
    "content": "from typing import TypeVar, overload, Callable, Any, Type, Optional, Union, Sequence, Mapping, Generic\n\n_T = TypeVar('_T')\n_C = TypeVar('_C', bound=type)\n\n_ValidatorType = Callable[[Any, Any, _T], Any]\n_ConverterType = Callable[[Any], _T]\n_FilterType = Callable[[Any, Any], bool]\n_ValidatorArgType = Union[_ValidatorType[_T], Sequence[_ValidatorType[_T]]]\n\n# This form catches explicit None or no default but with no other arguments returns Any.\n@overload\ndef attrib(default: None = ...,\n           validator: None = ...,\n           repr: bool = ...,\n           cmp: Optional[bool] = ...,\n           hash: Optional[bool] = ...,\n           init: bool = ...,\n           convert: None = ...,\n           metadata: Optional[Mapping[Any, Any]] = ...,\n           type: None = ...,\n           converter: None = ...,\n           factory: None = ...,\n           kw_only: bool = ...,\n           eq: Optional[bool] = ...,\n           order: Optional[bool] = ...,\n           ) -> Any: ...\n# This form catches an explicit None or no default and infers the type from the other arguments.\n@overload\ndef attrib(default: None = ...,\n           validator: Optional[_ValidatorArgType[_T]] = ...,\n           repr: bool = ...,\n           cmp: Optional[bool] = ...,\n           hash: Optional[bool] = ...,\n           init: bool = ...,\n           convert: Optional[_ConverterType[_T]] = ...,\n           metadata: Optional[Mapping[Any, Any]] = ...,\n           type: Optional[Type[_T]] = ...,\n           converter: Optional[_ConverterType[_T]] = ...,\n           factory: Optional[Callable[[], _T]] = ...,\n           kw_only: bool = ...,\n           eq: Optional[bool] = ...,\n           order: Optional[bool] = ...,\n           ) -> _T: ...\n# This form catches an explicit default argument.\n@overload\ndef attrib(default: _T,\n           validator: Optional[_ValidatorArgType[_T]] = ...,\n           repr: bool = ...,\n           cmp: Optional[bool] = ...,\n           hash: Optional[bool] = ...,\n           init: bool = ...,\n           convert: Optional[_ConverterType[_T]] = ...,\n           metadata: Optional[Mapping[Any, Any]] = ...,\n           type: Optional[Type[_T]] = ...,\n           converter: Optional[_ConverterType[_T]] = ...,\n           factory: Optional[Callable[[], _T]] = ...,\n           kw_only: bool = ...,\n           eq: Optional[bool] = ...,\n           order: Optional[bool] = ...,\n           ) -> _T: ...\n# This form covers type=non-Type: e.g. forward references (str), Any\n@overload\ndef attrib(default: Optional[_T] = ...,\n           validator: Optional[_ValidatorArgType[_T]] = ...,\n           repr: bool = ...,\n           cmp: Optional[bool] = ...,\n           hash: Optional[bool] = ...,\n           init: bool = ...,\n           convert: Optional[_ConverterType[_T]] = ...,\n           metadata: Optional[Mapping[Any, Any]] = ...,\n           type: object = ...,\n           converter: Optional[_ConverterType[_T]] = ...,\n           factory: Optional[Callable[[], _T]] = ...,\n           kw_only: bool = ...,\n           eq: Optional[bool] = ...,\n           order: Optional[bool] = ...,\n           ) -> Any: ...\n\n@overload\ndef attrs(maybe_cls: _C,\n          these: Optional[Mapping[str, Any]] = ...,\n          repr_ns: Optional[str] = ...,\n          repr: bool = ...,\n          cmp: Optional[bool] = ...,\n          hash: Optional[bool] = ...,\n          init: bool = ...,\n          slots: bool = ...,\n          frozen: bool = ...,\n          weakref_slot: bool = ...,\n          str: bool = ...,\n          auto_attribs: bool = ...,\n          kw_only: bool = ...,\n          cache_hash: bool = ...,\n          eq: Optional[bool] = ...,\n          order: Optional[bool] = ...,\n          match_args: bool = ...,\n          ) -> _C: ...\n@overload\ndef attrs(maybe_cls: None = ...,\n          these: Optional[Mapping[str, Any]] = ...,\n          repr_ns: Optional[str] = ...,\n          repr: bool = ...,\n          cmp: Optional[bool] = ...,\n          hash: Optional[bool] = ...,\n          init: bool = ...,\n          slots: bool = ...,\n          frozen: bool = ...,\n          weakref_slot: bool = ...,\n          str: bool = ...,\n          auto_attribs: bool = ...,\n          kw_only: bool = ...,\n          cache_hash: bool = ...,\n          eq: Optional[bool] = ...,\n          order: Optional[bool] = ...,\n          match_args: bool = ...,\n          ) -> Callable[[_C], _C]: ...\n\n\nclass Attribute(Generic[_T]): pass\n\n# aliases\ns = attributes = attrs\nib = attr = attrib\ndataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;)\n\n# Next Generation API\n@overload\ndef define(\n    maybe_cls: _C,\n    *,\n    these: Optional[Mapping[str, Any]] = ...,\n    repr: bool = ...,\n    unsafe_hash: Optional[bool]=None,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    slots: bool = ...,\n    frozen: bool = ...,\n    weakref_slot: bool = ...,\n    str: bool = ...,\n    auto_attribs: bool = ...,\n    kw_only: bool = ...,\n    cache_hash: bool = ...,\n    auto_exc: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    auto_detect: bool = ...,\n    getstate_setstate: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> _C: ...\n@overload\ndef define(\n    maybe_cls: None = ...,\n    *,\n    these: Optional[Mapping[str, Any]] = ...,\n    repr: bool = ...,\n    unsafe_hash: Optional[bool]=None,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    slots: bool = ...,\n    frozen: bool = ...,\n    weakref_slot: bool = ...,\n    str: bool = ...,\n    auto_attribs: bool = ...,\n    kw_only: bool = ...,\n    cache_hash: bool = ...,\n    auto_exc: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    auto_detect: bool = ...,\n    getstate_setstate: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> Callable[[_C], _C]: ...\n\nmutable = define\nfrozen = define  # they differ only in their defaults\n\n@overload\ndef field(\n    *,\n    default: None = ...,\n    validator: None = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: None = ...,\n    factory: None = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[_OnSetAttrArgType] = ...,\n) -> Any: ...\n\n# This form catches an explicit None or no default and infers the type from the\n# other arguments.\n@overload\ndef field(\n    *,\n    default: None = ...,\n    validator: Optional[_ValidatorArgType[_T]] = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: Optional[_ConverterType] = ...,\n    factory: Optional[Callable[[], _T]] = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> _T: ...\n\n# This form catches an explicit default argument.\n@overload\ndef field(\n    *,\n    default: _T,\n    validator: Optional[_ValidatorArgType[_T]] = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: Optional[_ConverterType] = ...,\n    factory: Optional[Callable[[], _T]] = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> _T: ...\n\n# This form covers type=non-Type: e.g. forward references (str), Any\n@overload\ndef field(\n    *,\n    default: Optional[_T] = ...,\n    validator: Optional[_ValidatorArgType[_T]] = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: Optional[_ConverterType] = ...,\n    factory: Optional[Callable[[], _T]] = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> Any: ...\n\ndef evolve(inst: _T, **changes: Any) -> _T: ...\ndef assoc(inst: _T, **changes: Any) -> _T: ...\n\ndef fields(cls: type) -> Any: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/attr/converters.pyi",
    "content": "from typing import TypeVar, Optional, Callable, overload\nfrom . import _ConverterType\n\n_T = TypeVar(\"_T\")\n\ndef optional(\n    converter: _ConverterType[_T]\n) -> _ConverterType[Optional[_T]]: ...\n@overload\ndef default_if_none(default: _T) -> _ConverterType[_T]: ...\n@overload\ndef default_if_none(*, factory: Callable[[], _T]) -> _ConverterType[_T]: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/attrs/__init__.pyi",
    "content": "from typing import TypeVar, overload, Callable, Any, Optional, Union, Sequence, Mapping, \\\n    Protocol, ClassVar, Type\nfrom typing_extensions import TypeGuard\n\nfrom attr import Attribute as Attribute\n\n\nclass AttrsInstance(Protocol):\n    __attrs_attrs__: ClassVar[Any]\n\n\n_T = TypeVar('_T')\n_C = TypeVar('_C', bound=type)\n\n_ValidatorType = Callable[[Any, Any, _T], Any]\n_ConverterType = Callable[[Any], _T]\n_ValidatorArgType = Union[_ValidatorType[_T], Sequence[_ValidatorType[_T]]]\n\n@overload\ndef define(\n    maybe_cls: _C,\n    *,\n    these: Optional[Mapping[str, Any]] = ...,\n    repr: bool = ...,\n    unsafe_hash: Optional[bool]=None,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    slots: bool = ...,\n    frozen: bool = ...,\n    weakref_slot: bool = ...,\n    str: bool = ...,\n    auto_attribs: bool = ...,\n    kw_only: bool = ...,\n    cache_hash: bool = ...,\n    auto_exc: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    auto_detect: bool = ...,\n    getstate_setstate: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> _C: ...\n@overload\ndef define(\n    maybe_cls: None = ...,\n    *,\n    these: Optional[Mapping[str, Any]] = ...,\n    repr: bool = ...,\n    unsafe_hash: Optional[bool]=None,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    slots: bool = ...,\n    frozen: bool = ...,\n    weakref_slot: bool = ...,\n    str: bool = ...,\n    auto_attribs: bool = ...,\n    kw_only: bool = ...,\n    cache_hash: bool = ...,\n    auto_exc: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    auto_detect: bool = ...,\n    getstate_setstate: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n) -> Callable[[_C], _C]: ...\n\nmutable = define\nfrozen = define  # they differ only in their defaults\n\n@overload\ndef field(\n    *,\n    default: None = ...,\n    validator: None = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: None = ...,\n    factory: None = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[_OnSetAttrArgType] = ...,\n    alias: Optional[str] = ...,\n) -> Any: ...\n\n# This form catches an explicit None or no default and infers the type from the\n# other arguments.\n@overload\ndef field(\n    *,\n    default: None = ...,\n    validator: Optional[_ValidatorArgType[_T]] = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: Optional[_ConverterType] = ...,\n    factory: Optional[Callable[[], _T]] = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n    alias: Optional[str] = ...,\n) -> _T: ...\n\n# This form catches an explicit default argument.\n@overload\ndef field(\n    *,\n    default: _T,\n    validator: Optional[_ValidatorArgType[_T]] = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: Optional[_ConverterType] = ...,\n    factory: Optional[Callable[[], _T]] = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n    alias: Optional[str] = ...,\n) -> _T: ...\n\n# This form covers type=non-Type: e.g. forward references (str), Any\n@overload\ndef field(\n    *,\n    default: Optional[_T] = ...,\n    validator: Optional[_ValidatorArgType[_T]] = ...,\n    repr: object = ...,\n    hash: Optional[bool] = ...,\n    init: bool = ...,\n    metadata: Optional[Mapping[Any, Any]] = ...,\n    converter: Optional[_ConverterType] = ...,\n    factory: Optional[Callable[[], _T]] = ...,\n    kw_only: bool = ...,\n    eq: Optional[bool] = ...,\n    order: Optional[bool] = ...,\n    on_setattr: Optional[object] = ...,\n    alias: Optional[str] = ...,\n) -> Any: ...\n\ndef evolve(inst: _T, **changes: Any) -> _T: ...\ndef assoc(inst: _T, **changes: Any) -> _T: ...\ndef has(cls: type) -> TypeGuard[Type[AttrsInstance]]: ...\ndef fields(cls: Type[AttrsInstance]) -> Any: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/attrs/converters.pyi",
    "content": "from typing import TypeVar, Optional, Callable, overload\nfrom attr import _ConverterType\n\n_T = TypeVar(\"_T\")\n\ndef optional(\n    converter: _ConverterType[_T]\n) -> _ConverterType[Optional[_T]]: ...\n@overload\ndef default_if_none(default: _T) -> _ConverterType[_T]: ...\n@overload\ndef default_if_none(*, factory: Callable[[], _T]) -> _ConverterType[_T]: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/basedtyping.pyi",
    "content": "# Stub for basedtyping. Many of the definitions have special handling in\n# the type checker, so they can just be initialized to anything.\n#\n# DO NOT ADD TO THIS FILE UNLESS YOU HAVE A GOOD REASON! Additional definitions\n# will slow down tests.\n\nUntyped = 0\nIntersection = 1\nFunctionType = 2\n"
  },
  {
    "path": "test-data/unit/lib-stub/blocker.pyi",
    "content": "# Stub file that generates a blocking parse error\nx y\n"
  },
  {
    "path": "test-data/unit/lib-stub/blocker2.pyi",
    "content": "# Stub file that generates a blocking semantic analysis error\ncontinue\n"
  },
  {
    "path": "test-data/unit/lib-stub/broken.pyi",
    "content": "# Stub file that generates an error\nx = y\n"
  },
  {
    "path": "test-data/unit/lib-stub/builtins.pyi",
    "content": "# DO NOT ADD TO THIS FILE AS IT WILL SLOW DOWN TESTS!\n#\n# Use [builtins fixtures/...pyi] if you need more features.\n\nimport _typeshed\n\nclass object:\n    def __init__(self) -> None: pass\n\nclass type:\n    def __init__(self, x: object) -> None: pass\n\n# These are provided here for convenience.\nclass int:\n    def __add__(self, other: int) -> int: pass\nclass bool(int): pass\nclass float: pass\n\nclass str: pass\nclass bytes: pass\n\nclass function:\n    __name__: str\nclass ellipsis: pass\n\nfrom typing import Generic, Iterator, Sequence, TypeVar\n_T = TypeVar('_T')\nclass list(Generic[_T], Sequence[_T]):\n    def __contains__(self, item: object) -> bool: pass\n    def __getitem__(self, key: int) -> _T: pass\n    def __iter__(self) -> Iterator[_T]: pass\n\nclass dict: pass\n\n# Definition of None is implicit\n"
  },
  {
    "path": "test-data/unit/lib-stub/collections.pyi",
    "content": "from typing import Any, Iterable, Union, Dict, TypeVar, Optional, Callable, Generic, Sequence, MutableMapping\n\ndef namedtuple(\n    typename: str,\n    field_names: Union[str, Iterable[str]],\n    *,\n    # really bool but many tests don't have bool available\n    rename: int = ...,\n    module: Optional[str] = ...,\n    defaults: Optional[Iterable[Any]] = ...\n) -> Any: ...\n\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nclass OrderedDict(Dict[KT, VT]): ...\n\nclass defaultdict(Dict[KT, VT]):\n    def __init__(self, default_factory: Optional[Callable[[], VT]]) -> None: ...\n\nclass Counter(Dict[KT, int], Generic[KT]): ...\n\nclass deque(Sequence[KT], Generic[KT]): ...\n\nclass ChainMap(MutableMapping[KT, VT], Generic[KT, VT]): ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/contextlib.pyi",
    "content": "from typing import AsyncIterator, Generic, TypeVar, Callable, Iterator\nfrom typing import ContextManager as ContextManager, AsyncContextManager as AsyncContextManager\n\n_T = TypeVar('_T')\n\nclass GeneratorContextManager(ContextManager[_T], Generic[_T]):\n    def __call__(self, func: Callable[..., _T]) -> Callable[..., _T]: ...\n\n# This does not match `typeshed` definition, needs `ParamSpec`:\ndef contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., GeneratorContextManager[_T]]:\n    ...\n\ndef asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]]: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/dataclasses.pyi",
    "content": "from typing import Any, Callable, Generic, Literal, Mapping, Optional, TypeVar, overload, Type, \\\n    Protocol, ClassVar\nfrom typing_extensions import TypeGuard\n\n# DataclassInstance is in _typeshed.pyi normally, but alas we can't do the same for lib-stub\n# due to test-data/unit/lib-stub/builtins.pyi not having 'tuple'.\nclass DataclassInstance(Protocol):\n    __dataclass_fields__: ClassVar[dict[str, Field[Any]]]\n\n_T = TypeVar('_T')\n_DataclassT = TypeVar(\"_DataclassT\", bound=DataclassInstance)\n\nclass InitVar(Generic[_T]):\n    ...\n\nclass KW_ONLY: ...\n\n@overload\ndef dataclass(_cls: Type[_T]) -> Type[_T]: ...\n\n@overload\ndef dataclass(*, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ...,\n    unsafe_hash: bool = ..., frozen: bool = ..., match_args: bool = ...,\n    kw_only: bool = ..., slots: bool = ...) -> Callable[[Type[_T]], Type[_T]]: ...\n\n@overload\ndef field(*, default: _T,\n    init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ...,\n    metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...,) -> _T: ...\n\n@overload\ndef field(*, default_factory: Callable[[], _T],\n    init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ...,\n    metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...,) -> _T: ...\n\n@overload\ndef field(*,\n    init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ...,\n    metadata: Optional[Mapping[str, Any]] = ..., kw_only: bool = ...,) -> Any: ...\n\n\nclass Field(Generic[_T]): pass\n\n@overload\ndef is_dataclass(obj: DataclassInstance) -> Literal[True]: ...\n@overload\ndef is_dataclass(obj: type) -> TypeGuard[type[DataclassInstance]]: ...\n@overload\ndef is_dataclass(obj: object) -> TypeGuard[DataclassInstance | type[DataclassInstance]]: ...\n\n\ndef replace(__obj: _DataclassT, **changes: Any) -> _DataclassT: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/datetime.pyi",
    "content": "# Very simplified datetime stubs for use in tests\n\nclass date:\n    def __new__(\n        cls,\n        year: int,\n        month: int,\n        day: int,\n    ) -> date: ...\n    def __format__(self, __fmt: str) -> str: ...\n\n\nclass datetime(date):\n    def __new__(\n        cls,\n        year: int,\n        month: int,\n        day: int,\n        hour: int = ...,\n        minute: int = ...,\n        second: int = ...,\n        microsecond: int = ...,\n        *,\n        fold: int = ...,\n    ) -> datetime: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/decimal.pyi",
    "content": "# Very simplified decimal stubs for use in tests\n\nfrom _decimal import *\n"
  },
  {
    "path": "test-data/unit/lib-stub/enum.pyi",
    "content": "from typing import Any, TypeVar, Union, Type, Sized, Iterator\nfrom typing_extensions import Literal\n\n_T = TypeVar('_T')\n\nclass EnumMeta(type, Sized):\n    def __len__(self) -> int: pass  # to make it non-abstract\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    def __bool__(self) -> Literal[True]: 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\n    name: str\n    value: Any\n    _name_: str\n    _value_: Any\n\n    # In reality, _generate_next_value_ is python3.6 only and has a different signature.\n    # However, this should be quick and doesn't require additional stubs (e.g. `staticmethod`)\n    def _generate_next_value_(self) -> Any: pass\n\nclass IntEnum(int, Enum):\n    value: int\n    def __new__(cls: Type[_T], value: Union[int, _T]) -> _T: ...\n\ndef unique(enumeration: _T) -> _T: pass\n\n# In reality Flag and IntFlag are 3.6 only\n\nclass Flag(Enum):\n    def __or__(self: _T, other: Union[int, _T]) -> _T: pass\n\n\nclass IntFlag(int, Flag):\n    def __and__(self: _T, other: Union[int, _T]) -> _T: pass\n\n\nclass auto(IntFlag):\n    value: Any\n\n\n# It is python-3.11+ only:\nclass StrEnum(str, Enum):\n    def __new__(cls: Type[_T], value: str | _T) -> _T: ...\n\n# It is python-3.11+ only:\nclass nonmember(Generic[_T]):\n    value: _T\n    def __init__(self, value: _T) -> None: ...\n\n# It is python-3.11+ only:\nclass member(Generic[_T]):\n    value: _T\n    def __init__(self, value: _T) -> None: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/functools.pyi",
    "content": "from typing import Generic, TypeVar, Callable, Any, Mapping, Self, overload\n\n_T = TypeVar(\"_T\")\n\nclass _SingleDispatchCallable(Generic[_T]):\n    registry: Mapping[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: type[Any], func: 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 = ...) -> Callable[..., _T]: ...\n    # fun.register(int, lambda x: x)\n    @overload\n    def register(self, cls: type[Any], 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\ndef total_ordering(cls: type[_T]) -> type[_T]: ...\n\nclass cached_property(Generic[_T]):\n    func: Callable[[Any], _T]\n    attrname: str | None\n    def __init__(self, func: Callable[[Any], _T]) -> None: ...\n    @overload\n    def __get__(self, instance: None, owner: type[Any] | None = ...) -> cached_property[_T]: ...\n    @overload\n    def __get__(self, instance: object, owner: type[Any] | None = ...) -> _T: ...\n    def __set_name__(self, owner: type[Any], name: str) -> None: ...\n    def __class_getitem__(cls, item: Any) -> Any: ...\n\nclass partial(Generic[_T]):\n    def __new__(cls, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ...\n    def __call__(__self, *args: Any, **kwargs: Any) -> _T: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/future/__init__.pyi",
    "content": "from __future__ import absolute_import, print_function\n"
  },
  {
    "path": "test-data/unit/lib-stub/future/utils.pyi",
    "content": "from typing import Type\ndef with_metaclass(meta: Type[type], *bases: type) -> type: pass\n"
  },
  {
    "path": "test-data/unit/lib-stub/helper.pyi",
    "content": "from typing import TypeVar\n\nT = TypeVar(\"T\")\nT_out = TypeVar(\"T_out\", covariant=True)\nout_T = TypeVar(\"out_T\", covariant=True)\nT_in = TypeVar(\"T_in\", contravariant=True)\nin_T = TypeVar(\"in_T\", contravariant=True)\n"
  },
  {
    "path": "test-data/unit/lib-stub/math.pyi",
    "content": "pi: float\ne: float\ntau: float\ninf: float\nnan: float\ndef sqrt(__x: float) -> float: ...\ndef sin(__x: float) -> float: ...\ndef cos(__x: float) -> float: ...\ndef tan(__x: float) -> float: ...\ndef exp(__x: float) -> float: ...\ndef log(__x: float) -> float: ...\ndef floor(__x: float) -> int: ...\ndef ceil(__x: float) -> int: ...\ndef fabs(__x: float) -> float: ...\ndef pow(__x: float, __y: float) -> float: ...\ndef copysign(__x: float, __y: float) -> float: ...\ndef isinf(__x: float) -> bool: ...\ndef isnan(__x: float) -> bool: ...\ndef isfinite(__x: float) -> bool: ...\ndef nextafter(__x: float, __y: float) -> float: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/mypy_extensions.pyi",
    "content": "# NOTE: Requires fixtures/dict.pyi\nfrom typing import (\n    Any, Dict, Type, TypeVar, Optional, Any, Generic, Mapping, NoReturn as NoReturn, Iterator,\n    Union, Protocol\n)\n\n_T = TypeVar('_T')\n_U = TypeVar('_U')\n\n\ndef Arg(type: _T = ..., name: Optional[str] = ...) -> _T: ...\n\ndef DefaultArg(type: _T = ..., name: Optional[str] = ...) -> _T: ...\n\ndef NamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ...\n\ndef DefaultNamedArg(type: _T = ..., name: Optional[str] = ...) -> _T: ...\n\ndef VarArg(type: _T = ...) -> _T: ...\n\ndef KwArg(type: _T = ...) -> _T: ...\n\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\ndef TypedDict(typename: str, fields: Dict[str, Type[_T]], *, total: Any = ...) -> Type[dict]: ...\n\n# This is intended as a class decorator, but mypy rejects abstract classes\n# when a Type[_T] is expected, so we can't give it the type we want.\ndef trait(cls: Any) -> Any: ...\n\n# The real type is in the comment but it isn't safe to use **kwargs in\n# a lib-stub because the fixtures might not have dict. Argh!\n# def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ...\nmypyc_attr: Any\n\nclass FlexibleAlias(Generic[_T, _U]): ...\n\nclass __SupportsInt(Protocol[T_co]):\n    def __int__(self) -> int: pass\n\n_Int = Union[int, u8, i16, i32, i64]\n\nclass u8:\n    def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ...\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\nclass i16:\n    def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ...\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\nclass i32:\n    def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ...\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\nclass i64:\n    def __init__(self, x: Union[_Int, str, bytes, SupportsInt], base: int = 10) -> None: ...\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"
  },
  {
    "path": "test-data/unit/lib-stub/numbers.pyi",
    "content": "# Test fixture for numbers\n#\n# The numbers module isn't properly supported, but we want to test that mypy\n# can tell that it doesn't work as expected.\n\nclass Number: pass\nclass Complex: pass\nclass Real: pass\nclass Rational: pass\nclass Integral: pass\n"
  },
  {
    "path": "test-data/unit/lib-stub/six.pyi",
    "content": "from typing import Type, Callable\ndef with_metaclass(mcls: Type[type], *args: type) -> type: pass\ndef add_metaclass(mcls: Type[type]) -> Callable[[type], type]: pass\n"
  },
  {
    "path": "test-data/unit/lib-stub/sys.pyi",
    "content": "version_info = (0, 0, 0, '', 0)\nplatform = ''\n"
  },
  {
    "path": "test-data/unit/lib-stub/traceback.pyi",
    "content": "# Very simplified traceback stubs for use in tests\n\ndef print_tb(*args, **kwargs) -> None: ...\n"
  },
  {
    "path": "test-data/unit/lib-stub/types.pyi",
    "content": "from typing import Any, TypeVar\nimport sys\n\n_T = TypeVar('_T')\n\ndef coroutine(func: _T) -> _T: pass\n\nclass ModuleType:\n    __file__: str\n    def __getattr__(self, name: str) -> Any: pass\n\nclass GenericAlias:\n    def __or__(self, o): ...\n    def __ror__(self, o): ...\n\nif sys.version_info >= (3, 10):\n    class NoneType:\n        ...\n\n    class UnionType:\n        def __or__(self, x) -> UnionType: ...\n\nclass FunctionType:\n    def __call__(self): ...\n\nclass MethodType:\n    pass\n"
  },
  {
    "path": "test-data/unit/lib-stub/typing.pyi",
    "content": "# Stub for typing module. Many of the definitions have special handling in\n# the type checker, so they can just be initialized to anything.\n#\n# DO NOT ADD TO THIS FILE UNLESS YOU HAVE A GOOD REASON! Additional definitions\n# will slow down tests.\n#\n# Use [typing fixtures/typing-{medium,full,async,...}.pyi] in a test case for\n# a more complete stub for typing. If you need to add things, add to one of\n# the stubs under fixtures/.\n\ncast = 0\nassert_type = 0\noverload = 0\nAny = object()\nUnion = 0\nOptional = 0\nTypeVar = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\nNamedTuple = 0\nType = 0\nClassVar = 0\nFinal = 0\nNoReturn = 0\nNever = 0\nNewType = 0\nParamSpec = 0\nTypeVarTuple = 0\nUnpack = 0\nSelf = 0\nTYPE_CHECKING = 0\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nU = TypeVar('U')\nV = TypeVar('V')\n\n\nclass Callable:\n    def __call__(self): pass\nclass _NamedCallable(Callable):\n    __name__: str\n    __qualname__: str\nclass Iterable(Protocol[T_co]):\n    def __iter__(self) -> Iterator[T_co]: pass\n\nclass Iterator(Iterable[T_co], Protocol):\n    def __next__(self) -> T_co: pass\n\nclass Generator(Iterator[T], Generic[T, U, V]):\n    def __iter__(self) -> Generator[T, U, V]: pass\n\nclass Sequence(Iterable[T_co]):\n    def __getitem__(self, n: Any) -> T_co: pass\n    def __len__(self) -> int: pass\n\n# Mapping type is oversimplified intentionally.\nclass Mapping(Iterable[T], Generic[T, T_co]):\n    def keys(self) -> Iterable[T]: pass  # Approximate return type\n    def __getitem__(self, key: T) -> T_co: pass\n\nclass Awaitable(Protocol[T]):\n    def __await__(self) -> Generator[Any, Any, T]: pass\n\nclass Coroutine(Awaitable[V], Generic[T, U, V]): pass\n\ndef final(meth: T) -> T: pass\n\ndef reveal_type(__obj: T) -> T: pass\n\nclass _SpecialForm: pass\n"
  },
  {
    "path": "test-data/unit/lib-stub/typing_extensions.pyi",
    "content": "import typing\nfrom typing import Any, Callable, Mapping, Iterable, Iterator, NoReturn as NoReturn, Dict, Tuple, Type, Union\nfrom typing import TYPE_CHECKING as TYPE_CHECKING\nfrom typing import NewType as NewType, overload as overload\n\nimport sys\n\n_T = typing.TypeVar('_T')\n\nclass _SpecialForm:\n    def __getitem__(self, typeargs: Any) -> Any:\n        pass\n\n    def __call__(self, arg: Any) -> Any:\n        pass\n\nNamedTuple = 0\nProtocol: _SpecialForm = ...\ndef runtime_checkable(x: _T) -> _T: pass\nruntime = runtime_checkable\n\nFinal: _SpecialForm = ...\ndef final(x: _T) -> _T: pass\n\nLiteral: _SpecialForm = ...\n\nAnnotated: _SpecialForm = ...\n\nTypeVar: _SpecialForm\n\nParamSpec: _SpecialForm\nConcatenate: _SpecialForm\n\nTypeAlias: _SpecialForm\n\nTypeGuard: _SpecialForm\nTypeIs: _SpecialForm\nNever: _SpecialForm\n\nTypeVarTuple: _SpecialForm\nUnpack: _SpecialForm\nRequired: _SpecialForm\nNotRequired: _SpecialForm\nReadOnly: _SpecialForm\n\nSelf: _SpecialForm\n\n@final\nclass TypeAliasType:\n    def __init__(\n        self, name: str, value: Any, *, type_params: Tuple[Union[TypeVar, ParamSpec, TypeVarTuple], ...] = ()\n    ) -> None: ...\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 items(self) -> Iterable[Tuple[str, object]]: ...\n    def keys(self) -> Iterable[str]: ...\n    def values(self) -> Iterable[object]: ...\n    if sys.version_info < (3, 0):\n        def has_key(self, k: str) -> bool: ...\n    def __delitem__(self, k: NoReturn) -> None: ...\n    # Stubtest's tests need the following items:\n    __required_keys__: frozenset[str]\n    __optional_keys__: frozenset[str]\n    __readonly_keys__: frozenset[str]\n    __mutable_keys__: frozenset[str]\n    __closed__: bool\n    __extra_items__: Any\n    __total__: bool\n\ndef TypedDict(typename: str, fields: Dict[str, Type[_T]], *, total: Any = ...) -> Type[dict]: ...\n\ndef reveal_type(__obj: _T) -> _T: pass\ndef assert_type(__val: _T, __typ: Any) -> _T: pass\n\ndef dataclass_transform(\n    *,\n    eq_default: bool = ...,\n    order_default: bool = ...,\n    kw_only_default: bool = ...,\n    field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ...,\n    **kwargs: Any,\n) -> Callable[[_T], _T]: ...\n\ndef override(__arg: _T) -> _T: ...\ndef deprecated(__msg: str) -> Callable[[_T], _T]: ...\n\n_FutureFeatureFixture = 0\n"
  },
  {
    "path": "test-data/unit/lib-stub/unannotated_lib.pyi",
    "content": "def f(x): ...\n"
  },
  {
    "path": "test-data/unit/merge.test",
    "content": "-- Test cases for AST merge (used for fine-grained incremental checking)\n--\n-- Each test case has two versions of the module 'target' (target.py and\n-- target.py.next). A test cases type checks both of them, merges the ASTs,\n-- and finally dumps certain parts of the ASTs for both versions (==>\n-- separates the first and second versions). A test case passes if the\n-- dumped output is as expected.\n--\n-- The dumped output uses <N> to denote identities of objects. Objects\n-- suffixed by the same <N> refer to the same object; <N> and <M> (if\n-- N != M) refer to different objects. The objective of these test cases\n-- is to verify that identities of publicly visible AST nodes is\n-- preserved across merge. Other AST nodes may get new identities.\n--\n-- Each test case dumps one of four kinds of information:\n--\n-- 1) ASTs (test case has no magic suffix)\n-- 2) Symbol tables (_symtable test case name suffix)\n-- 3) TypeInfos (_typeinfo suffix)\n-- 4) Inferred types (_types suffix)\n--\n-- If you need to dump multiple different kinds of information, write\n-- multiple test cases.\n\n[case testFunction]\nimport target\n[file target.py]\ndef f() -> int:\n    pass\n[file target.py.next]\ndef f() -> int:\n    pass\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  FuncDef:1<2>(\n    f\n    def () -> builtins.int<3>\n    Block:2<4>(\n      PassStmt:2<5>())))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  FuncDef:1<2>(\n    f\n    def () -> builtins.int<3>\n    Block:2<6>(\n      PassStmt:2<7>())))\n\n[case testClass]\nimport target\n[file target.py]\nclass A:\n    def f(self, x: str) -> int:\n        pass\n[file target.py.next]\nclass A:\n    def f(self, x: int) -> str:\n        pass\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<2>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self)\n        Var(x))\n      def (self: target.A<4>, x: builtins.str<5>) -> builtins.int<6>\n      Block:3<7>(\n        PassStmt:3<8>()))))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<9>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self)\n        Var(x))\n      def (self: target.A<4>, x: builtins.int<6>) -> builtins.str<5>\n      Block:3<10>(\n        PassStmt:3<11>()))))\n\n[case testClass_typeinfo]\nimport target\n[file target.py]\nclass A:\n    def f(self, x: str) -> int: pass\n    def g(self, x: str) -> int: pass\n[file target.py.next]\nclass A:\n    def f(self, x: int) -> str: pass\n    def h(self, x: int) -> str: pass\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names(\n    f<2>\n    g<3>))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names(\n    f<2>\n    h<4>))\n\n[case testConstructInstance]\nimport target\n[file target.py]\nclass A:\n    def f(self) -> B:\n        return B()\nclass B: pass\n[file target.py.next]\nclass B: pass\nclass A:\n    def f(self) -> B:\n        1\n        return B()\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<2>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self))\n      def (self: target.A<4>) -> target.B<5>\n      Block:3<6>(\n        ReturnStmt:3<7>(\n          CallExpr:3<8>(\n            NameExpr(B [target.B<5>])\n            Args())))))\n  ClassDef:4<9>(\n    B\n    PassStmt:4<10>()))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<11>(\n    B\n    PassStmt:1<12>())\n  ClassDef:2<13>(\n    A\n    FuncDef:3<3>(\n      f\n      Args(\n        Var(self))\n      def (self: target.A<4>) -> target.B<5>\n      Block:4<14>(\n        ExpressionStmt:4<15>(\n          IntExpr(1))\n        ReturnStmt:5<16>(\n          CallExpr:5<17>(\n            NameExpr(B [target.B<5>])\n            Args()))))))\n\n[case testCallMethod]\nimport target\n[file target.py]\nclass A:\n    def f(self) -> None:\n        self.f()\n[file target.py.next]\nclass A:\n    def f(self) -> None:\n        self.f()\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<2>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self))\n      def (self: target.A<4>)\n      Block:3<5>(\n        ExpressionStmt:3<6>(\n          CallExpr:3<7>(\n            MemberExpr:3<8>(\n              NameExpr(self [l<9>])\n              f)\n            Args()))))))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<10>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self))\n      def (self: target.A<4>)\n      Block:3<11>(\n        ExpressionStmt:3<12>(\n          CallExpr:3<13>(\n            MemberExpr:3<14>(\n              NameExpr(self [l<15>])\n              f)\n            Args()))))))\n\n[case testClassAttribute]\nimport target\n[file target.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.x\n[file target.py.next]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.x\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<2>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self))\n      def (self: target.A<4>)\n      Block:3<5>(\n        AssignmentStmt:3<6>(\n          MemberExpr:3<8>(\n            NameExpr(self [l<9>])\n            x*<7>)\n          IntExpr(1))\n        ExpressionStmt:4<10>(\n          MemberExpr:4<11>(\n            NameExpr(self [l<9>])\n            x))))))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<12>(\n    A\n    FuncDef:2<3>(\n      f\n      Args(\n        Var(self))\n      def (self: target.A<4>)\n      Block:3<13>(\n        AssignmentStmt:3<14>(\n          MemberExpr:3<15>(\n            NameExpr(self [l<16>])\n            x*<7>)\n          IntExpr(1))\n        ExpressionStmt:4<17>(\n          MemberExpr:4<18>(\n            NameExpr(self [l<16>])\n            x))))))\n\n[case testClassAttribute_typeinfo]\nimport target\n[file target.py]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.x\n        self.y = A()\n[file target.py.next]\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.x\n        self.y = A()\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names(\n    f<2>\n    x<3> (builtins.int<4>)\n    y<5> (target.A<0>)))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names(\n    f<2>\n    x<3> (builtins.int<4>)\n    y<5> (target.A<0>)))\n\n[case testFunction_symtable]\nimport target\n[file target.py]\ndef f() -> int:\n    pass\n[file target.py.next]\ndef f() -> int:\n    pass\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    f: FuncDef<1>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    f: FuncDef<1>\n\n[case testClass_symtable]\nimport target\n[file target.py]\nclass A: pass\nclass B: pass\n[file target.py.next]\nclass A: pass\nclass C: pass\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    B: TypeInfo<2>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    C: TypeInfo<3>\n\n[case testTopLevelExpression]\nimport target\n[file target.py]\nclass A: pass\nA()\n[file target.py.next]\nclass A: pass\nclass B: pass\nA()\nB()\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<2>(\n    A\n    PassStmt:1<3>())\n  ExpressionStmt:2<4>(\n    CallExpr:2<5>(\n      NameExpr(A [target.A<6>])\n      Args())))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ClassDef:1<7>(\n    A\n    PassStmt:1<8>())\n  ClassDef:2<9>(\n    B\n    PassStmt:2<10>())\n  ExpressionStmt:3<11>(\n    CallExpr:3<12>(\n      NameExpr(A [target.A<6>])\n      Args()))\n  ExpressionStmt:4<13>(\n    CallExpr:4<14>(\n      NameExpr(B [target.B<15>])\n      Args())))\n\n[case testExpression_types]\nimport target\n[file target.py]\nclass A: pass\ndef f(a: A) -> None:\n    1\n    a\n[file target.py.next]\nclass A: pass\ndef f(a: A) -> None:\n    a\n    1\n[out]\n## target\nIntExpr:3: Literal[1]?<0>\nNameExpr:4: target.A<1>\n==>\n## target\nNameExpr:3: target.A<1>\nIntExpr:4: Literal[1]?<0>\n\n[case testClassAttribute_types]\nimport target\n[file target.py]\nclass A:\n    def f(self) -> None:\n        self.x = A()\n        self.x\n        self.y = 1\n        self.y\n[file target.py.next]\nclass A:\n    def f(self) -> None:\n        self.y = 1\n        self.y\n        self.x = A()\n        self.x\n[out]\n## target\nCallExpr:3: target.A<0>\nMemberExpr:3: target.A<0>\nNameExpr:3: def () -> target.A<0>\nNameExpr:3: target.A<0>\nMemberExpr:4: target.A<0>\nNameExpr:4: target.A<0>\nIntExpr:5: Literal[1]?<1>\nMemberExpr:5: builtins.int<1>\nNameExpr:5: target.A<0>\nMemberExpr:6: builtins.int<1>\nNameExpr:6: target.A<0>\n==>\n## target\nIntExpr:3: Literal[1]?<1>\nMemberExpr:3: builtins.int<1>\nNameExpr:3: target.A<0>\nMemberExpr:4: builtins.int<1>\nNameExpr:4: target.A<0>\nCallExpr:5: target.A<0>\nMemberExpr:5: target.A<0>\nNameExpr:5: def () -> target.A<0>\nNameExpr:5: target.A<0>\nMemberExpr:6: target.A<0>\nNameExpr:6: target.A<0>\n\n[case testMethod_types]\nimport target\n[file target.py]\nclass A:\n    def f(self) -> A:\n        return self.f()\n[file target.py.next]\nclass A:\n    # Extra line to change line numbers\n    def f(self) -> A:\n        return self.f()\n[out]\n## target\nCallExpr:3: target.A<0>\nMemberExpr:3: def () -> target.A<0>\nNameExpr:3: target.A<0>\n==>\n## target\nCallExpr:4: target.A<0>\nMemberExpr:4: def () -> target.A<0>\nNameExpr:4: target.A<0>\n\n[case testRenameFunction]\nimport target\n[file target.py]\ndef f() -> int: pass\n[file target.py.next]\ndef g() -> int: pass\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  FuncDef:1<2>(\n    f\n    def () -> builtins.int<3>\n    Block:1<4>(\n      PassStmt:1<5>())))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  FuncDef:1<6>(\n    g\n    def () -> builtins.int<3>\n    Block:1<7>(\n      PassStmt:1<8>())))\n\n[case testRenameFunction_symtable]\nimport target\n[file target.py]\ndef f() -> int: pass\n[file target.py.next]\ndef g() -> int: pass\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    f: FuncDef<1>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    g: FuncDef<2>\n\n[case testMergeWithBaseClass_typeinfo]\nimport target\n[file target.py]\nclass A: pass\nclass B(A):\n    def f(self) -> None: pass\n[file target.py.next]\nclass C: pass\nclass A: pass\nclass B(A):\n    def f(self) -> None: pass\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names())\nTypeInfo<2>(\n  Name(target.B)\n  Bases(target.A<0>)\n  Mro(target.B<2>, target.A<0>, builtins.object<1>)\n  Names(\n    f<3>))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names())\nTypeInfo<2>(\n  Name(target.B)\n  Bases(target.A<0>)\n  Mro(target.B<2>, target.A<0>, builtins.object<1>)\n  Names(\n    f<3>))\nTypeInfo<4>(\n  Name(target.C)\n  Bases(builtins.object<1>)\n  Mro(target.C<4>, builtins.object<1>)\n  Names())\n\n[case testModuleAttribute]\nimport target\n[file target.py]\nx = 1\n[file target.py.next]\nx = 2\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  AssignmentStmt:1<2>(\n    NameExpr(x [target.x<3>])\n    IntExpr(1)\n    builtins.int<4>))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  AssignmentStmt:1<5>(\n    NameExpr(x [target.x<3>])\n    IntExpr(2)\n    builtins.int<4>))\n\n[case testNestedClassMethod_typeinfo]\nimport target\n[file target.py]\nclass A:\n    class B:\n        def f(self) -> None: pass\n[file target.py.next]\nclass A:\n    class B:\n        def f(self) -> None: pass\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names(\n    B<2>))\nTypeInfo<2>(\n  Name(target.A.B)\n  Bases(builtins.object<1>)\n  Mro(target.A.B<2>, builtins.object<1>)\n  Names(\n    f<3>))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names(\n    B<2>))\nTypeInfo<2>(\n  Name(target.A.B)\n  Bases(builtins.object<1>)\n  Mro(target.A.B<2>, builtins.object<1>)\n  Names(\n    f<3>))\n\n[case testNamedTuple_typeinfo]\n# flags: --python-version 3.10\nimport target\n[file target.py]\nfrom typing import NamedTuple\nclass A: pass\nN = NamedTuple('N', [('x', A)])\n[file target.py.next]\nfrom typing import NamedTuple\nclass A: pass\nN = NamedTuple('N', [('x', A), ('y', A)])\n[builtins fixtures/tuple.pyi]\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names())\nTypeInfo<2>(\n  Name(target.N)\n  Bases(builtins.tuple[target.A<0>, ...]<3>)\n  Mro(target.N<2>, builtins.tuple<3>, typing.Sequence<4>, typing.Iterable<5>, builtins.object<1>)\n  Names(\n    _NT<6>\n    __annotations__<7> (builtins.dict[builtins.str<8>, Any]<9>)\n    __doc__<10> (builtins.str<8>)\n    __match_args__<11> (Tuple[Literal['x']])\n    __new__<12>\n    _asdict<13>\n    _field_defaults<14> (builtins.dict[builtins.str<8>, Any]<9>)\n    _field_types<15> (builtins.dict[builtins.str<8>, Any]<9>)\n    _fields<16> (Tuple[builtins.str<8>])\n    _make<17>\n    _replace<18>\n    _source<19> (builtins.str<8>)\n    x<20> (target.A<0>)))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names())\nTypeInfo<2>(\n  Name(target.N)\n  Bases(builtins.tuple[target.A<0>, ...]<3>)\n  Mro(target.N<2>, builtins.tuple<3>, typing.Sequence<4>, typing.Iterable<5>, builtins.object<1>)\n  Names(\n    _NT<6>\n    __annotations__<7> (builtins.dict[builtins.str<8>, Any]<9>)\n    __doc__<10> (builtins.str<8>)\n    __match_args__<11> (Tuple[Literal['x'], Literal['y']])\n    __new__<12>\n    _asdict<13>\n    _field_defaults<14> (builtins.dict[builtins.str<8>, Any]<9>)\n    _field_types<15> (builtins.dict[builtins.str<8>, Any]<9>)\n    _fields<16> (Tuple[builtins.str<8>, builtins.str<8>])\n    _make<17>\n    _replace<18>\n    _source<19> (builtins.str<8>)\n    x<20> (target.A<0>)\n    y<21> (target.A<0>)))\n\n[case testNamedTupleOldVersion_typeinfo]\nimport target\n[file target.py]\nfrom typing import NamedTuple\nclass A: pass\nN = NamedTuple('N', [('x', A)])\n[file target.py.next]\nfrom typing import NamedTuple\nclass A: pass\nN = NamedTuple('N', [('x', A), ('y', A)])\n[builtins fixtures/tuple.pyi]\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names())\nTypeInfo<2>(\n  Name(target.N)\n  Bases(builtins.tuple[target.A<0>, ...]<3>)\n  Mro(target.N<2>, builtins.tuple<3>, typing.Sequence<4>, typing.Iterable<5>, builtins.object<1>)\n  Names(\n    _NT<6>\n    __annotations__<7> (builtins.dict[builtins.str<8>, Any]<9>)\n    __doc__<10> (builtins.str<8>)\n    __new__<11>\n    _asdict<12>\n    _field_defaults<13> (builtins.dict[builtins.str<8>, Any]<9>)\n    _field_types<14> (builtins.dict[builtins.str<8>, Any]<9>)\n    _fields<15> (Tuple[builtins.str<8>])\n    _make<16>\n    _replace<17>\n    _source<18> (builtins.str<8>)\n    x<19> (target.A<0>)))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(builtins.object<1>)\n  Mro(target.A<0>, builtins.object<1>)\n  Names())\nTypeInfo<2>(\n  Name(target.N)\n  Bases(builtins.tuple[target.A<0>, ...]<3>)\n  Mro(target.N<2>, builtins.tuple<3>, typing.Sequence<4>, typing.Iterable<5>, builtins.object<1>)\n  Names(\n    _NT<6>\n    __annotations__<7> (builtins.dict[builtins.str<8>, Any]<9>)\n    __doc__<10> (builtins.str<8>)\n    __new__<11>\n    _asdict<12>\n    _field_defaults<13> (builtins.dict[builtins.str<8>, Any]<9>)\n    _field_types<14> (builtins.dict[builtins.str<8>, Any]<9>)\n    _fields<15> (Tuple[builtins.str<8>, builtins.str<8>])\n    _make<16>\n    _replace<17>\n    _source<18> (builtins.str<8>)\n    x<19> (target.A<0>)\n    y<20> (target.A<0>)))\n\n[case testUnionType_types]\nimport target\n[file target.py]\nfrom typing import Union\nclass A: pass\na: A\n[file target.py.next]\nfrom typing import Union\nclass A: pass\na: Union[A, int]\n[out]\n## target\nNameExpr:3: target.A<0>\n==>\n## target\nNameExpr:3: Union[target.A<0>, builtins.int<1>]\n\n[case testTypeType_types]\nimport target\n[file target.py]\nfrom typing import Type\nclass A: pass\na: Type[A]\n[file target.py.next]\nfrom typing import Type\nclass A: pass\na: Type[A]\n[out]\n## target\nNameExpr:3: Type[target.A<0>]\n==>\n## target\nNameExpr:3: Type[target.A<0>]\n\n[case testTypeVar_types]\nimport target\n[file target.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', bound=int)\nclass A(Generic[T]):\n    x: T\n[file target.py.next]\nfrom typing import TypeVar\nT = TypeVar('T', bound='A')\nclass A(Generic[T]):\n    x: T\n[out]\n## target\nCallExpr:2: Any\nNameExpr:2: Any\nTypeVarExpr:2: Any\nNameExpr:4: T`1(upper_bound=builtins.int<0>)\n==>\n## target\nCallExpr:2: Any\nNameExpr:2: Any\nTypeVarExpr:2: Any\nNameExpr:4: T`1(upper_bound=target.A[Any]<1>)\n\n[case testUnboundType_types]\n\nimport target\n[file target.py]\nfrom typing import TypeVar, Generic\nclass A: pass\nfoo: int\nx: foo[A]\n[file target.py.next]\nfrom typing import TypeVar, Generic\nclass A: pass\nfoo: int\nx: foo[A]\n[out]\ntmp/target.py:4: error: Variable \"target.foo\" is not valid as a type\ntmp/target.py:4: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n## target\nNameExpr:3: builtins.int<0>\nNameExpr:4: foo?[target.A<1>]\n==>\n## target\nNameExpr:3: builtins.int<0>\nNameExpr:4: foo?[target.A<1>]\n\n[case testOverloaded_types]\nimport target\n[file target.py]\nfrom typing import overload\nclass A: pass\n\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: int) -> int: pass\n\ndef f(x): pass\n\ng = f\n[file target.py.next]\nfrom typing import overload\n\nclass A: pass\n\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: str) -> str: pass\n\ndef f(x): pass\n\ng = f\n[out]\n-- TODO: It is unclear why this works correctly...\n## target\nNameExpr:11: Overload(def (x: target.A<0>) -> target.A<0>, def (x: builtins.int<1>) -> builtins.int<1>)\nNameExpr:11: Overload(def (x: target.A<0>) -> target.A<0>, def (x: builtins.int<1>) -> builtins.int<1>)\n==>\n## target\nNameExpr:12: Overload(def (x: target.A<0>) -> target.A<0>, def (x: builtins.str<2>) -> builtins.str<2>)\nNameExpr:12: Overload(def (x: target.A<0>) -> target.A<0>, def (x: builtins.str<2>) -> builtins.str<2>)\n\n[case testOverloaded]\nimport target\n[file target.py]\nfrom typing import overload\nclass A: pass\n\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: int) -> int: pass\n\ndef f(x): pass\n[file target.py.next]\nfrom typing import overload\n\nclass A: pass\nclass B: pass\n\n@overload\ndef f(x: A) -> B: pass\n@overload\ndef f(x: str) -> str: pass\n\ndef f(x): pass\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ImportFrom:1(typing, [overload])\n  ClassDef:2<2>(\n    A\n    PassStmt:2<3>())\n  OverloadedFuncDef:4<4>(\n    FuncDef:9<5>(\n      f\n      Args(\n        Var(x))\n      Block:9<6>(\n        PassStmt:9<7>()))\n    Overload(def (x: target.A<8>) -> target.A<8>, def (x: builtins.int<9>) -> builtins.int<9>)\n    Decorator:4<10>(\n      Var(f)\n      NameExpr(overload [typing.overload<11>])\n      FuncDef:5<12>(\n        f\n        Args(\n          Var(x))\n        def (x: target.A<8>) -> target.A<8>\n        Block:5<13>(\n          PassStmt:5<14>())))\n    Decorator:6<15>(\n      Var(f)\n      NameExpr(overload [typing.overload<11>])\n      FuncDef:7<16>(\n        f\n        Args(\n          Var(x))\n        def (x: builtins.int<9>) -> builtins.int<9>\n        Block:7<17>(\n          PassStmt:7<18>())))))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ImportFrom:1(typing, [overload])\n  ClassDef:3<19>(\n    A\n    PassStmt:3<20>())\n  ClassDef:4<21>(\n    B\n    PassStmt:4<22>())\n  OverloadedFuncDef:6<4>(\n    FuncDef:11<23>(\n      f\n      Args(\n        Var(x))\n      Block:11<24>(\n        PassStmt:11<25>()))\n    Overload(def (x: target.A<8>) -> target.B<26>, def (x: builtins.str<27>) -> builtins.str<27>)\n    Decorator:6<28>(\n      Var(f)\n      NameExpr(overload [typing.overload<11>])\n      FuncDef:7<29>(\n        f\n        Args(\n          Var(x))\n        def (x: target.A<8>) -> target.B<26>\n        Block:7<30>(\n          PassStmt:7<31>())))\n    Decorator:8<32>(\n      Var(f)\n      NameExpr(overload [typing.overload<11>])\n      FuncDef:9<33>(\n        f\n        Args(\n          Var(x))\n        def (x: builtins.str<27>) -> builtins.str<27>\n        Block:9<34>(\n          PassStmt:9<35>())))))\n\n[case testTypeVar_symtable]\nimport target\n\n[file target.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n\n[file target.py.next]\nfrom typing import TypeVar\nT = TypeVar('T', bound=int)\n\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    T: TypeVarExpr<1>\n    TypeVar: Var<2>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    T: TypeVarExpr<1>\n    TypeVar: Var<2>\n\n[case testTypeAlias_symtable]\nimport target\n\n[file target.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): pass\nX = A[int]\n\n[file target.py.next]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): pass\nX = A[str]\n\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    Generic: Var<2>\n    T: TypeVarExpr<3>\n    TypeVar: Var<4>\n    X: TypeAlias<5>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    Generic: Var<2>\n    T: TypeVarExpr<3>\n    TypeVar: Var<4>\n    X: TypeAlias<5>\n\n[case testGenericFunction_types]\nimport target\n\n[file target.py]\nfrom typing import TypeVar\nclass A: pass\nT = TypeVar('T', bound=A)\ndef f(x: T) -> T: pass\nf\n\n[file target.py.next]\nfrom typing import TypeVar\nclass A: pass\nT = TypeVar('T', bound=A)\ndef f(x: T, y: A) -> T: pass\nf\n\n[out]\n## target\nCallExpr:3: Any\nNameExpr:3: Any\nTypeVarExpr:3: Any\nNameExpr:5: def [T <: target.A<0>] (x: T`-1(upper_bound=target.A<0>)) -> T`-1(upper_bound=target.A<0>)\n==>\n## target\nCallExpr:3: Any\nNameExpr:3: Any\nTypeVarExpr:3: Any\nNameExpr:5: def [T <: target.A<0>] (x: T`-1(upper_bound=target.A<0>), y: target.A<0>) -> T`-1(upper_bound=target.A<0>)\n\n[case testMergeOverloaded_types]\nimport target\n[file target.py]\nfrom _x import A\na: A\n[file target.py.next]\nfrom _x import A\na: A\n[fixture _x.pyi]\nfrom typing import Generic, TypeVar, overload\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: int) -> None: pass\nA = C[int]\n[out]\n## target\nNameExpr:2: _x.C[builtins.int<0>]<1>\n==>\n## target\nNameExpr:2: _x.C[builtins.int<0>]<1>\n\n[case testRefreshVar_symtable]\nfrom typing import TypeVar\nfrom target import f\nx = 1\ny = '' # type: str\n[file target.py]\nf = 1\n[file target.py.next]\n[out]\n__main__:\n    TypeVar: Var<0>\n    f: Var<1>(builtins.int<2>)\n    x: Var<3>(builtins.int<2>)\n    y: Var<4>(builtins.str<5>)\ntarget:\n    f: Var<1>(builtins.int<2>)\n==>\n__main__:\n    TypeVar: Var<0>\n    f: Var<6>(Any)\n    x: Var<3>(builtins.int<2>)\n    y: Var<4>(builtins.str<5>)\ntarget:\n\n[case testRefreshTypeVar_symtable]\nfrom typing import TypeVar\nfrom target import f\nT = TypeVar('T')\n[file target.py]\nf = 1\n[file target.py.next]\n[out]\n__main__:\n    T: TypeVarExpr<0>\n    TypeVar: Var<1>\n    f: Var<2>(builtins.int<3>)\ntarget:\n    f: Var<2>(builtins.int<3>)\n==>\n__main__:\n    T: TypeVarExpr<0>\n    TypeVar: Var<1>\n    f: Var<4>(Any)\ntarget:\n\n[case testRefreshNamedTuple_symtable]\nfrom typing import NamedTuple\nfrom target import f\nN = NamedTuple('N', [('x', int)])\n[file target.py]\nf = 1\n[file target.py.next]\n[builtins fixtures/tuple.pyi]\n[out]\n__main__:\n    N: TypeInfo<0>\n    NamedTuple: Var<1>\n    f: Var<2>(builtins.int<3>)\ntarget:\n    f: Var<2>(builtins.int<3>)\n==>\n__main__:\n    N: TypeInfo<0>\n    NamedTuple: Var<1>\n    f: Var<4>(Any)\ntarget:\n\n[case testRefreshAttributeDefinedInClassBody_typeinfo]\nfrom target import f\nclass A:\n    a = 1\n    b = '' # type: str\n[file target.py]\nf = 1\n[file target.py.next]\n[out]\nTypeInfo<0>(\n  Name(__main__.A)\n  Bases(builtins.object<1>)\n  Mro(__main__.A<0>, builtins.object<1>)\n  Names(\n    a<2> (builtins.int<3>)\n    b<4> (builtins.str<5>)))\n==>\nTypeInfo<0>(\n  Name(__main__.A)\n  Bases(builtins.object<1>)\n  Mro(__main__.A<0>, builtins.object<1>)\n  Names(\n    a<2> (builtins.int<3>)\n    b<4> (builtins.str<5>)))\n\n[case testDecorator_symtable]\nimport target\n[file target.py]\nfrom contextlib import contextmanager\nfrom typing import Iterator, List, Tuple\n\n@contextmanager\ndef f(x: List[Tuple[int]]) -> Iterator[None]:\n    yield\n[file target.py.next]\nfrom contextlib import contextmanager\nfrom typing import Iterator, List, Tuple\n\n@contextmanager\ndef f(x: List[Tuple[int]]) -> Iterator[None]:\n    yield\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    Iterator: TypeInfo<1>\n    List: TypeAlias<2>\n    Tuple: Var<3>\n    contextmanager: FuncDef<4>\n    f: Decorator<5>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    Iterator: TypeInfo<1>\n    List: TypeAlias<2>\n    Tuple: Var<3>\n    contextmanager: FuncDef<4>\n    f: Decorator<5>\n\n[case testConditionalFunctionDefinition]\nimport target\n[file target.py]\nimport sys\nclass A: pass\nclass B: pass\nif sys.platform == 'nonexistent':\n    def f(x: A) -> None: pass\nelse:\n    def f(x: B) -> None: pass\n[file target.py.next]\nimport sys\nclass A: pass\nclass B: pass\nif sys.platform == 'nonexistent':\n    def f(x: A, y: int) -> None: pass\nelse:\n    def f(x: B, y: int) -> None: pass\n[builtins fixtures/ops.pyi]\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  Import:1(sys)\n  ClassDef:2<2>(\n    A\n    PassStmt:2<3>())\n  ClassDef:3<4>(\n    B\n    PassStmt:3<5>())\n  IfStmt:4<6>(\n    If(\n      ComparisonExpr:4<7>(\n        ==\n        MemberExpr:4<9>(\n          NameExpr(sys<10>)\n          platform [sys.platform<8>])\n        StrExpr(nonexistent)))\n    Then(\n      FuncDef:5<11>(\n        f\n        Args(\n          Var(x))\n        def (x: A?) -> None?\n        Block:5<12>(\n          PassStmt:5<13>())))\n    Else(\n      FuncDef:7<14>(\n        f\n        Args(\n          Var(x))\n        def (x: target.B<15>)\n        Block:7<16>(\n          PassStmt:7<17>())))))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  Import:1(sys)\n  ClassDef:2<18>(\n    A\n    PassStmt:2<19>())\n  ClassDef:3<20>(\n    B\n    PassStmt:3<21>())\n  IfStmt:4<22>(\n    If(\n      ComparisonExpr:4<23>(\n        ==\n        MemberExpr:4<24>(\n          NameExpr(sys<10>)\n          platform [sys.platform<8>])\n        StrExpr(nonexistent)))\n    Then(\n      FuncDef:5<25>(\n        f\n        Args(\n          Var(x)\n          Var(y))\n        def (x: A?, y: int?) -> None?\n        Block:5<26>(\n          PassStmt:5<27>())))\n    Else(\n      FuncDef:7<14>(\n        f\n        Args(\n          Var(x)\n          Var(y))\n        def (x: target.B<15>, y: builtins.int<28>)\n        Block:7<29>(\n          PassStmt:7<30>())))))\n\n[case testMergeTypedDict_symtable]\nimport target\n[file target.py]\nfrom mypy_extensions import TypedDict\nclass A: pass\nD = TypedDict('D', {'a': A})\nd: D\n[file target.py.next]\nfrom mypy_extensions import TypedDict\nclass A: pass\nD = TypedDict('D', {'a': A, 'b': int})\nd: D\n[builtins fixtures/dict.pyi]\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    D: TypeInfo<2>\n    TypedDict: FuncDef<3>\n    d: Var<4>(TypedDict('target.D', {'a': target.A<1>}))\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    D: TypeInfo<2>\n    TypedDict: FuncDef<3>\n    d: Var<4>(TypedDict('target.D', {'a': target.A<1>, 'b': builtins.int<5>}))\n\n[case testNewType_symtable]\nimport target\n[file target.py]\nfrom typing import NewType\nclass A: pass\nB = NewType('B', A)\nC = NewType('C', A)\n[file target.py.next]\nfrom typing import NewType\nclass A: pass\nB = NewType('B', A)\nC = NewType('C', B)\nD = NewType('D', int)\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    B: TypeInfo<2>\n    C: TypeInfo<3>\n    NewType: Var<4>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    A: TypeInfo<1>\n    B: TypeInfo<2>\n    C: TypeInfo<3>\n    D: TypeInfo<5>\n    NewType: Var<4>\n\n[case testCallable_symtable-skip]\n# The TypeInfo is currently not being merged correctly\nimport target\n[file target.py]\ndef g(o: object) -> None:\n    if callable(o):\n        pass\n[file target.py.next]\ndef g(o: object) -> None:\n    if callable(o):\n        o()\n[builtins fixtures/callable.pyi]\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    <callable subtype of object>: TypeInfo<1>\n    g: FuncDef<2>\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    <callable subtype of object>: TypeInfo<1>\n    g: FuncDef<2>\n\n[case testMetaclass_typeinfo]\nimport target\n[file target.py]\nclass M(type): pass\nclass C(metaclass=M):\n    pass\n[file target.py.next]\nclass M(type): pass\nclass C(metaclass=M):\n    pass # dummy change\n[out]\nTypeInfo<0>(\n  Name(target.C)\n  Bases(builtins.object<1>)\n  Mro(target.C<0>, builtins.object<1>)\n  Names()\n  DeclaredMetaclass(target.M<2>)\n  MetaclassType(target.M<2>))\nTypeInfo<2>(\n  Name(target.M)\n  Bases(builtins.type<3>)\n  Mro(target.M<2>, builtins.type<3>, builtins.object<1>)\n  Names())\n==>\nTypeInfo<0>(\n  Name(target.C)\n  Bases(builtins.object<1>)\n  Mro(target.C<0>, builtins.object<1>)\n  Names()\n  DeclaredMetaclass(target.M<2>)\n  MetaclassType(target.M<2>))\nTypeInfo<2>(\n  Name(target.M)\n  Bases(builtins.type<3>)\n  Mro(target.M<2>, builtins.type<3>, builtins.object<1>)\n  Names())\n\n[case testCast_symtable]\nimport target\n[file target.py]\nfrom typing import cast\nclass Thing:\n    pass\nthing = cast(Thing, Thing())\n[file target.py.next]\nfrom typing import cast\nclass Thing:\n    pass\nthing = cast(Thing, Thing())\n[out]\n__main__:\n    target: MypyFile<0>\ntarget:\n    Thing: TypeInfo<1>\n    cast: Var<2>\n    thing: Var<3>(target.Thing<1>)\n==>\n__main__:\n    target: MypyFile<0>\ntarget:\n    Thing: TypeInfo<1>\n    cast: Var<2>\n    thing: Var<3>(target.Thing<1>)\n\n[case testClassBasedEnum_typeinfo]\nimport target\n[file target.py]\nfrom enum import Enum\nclass A(Enum):\n    X = 0\n[file target.py.next]\nfrom enum import Enum\nclass A(Enum):\n    X = 0\n    Y = 1\n[builtins fixtures/enum.pyi]\n[out]\nTypeInfo<0>(\n  Name(target.A)\n  Bases(enum.Enum<1>)\n  Mro(target.A<0>, enum.Enum<1>, builtins.object<2>)\n  Names(\n    X<3> (Literal[0]?<4>))\n  MetaclassType(enum.EnumMeta<5>))\n==>\nTypeInfo<0>(\n  Name(target.A)\n  Bases(enum.Enum<1>)\n  Mro(target.A<0>, enum.Enum<1>, builtins.object<2>)\n  Names(\n    X<3> (Literal[0]?<4>)\n    Y<6> (Literal[1]?<4>))\n  MetaclassType(enum.EnumMeta<5>))\n\n[case testLiteralMerge]\nimport target\n[file target.py]\nfrom typing_extensions import Literal\ndef foo(x: Literal[3]) -> Literal['a']: pass\nbar: Literal[4] = 4\n[file target.py.next]\nfrom typing_extensions import Literal\ndef foo(x: Literal['3']) -> Literal['b']: pass\nbar: Literal[5] = 5\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ImportFrom:1(typing_extensions, [Literal])\n  FuncDef:2<2>(\n    foo\n    Args(\n      Var(x))\n    def (x: Literal[3]) -> Literal['a']\n    Block:2<3>(\n      PassStmt:2<4>()))\n  AssignmentStmt:3<5>(\n    NameExpr(bar [target.bar<6>])\n    IntExpr(4)\n    Literal[4]))\n==>\nMypyFile:1<0>(\n  tmp/main\n  Import:1(target))\nMypyFile:1<1>(\n  tmp/target.py\n  ImportFrom:1(typing_extensions, [Literal])\n  FuncDef:2<2>(\n    foo\n    Args(\n      Var(x))\n    def (x: Literal['3']) -> Literal['b']\n    Block:2<7>(\n      PassStmt:2<8>()))\n  AssignmentStmt:3<9>(\n    NameExpr(bar [target.bar<6>])\n    IntExpr(5)\n    Literal[5]))\n"
  },
  {
    "path": "test-data/unit/outputjson.test",
    "content": "-- Test cases for `--output=json`.\n-- These cannot be run by the usual unit test runner because of the backslashes\n-- in the output, which get normalized to forward slashes by the test suite on\n-- Windows.\n\n[case testOutputJsonNoIssues]\n# flags: --output=json\ndef foo() -> None:\n    pass\n\nfoo()\n[out]\n\n[case testOutputJsonSimple]\n# flags: --output=json\ndef foo() -> None:\n    pass\n\nfoo(1)\n[out]\n{\"file\": \"main\", \"line\": 5, \"column\": 0, \"message\": \"Too many arguments for \\\"foo\\\"\", \"hint\": null, \"code\": \"call-arg\", \"severity\": \"error\"}\n\n[case testOutputJsonWithHint]\n# flags: --output=json\nfrom typing import Optional, overload\n\n@overload\ndef foo() -> None: ...\n@overload\ndef foo(x: int) -> None: ...\n\ndef foo(x: Optional[int] = None) -> None:\n    ...\n\nreveal_type(foo)\n\nfoo('42')\n\ndef bar() -> None: ...\nbar('42')\n[out]\n{\"file\": \"main\", \"line\": 12, \"column\": 12, \"message\": \"Revealed type is \\\"Overload(def (), def (x: builtins.int))\\\"\", \"hint\": null, \"code\": \"reveal\", \"severity\": \"note\"}\n{\"file\": \"main\", \"line\": 14, \"column\": 0, \"message\": \"No overload variant of \\\"foo\\\" matches argument type \\\"str\\\"\", \"hint\": \"Possible overload variants:\\n    def foo() -> None\\n    def foo(x: int) -> None\", \"code\": \"call-overload\", \"severity\": \"error\"}\n{\"file\": \"main\", \"line\": 17, \"column\": 0, \"message\": \"Too many arguments for \\\"bar\\\"\", \"hint\": null, \"code\": \"call-arg\", \"severity\": \"error\"}\n"
  },
  {
    "path": "test-data/unit/parse-errors.test",
    "content": "-- Test cases for parser errors. Each test case consists of two sections.\n-- The first section contains [case NAME] followed by the input code, while\n-- the second section contains [out] followed by the output from the parser.\n--\n-- The input file name in errors is \"file\".\n--\n-- Comments starting with \"--\" in this file will be ignored, except for lines\n-- starting with \"----\" that are not ignored. The first two dashes of these\n-- lines are interpreted as escapes and removed.\n\n[case testInvalidFunction]\ndef f()\n  pass\n[out]\nfile:1: error: invalid syntax\n\n[case testUnexpectedIndent]\n1\n 2\n[out]\nfile:2: error: unexpected indent\n\n[case testInconsistentIndent]\nif x:\n  1\n   1\n[out]\nfile:3: error: unexpected indent\n\n[case testInconsistentIndent2]\nif x:\n   1\n  1\n[out]\nfile:3: error: unindent does not match any outer indentation level\n\n[case testInvalidBinaryOp]\n1>\na*\na+1*\n[out]\nfile:1: error: invalid syntax\n\n[case testDoubleStar]\n**a\n[out]\nfile:1: error: invalid syntax\n\n[case testMissingSuperClass]\nclass A(:\n  pass\n[out]\nfile:1: error: invalid syntax\n\n[case testUnexpectedEof]\nif 1:\n[out]\nfile:1: error: expected an indented block\n\n[case testInvalidKeywordArguments1]\nf(x=y, z)\n[out]\nfile:1: error: positional argument follows keyword argument\n\n[case testInvalidKeywordArguments2]\nf(**x, y)\n[out]\nfile:1: error: positional argument follows keyword argument unpacking\n\n[case testInvalidBareAsteriskAndVarArgs2]\ndef f(*x: A, *) -> None: pass\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidBareAsteriskAndVarArgs3]\ndef f(*, *x: A) -> None: pass\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidBareAsteriskAndVarArgs4]\ndef f(*, **x: A) -> None: pass\n[out]\nfile:1: error: named arguments must follow bare *\n\n[case testInvalidBareAsterisk1]\ndef f(*) -> None: pass\n[out]\nfile:1: error: named arguments must follow bare *\n\n[case testInvalidBareAsterisk2]\ndef f(x, *) -> None: pass\n[out]\nfile:1: error: named arguments must follow bare *\n\n[case testInvalidFuncDefArgs1]\ndef f(x = y, x): pass\n[out]\nfile:1: error: non-default argument follows default argument\n\n[case testInvalidFuncDefArgs3]\ndef f(**x, y):\n   pass\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidFuncDefArgs4]\ndef f(**x, y=x):\n    pass\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidTypeComment]\n0\nx = 0 # type: A A\n[out]\nfile:2: error: Syntax error in type comment \"A A\"\n\n[case testInvalidTypeComment2]\n0\nx = 0 # type: A[\n[out]\nfile:2: error: Syntax error in type comment \"A[\"\n\n[case testInvalidTypeComment3]\n0\nx = 0 # type:\n[out]\nfile:2: error: Syntax error in type comment \"\"\n\n[case testInvalidTypeComment4]\n0\nx = 0 # type: *\n[out]\nfile:2: error: Syntax error in type comment \"*\"\n\n[case testInvalidTypeComment5]\n0\nx = 0 # type:# some comment\n[out]\nfile:2: error: Syntax error in type comment \"\"\n\n[case testInvalidTypeComment6]\n0\nx = 0 # type: *# comment #6\n[out]\nfile:2: error: Syntax error in type comment \"*\"\n\n[case testInvalidTypeComment7]\n0\nx = 0 # type: A B #comment #7\n[out]\nfile:2: error: Syntax error in type comment \"A B\"\n\n[case testMissingBracket]\ndef foo(\n[out]\nfile:1: error: unexpected EOF while parsing\n[out version>=3.10]\nfile:1: error: '(' was never closed\n\n[case testInvalidSignatureInComment1]\ndef f(): # type: x\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"x\"\nfile:1: note: Suggestion: wrap argument types in parentheses\n\n[case testInvalidSignatureInComment2]\ndef f(): # type:\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"\"\n\n[case testInvalidSignatureInComment3]\ndef f(): # type: (\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(\"\n\n[case testInvalidSignatureInComment4]\ndef f(): # type: (.\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(.\"\n\n[case testInvalidSignatureInComment5]\ndef f(): # type: (x\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x\"\n\n[case testInvalidSignatureInComment6]\ndef f(): # type: (x)\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x)\"\n\n[case testInvalidSignatureInComment7]\ndef f(): # type: (x) -\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x) -\"\n\n[case testInvalidSignatureInComment8]\ndef f(): # type: (x) ->\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x) ->\"\n\n[case testInvalidSignatureInComment9]\ndef f(): # type: (x) -> .\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x) -> .\"\n\n[case testInvalidSignatureInComment10]\ndef f(): # type: (x) -> x x\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x) -> x x\"\n\n[case testInvalidSignatureInComment11]\ndef f(): # type: # abc comment\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"\"\n\n[case testInvalidSignatureInComment12]\ndef f(): # type: (x) -> x x # comment #2\n  pass\n[out]\nfile:1: error: Syntax error in type comment \"(x) -> x x\"\n\n\n[case testDuplicateSignatures1]\ndef f() -> None: # type: () -> None\n  pass\ndef f(): # type: () -> None\n    pass\n[out]\nfile:1: error: Function has duplicate type signatures\n\n[case testDuplicateSignatures2]\ndef f(x, y: Z): # type: (x, y) -> z\n  pass\n[out]\nfile:1: error: Function has duplicate type signatures\n\n[case testTooManyTypes]\ndef f(x, y): # type: (X, Y, Z) -> z\n  pass\n[out]\nfile:1: error: Type signature has too many arguments\n\n[case testTooFewTypes]\ndef f(x, y): # type: (X) -> z\n  pass\n[out]\nfile:1: error: Type signature has too few arguments\n\n[case testCommentFunctionAnnotationVarArgMispatch-skip]\n# see mypy issue #1997\ndef f(x): # type: (*X) -> Y\n    pass\ndef g(*x): # type: (X) -> Y\n    pass\n[out]\nfile:1: error: Inconsistent use of \"*\" in function signature\nfile:3: error: Inconsistent use of \"*\" in function signature\n\n[case testCommentFunctionAnnotationVarArgMispatch2-skip]\n# see mypy issue #1997\ndef f(*x, **y): # type: (**X, *Y) -> Z\n    pass\ndef g(*x, **y): # type: (*X, *Y) -> Z\n    pass\n[out]\nfile:1: error: Inconsistent use of \"*\" in function signature\nfile:3: error: Syntax error in type comment\nfile:3: error: Inconsistent use of \"*\" in function signature\nfile:3: error: Inconsistent use of \"**\" in function signature\n\n[case testPrintStatementInPython3]\nprint 1\n[out]\nfile:1: error: Missing parentheses in call to 'print'. Did you mean print(1)?\n\n[case testInvalidConditionInConditionalExpression]\n1 if 2, 3 else 4\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidConditionInConditionalExpression2]\n1 if x for y in z else 4\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidConditionInConditionalExpression3]\n1 if x else for y in z\n[out]\nfile:1: error: invalid syntax\n\n[case testYieldFromNotRightParameter]\ndef f():\n    yield from\n[out]\nfile:2: error: invalid syntax\n\n[case testYieldFromAfterReturn]\ndef f():\n    return yield from h()\n[out]\nfile:2: error: invalid syntax\n\n[case testImportDotModule]\nimport .x\n[out]\nfile:1: error: invalid syntax\n\n[case testImportDot]\nimport .\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidFunctionName]\ndef while(): pass\n[out]\nfile:1: error: invalid syntax\n\n[case testInvalidEllipsis1]\n...0\n..._\n...a\n[out]\nfile:1: error: invalid syntax\n\n[case testBlockStatementInSingleLineIf]\nif 1: if 2: pass\n[out]\nfile:1: error: invalid syntax\n\n[case testBlockStatementInSingleLineIf2]\nif 1: while 2: pass\n[out]\nfile:1: error: invalid syntax\n\n[case testBlockStatementInSingleLineIf3]\nif 1: for x in y: pass\n[out]\nfile:1: error: invalid syntax\n\n[case testUnexpectedEllipsis]\na = a...\n[out]\nfile:1: error: invalid syntax\n\n[case testParseErrorBeforeUnicodeLiteral]\nx u'y'\n[out]\nfile:1: error: invalid syntax\n\n[case testParseErrorInExtendedSlicing]\nx[:,\n[out]\nfile:1: error: unexpected EOF while parsing\n\n[case testParseErrorInExtendedSlicing2]\nx[:,::\n[out]\nfile:1: error: unexpected EOF while parsing\n\n[case testParseErrorInExtendedSlicing3]\nx[:,:\n[out]\nfile:1: error: unexpected EOF while parsing\n\n[case testInvalidEncoding]\n# foo\n# coding: uft-8\n[out]\nfile:0: error: unknown encoding: uft-8\n\n[case testInvalidEncoding2]\n# coding=Uft.8\n[out]\nfile:0: error: unknown encoding: Uft.8\n\n[case testInvalidEncoding3]\n#!/usr/bin python\n# vim: set fileencoding=uft8 :\n[out]\nfile:0: error: unknown encoding: uft8\n\n[case testDoubleEncoding]\n# coding: uft8\n# coding: utf8\n# The first coding cookie should be used and fail.\n[out]\nfile:0: error: unknown encoding: uft8\n\n[case testDoubleEncoding2]\n# Again the first cookie should be used and fail.\n# coding: uft8\n# coding: utf8\n[out]\nfile:0: error: unknown encoding: uft8\n\n[case testLongLiteralInPython3]\n2L\n0x2L\n[out]\nfile:1: error: invalid syntax\n\n[case testPython2LegacyInequalityInPython3]\n1 <> 2\n[out]\nfile:1: error: invalid syntax\n\n[case testLambdaInListComprehensionInPython3]\n([ 0 for x in 1, 2 if 3 ])\n[out]\nfile:1: error: invalid syntax\n\n[case testTupleArgListInPython3]\ndef f(x, (y, z)): pass\n[out]\nfile:1: error: invalid syntax\n\n[case testBackquoteInPython3]\n`1 + 2`\n[out]\nfile:1: error: invalid syntax\n\n[case testSmartQuotes]\nfoo = ‘bar’\n[out]\nfile:1: error: invalid character '‘' (U+2018)\n\n[case testExceptCommaInPython3]\ntry:\n    pass\nexcept KeyError, IndexError:\n    pass\n[out]\nfile:3: error: invalid syntax\n"
  },
  {
    "path": "test-data/unit/parse-python310.test",
    "content": "-- Test cases for parser -- Python 3.10 syntax (match statement)\n--\n-- See parse.test for a description of this file format.\n\n[case testSimpleMatch]\nmatch a:\n    case 1:\n      pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      ValuePattern:2(\n        IntExpr(1)))\n    Body(\n      PassStmt:3())))\n\n\n[case testTupleMatch]\nmatch a, b:\n    case 1:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    TupleExpr:1(\n      NameExpr(a)\n      NameExpr(b))\n    Pattern(\n      ValuePattern:2(\n        IntExpr(1)))\n    Body(\n      PassStmt:3())))\n\n[case testMatchWithGuard]\nmatch a:\n    case 1 if f():\n        pass\n    case d if d > 5:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      ValuePattern:2(\n        IntExpr(1)))\n    Guard(\n      CallExpr:2(\n        NameExpr(f)\n        Args()))\n    Body(\n      PassStmt:3())\n    Pattern(\n      AsPattern:4(\n        NameExpr(d)))\n    Guard(\n      ComparisonExpr:4(\n        >\n        NameExpr(d)\n        IntExpr(5)))\n    Body(\n      PassStmt:5())))\n\n[case testAsPattern]\nmatch a:\n    case 1 as b:\n      pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      AsPattern:2(\n        ValuePattern:2(\n          IntExpr(1))\n        NameExpr(b)))\n    Body(\n      PassStmt:3())))\n\n\n[case testLiteralPattern]\nmatch a:\n  case 1:\n    pass\n  case -1:\n    pass\n  case 1+2j:\n    pass\n  case -1+2j:\n    pass\n  case 1-2j:\n    pass\n  case -1-2j:\n    pass\n  case \"str\":\n    pass\n  case b\"bytes\":\n    pass\n  case r\"raw_string\":\n    pass\n  case None:\n    pass\n  case True:\n    pass\n  case False:\n    pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      ValuePattern:2(\n        IntExpr(1)))\n    Body(\n      PassStmt:3())\n    Pattern(\n      ValuePattern:4(\n        UnaryExpr:4(\n          -\n          IntExpr(1))))\n    Body(\n      PassStmt:5())\n    Pattern(\n      ValuePattern:6(\n        OpExpr:6(\n          +\n          IntExpr(1)\n          ComplexExpr(2j))))\n    Body(\n      PassStmt:7())\n    Pattern(\n      ValuePattern:8(\n        OpExpr:8(\n          +\n          UnaryExpr:8(\n            -\n            IntExpr(1))\n          ComplexExpr(2j))))\n    Body(\n      PassStmt:9())\n    Pattern(\n      ValuePattern:10(\n        OpExpr:10(\n          -\n          IntExpr(1)\n          ComplexExpr(2j))))\n    Body(\n      PassStmt:11())\n    Pattern(\n      ValuePattern:12(\n        OpExpr:12(\n          -\n          UnaryExpr:12(\n            -\n            IntExpr(1))\n          ComplexExpr(2j))))\n    Body(\n      PassStmt:13())\n    Pattern(\n      ValuePattern:14(\n        StrExpr(str)))\n    Body(\n      PassStmt:15())\n    Pattern(\n      ValuePattern:16(\n        BytesExpr(bytes)))\n    Body(\n      PassStmt:17())\n    Pattern(\n      ValuePattern:18(\n        StrExpr(raw_string)))\n    Body(\n      PassStmt:19())\n    Pattern(\n      SingletonPattern:20())\n    Body(\n      PassStmt:21())\n    Pattern(\n      SingletonPattern:22(\n        True))\n    Body(\n      PassStmt:23())\n    Pattern(\n      SingletonPattern:24(\n        False))\n    Body(\n      PassStmt:25())))\n\n[case testCapturePattern]\nmatch a:\n    case x:\n        pass\n    case longName:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      AsPattern:2(\n        NameExpr(x)))\n    Body(\n      PassStmt:3())\n    Pattern(\n      AsPattern:4(\n        NameExpr(longName)))\n    Body(\n      PassStmt:5())))\n\n[case testWildcardPattern]\nmatch a:\n    case _:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      AsPattern:2())\n    Body(\n      PassStmt:3())))\n\n[case testValuePattern]\nmatch a:\n    case b.c:\n        pass\n    case b.c.d.e.f:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      ValuePattern:2(\n        MemberExpr:2(\n          NameExpr(b)\n          c)))\n    Body(\n      PassStmt:3())\n    Pattern(\n      ValuePattern:4(\n        MemberExpr:4(\n          MemberExpr:4(\n            MemberExpr:4(\n              MemberExpr:4(\n                NameExpr(b)\n                c)\n              d)\n            e)\n          f)))\n    Body(\n      PassStmt:5())))\n\n[case testGroupPattern]\n# This is optimized out by the compiler. It doesn't appear in the ast\nmatch a:\n    case (1):\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:2(\n    NameExpr(a)\n    Pattern(\n      ValuePattern:3(\n        IntExpr(1)))\n    Body(\n      PassStmt:4())))\n\n[case testSequencePattern]\nmatch a:\n    case []:\n        pass\n    case ():\n        pass\n    case [1]:\n        pass\n    case (1,):\n        pass\n    case 1,:\n        pass\n    case [1, 2, 3]:\n        pass\n    case (1, 2, 3):\n        pass\n    case 1, 2, 3:\n        pass\n    case [1, *a, 2]:\n        pass\n    case (1, *a, 2):\n        pass\n    case 1, *a, 2:\n        pass\n    case [1, *_, 2]:\n        pass\n    case (1, *_, 2):\n        pass\n    case 1, *_, 2:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      SequencePattern:2())\n    Body(\n      PassStmt:3())\n    Pattern(\n      SequencePattern:4())\n    Body(\n      PassStmt:5())\n    Pattern(\n      SequencePattern:6(\n        ValuePattern:6(\n          IntExpr(1))))\n    Body(\n      PassStmt:7())\n    Pattern(\n      SequencePattern:8(\n        ValuePattern:8(\n          IntExpr(1))))\n    Body(\n      PassStmt:9())\n    Pattern(\n      SequencePattern:10(\n        ValuePattern:10(\n          IntExpr(1))))\n    Body(\n      PassStmt:11())\n    Pattern(\n      SequencePattern:12(\n        ValuePattern:12(\n          IntExpr(1))\n        ValuePattern:12(\n          IntExpr(2))\n        ValuePattern:12(\n          IntExpr(3))))\n    Body(\n      PassStmt:13())\n    Pattern(\n      SequencePattern:14(\n        ValuePattern:14(\n          IntExpr(1))\n        ValuePattern:14(\n          IntExpr(2))\n        ValuePattern:14(\n          IntExpr(3))))\n    Body(\n      PassStmt:15())\n    Pattern(\n      SequencePattern:16(\n        ValuePattern:16(\n          IntExpr(1))\n        ValuePattern:16(\n          IntExpr(2))\n        ValuePattern:16(\n          IntExpr(3))))\n    Body(\n      PassStmt:17())\n    Pattern(\n      SequencePattern:18(\n        ValuePattern:18(\n          IntExpr(1))\n        StarredPattern:18(\n          NameExpr(a))\n        ValuePattern:18(\n          IntExpr(2))))\n    Body(\n      PassStmt:19())\n    Pattern(\n      SequencePattern:20(\n        ValuePattern:20(\n          IntExpr(1))\n        StarredPattern:20(\n          NameExpr(a))\n        ValuePattern:20(\n          IntExpr(2))))\n    Body(\n      PassStmt:21())\n    Pattern(\n      SequencePattern:22(\n        ValuePattern:22(\n          IntExpr(1))\n        StarredPattern:22(\n          NameExpr(a))\n        ValuePattern:22(\n          IntExpr(2))))\n    Body(\n      PassStmt:23())\n    Pattern(\n      SequencePattern:24(\n        ValuePattern:24(\n          IntExpr(1))\n        StarredPattern:24()\n        ValuePattern:24(\n          IntExpr(2))))\n    Body(\n      PassStmt:25())\n    Pattern(\n      SequencePattern:26(\n        ValuePattern:26(\n          IntExpr(1))\n        StarredPattern:26()\n        ValuePattern:26(\n          IntExpr(2))))\n    Body(\n      PassStmt:27())\n    Pattern(\n      SequencePattern:28(\n        ValuePattern:28(\n          IntExpr(1))\n        StarredPattern:28()\n        ValuePattern:28(\n          IntExpr(2))))\n    Body(\n      PassStmt:29())))\n\n[case testMappingPattern]\nmatch a:\n    case {'k': v}:\n        pass\n    case {a.b: v}:\n        pass\n    case {1: v}:\n        pass\n    case {a.c: v}:\n        pass\n    case {'k': v1, a.b: v2, 1: v3, a.c: v4}:\n        pass\n    case {'k1': 1, 'k2': \"str\", 'k3': b'bytes', 'k4': None}:\n        pass\n    case {'k': v, **r}:\n        pass\n    case {**r}:\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      MappingPattern:2(\n        Key(\n          StrExpr(k))\n        Value(\n          AsPattern:2(\n            NameExpr(v)))))\n    Body(\n      PassStmt:3())\n    Pattern(\n      MappingPattern:4(\n        Key(\n          MemberExpr:4(\n            NameExpr(a)\n            b))\n        Value(\n          AsPattern:4(\n            NameExpr(v)))))\n    Body(\n      PassStmt:5())\n    Pattern(\n      MappingPattern:6(\n        Key(\n          IntExpr(1))\n        Value(\n          AsPattern:6(\n            NameExpr(v)))))\n    Body(\n      PassStmt:7())\n    Pattern(\n      MappingPattern:8(\n        Key(\n          MemberExpr:8(\n            NameExpr(a)\n            c))\n        Value(\n          AsPattern:8(\n            NameExpr(v)))))\n    Body(\n      PassStmt:9())\n    Pattern(\n      MappingPattern:10(\n        Key(\n          StrExpr(k))\n        Value(\n          AsPattern:10(\n            NameExpr(v1)))\n        Key(\n          MemberExpr:10(\n            NameExpr(a)\n            b))\n        Value(\n          AsPattern:10(\n            NameExpr(v2)))\n        Key(\n          IntExpr(1))\n        Value(\n          AsPattern:10(\n            NameExpr(v3)))\n        Key(\n          MemberExpr:10(\n            NameExpr(a)\n            c))\n        Value(\n          AsPattern:10(\n            NameExpr(v4)))))\n    Body(\n      PassStmt:11())\n    Pattern(\n      MappingPattern:12(\n        Key(\n          StrExpr(k1))\n        Value(\n          ValuePattern:12(\n            IntExpr(1)))\n        Key(\n          StrExpr(k2))\n        Value(\n          ValuePattern:12(\n            StrExpr(str)))\n        Key(\n          StrExpr(k3))\n        Value(\n          ValuePattern:12(\n            BytesExpr(bytes)))\n        Key(\n          StrExpr(k4))\n        Value(\n          SingletonPattern:12())))\n    Body(\n      PassStmt:13())\n    Pattern(\n      MappingPattern:14(\n        Key(\n          StrExpr(k))\n        Value(\n          AsPattern:14(\n            NameExpr(v)))\n        Rest(\n          NameExpr(r))))\n    Body(\n      PassStmt:15())\n    Pattern(\n      MappingPattern:16(\n        Rest(\n          NameExpr(r))))\n    Body(\n      PassStmt:17())))\n\n[case testClassPattern]\nmatch a:\n    case A():\n        pass\n    case B(1, 2):\n        pass\n    case B(1, b=2):\n        pass\n    case B(a=1, b=2):\n        pass\n[out]\nMypyFile:1(\n  MatchStmt:1(\n    NameExpr(a)\n    Pattern(\n      ClassPattern:2(\n        NameExpr(A)))\n    Body(\n      PassStmt:3())\n    Pattern(\n      ClassPattern:4(\n        NameExpr(B)\n        Positionals(\n          ValuePattern:4(\n            IntExpr(1))\n          ValuePattern:4(\n            IntExpr(2)))))\n    Body(\n      PassStmt:5())\n    Pattern(\n      ClassPattern:6(\n        NameExpr(B)\n        Positionals(\n          ValuePattern:6(\n            IntExpr(1)))\n        Keyword(\n          b\n          ValuePattern:6(\n            IntExpr(2)))))\n    Body(\n      PassStmt:7())\n    Pattern(\n      ClassPattern:8(\n        NameExpr(B)\n        Keyword(\n          a\n          ValuePattern:8(\n            IntExpr(1)))\n        Keyword(\n          b\n          ValuePattern:8(\n            IntExpr(2)))))\n    Body(\n      PassStmt:9())))\n"
  },
  {
    "path": "test-data/unit/parse-python312.test",
    "content": "[case testPEP695TypeAlias]\n# comment\ntype A[T] = C[T]\n[out]\nMypyFile:1(\n  TypeAliasStmt:2(\n    NameExpr(A)\n    TypeParam(\n      T)\n    LambdaExpr:2(\n      Block:-1(\n        ReturnStmt:2(\n          IndexExpr:2(\n            NameExpr(C)\n            NameExpr(T)))))))\n\n[case testPEP695GenericFunction]\n# comment\n\ndef f[T](): pass\ndef g[T: str](): pass\ndef h[T: (int, str)](): pass\n[out]\nMypyFile:1(\n  FuncDef:3(\n    f\n    TypeParam(\n      T)\n    Block:3(\n      PassStmt:3()))\n  FuncDef:4(\n    g\n    TypeParam(\n      T\n      str?)\n    Block:4(\n      PassStmt:4()))\n  FuncDef:5(\n    h\n    TypeParam(\n      T\n      Values(\n        int?\n        str?))\n    Block:5(\n      PassStmt:5())))\n\n[case testPEP695ParamSpec]\n# comment\n\ndef f[**P](): pass\nclass C[T: int, **P]: pass\n[out]\nMypyFile:1(\n  FuncDef:3(\n    f\n    TypeParam(\n      **P)\n    Block:3(\n      PassStmt:3()))\n  ClassDef:4(\n    C\n    TypeParam(\n      T\n      int?)\n    TypeParam(\n      **P)\n    PassStmt:4()))\n\n[case testPEP695TypeVarTuple]\n# comment\n\ndef f[*Ts](): pass\nclass C[T: int, *Ts]: pass\n[out]\nMypyFile:1(\n  FuncDef:3(\n    f\n    TypeParam(\n      *Ts)\n    Block:3(\n      PassStmt:3()))\n  ClassDef:4(\n    C\n    TypeParam(\n      T\n      int?)\n    TypeParam(\n      *Ts)\n    PassStmt:4()))\n"
  },
  {
    "path": "test-data/unit/parse-python313.test",
    "content": "[case testPEP696TypeAlias]\ntype A[T = int] = C[T]\n[out]\nMypyFile:1(\n  TypeAliasStmt:1(\n    NameExpr(A)\n    TypeParam(\n      T\n      Default(\n        int?))\n    LambdaExpr:1(\n      Block:-1(\n        ReturnStmt:1(\n          IndexExpr:1(\n            NameExpr(C)\n            NameExpr(T)))))))\n\n[case testPEP696GenericFunction]\ndef f[T = int](): pass\nclass C[T = int]: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    TypeParam(\n      T\n      Default(\n        int?))\n    Block:1(\n      PassStmt:1()))\n  ClassDef:2(\n    C\n    TypeParam(\n      T\n      Default(\n        int?))\n    PassStmt:2()))\n\n[case testPEP696ParamSpec]\ndef f[**P = [int, str]](): pass\nclass C[**P = [int, str]]: pass\n[out]\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    TypeParam(\n      **P\n      Default(\n        <TypeList int?, str?>))\n    Block:1(\n      PassStmt:1()))\n  ClassDef:2(\n    C\n    TypeParam(\n      **P\n      Default(\n        <TypeList int?, str?>))\n    PassStmt:2()))\n\n[case testPEP696TypeVarTuple]\ndef f[*Ts = *tuple[str, int]](): pass\nclass C[*Ts = *tuple[str, int]]: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    TypeParam(\n      *Ts\n      Default(\n        Unpack[tuple?[str?, int?]]))\n    Block:1(\n      PassStmt:1()))\n  ClassDef:2(\n    C\n    TypeParam(\n      *Ts\n      Default(\n        Unpack[tuple?[str?, int?]]))\n    PassStmt:2()))\n"
  },
  {
    "path": "test-data/unit/parse.test",
    "content": "-- Test cases for parser. Each test case consists of two sections.\n-- The first section contains [case NAME] followed by the input code, while\n-- the second section contains [out] followed by the output from the parser.\n--\n-- Lines starting with \"--\" in this file will be ignored, except for lines\n-- starting with \"----\" that are not ignored. The first two dashes of these\n-- lines are interpreted as escapes and removed.\n\n[case testEmptyFile]\n[out]\nMypyFile:1()\n\n[case testExpressionStatement]\n1\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IntExpr(1)))\n\n[case testAssignment]\nx = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(1)))\n\n[case testExpressionBasics]\nx = f(1, None)\n123 * (2 + x)\n\"hello\".lower()\n-1.23\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    CallExpr:1(\n      NameExpr(f)\n      Args(\n        IntExpr(1)\n        NameExpr(None))))\n  ExpressionStmt:2(\n    OpExpr:2(\n      *\n      IntExpr(123)\n      OpExpr:2(\n        +\n        IntExpr(2)\n        NameExpr(x))))\n  ExpressionStmt:3(\n    CallExpr:3(\n      MemberExpr:3(\n        StrExpr(hello)\n        lower)\n      Args()))\n  ExpressionStmt:4(\n    UnaryExpr:4(\n      -\n      FloatExpr(1.23))))\n\n[case testSingleQuotedStr]\n''\n'foo'\n'foo\\\nbar'\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr())\n  ExpressionStmt:2(\n    StrExpr(foo))\n  ExpressionStmt:3(\n    StrExpr(foobar)))\n\n[case testDoubleQuotedStr]\n\"\"\n\"foo\"\n\"foo\\\nbar\"\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr())\n  ExpressionStmt:2(\n    StrExpr(foo))\n  ExpressionStmt:3(\n    StrExpr(foobar)))\n\n[case testRawStr]\nr'x\\n\\''\nr\"x\\n\\\"\"\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr(x\\n\\'))\n  ExpressionStmt:2(\n    StrExpr(x\\n\\\")))\n\n[case testBytes]\nb'foo'\nb\"foo\\\nbar\"\nbr'x\\n\\''\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    BytesExpr(foo))\n  ExpressionStmt:2(\n    BytesExpr(foobar))\n  ExpressionStmt:3(\n    BytesExpr(x\\\\n\\\\')))\n\n[case testEscapesInStrings]\n'\\r\\n\\t\\x2f\\u123f'\nb'\\r\\n\\t\\x2f\\u123f'\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr(\\u000d\\u000a\\u0009/\\u123f))\n  ExpressionStmt:2(\n    BytesExpr(\\r\\n\\t/\\\\\\u123f)))\n-- Note \\\\u in the b'...' case (\\u sequence not translated)\n\n[case testEscapedQuote]\n'\\''\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr(')))\n\n[case testOctalEscapes]\n'\\0\\1\\177\\1234'\nb'\\1\\476'\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr(\\u0000\\u0001\\u007fS4))\n  ExpressionStmt:2(\n    BytesExpr(\\x01>)))\n\n[case testUnicodeLiteralInPython3]\nu'foo'\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr(foo)))\n\n[case testArrays]\na = []\na = [1, 2]\na[[1]] = a[2]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    ListExpr:1())\n  AssignmentStmt:2(\n    NameExpr(a)\n    ListExpr:2(\n      IntExpr(1)\n      IntExpr(2)))\n  AssignmentStmt:3(\n    IndexExpr:3(\n      NameExpr(a)\n      ListExpr:3(\n        IntExpr(1)))\n    IndexExpr:3(\n      NameExpr(a)\n      IntExpr(2))))\n\n[case testTuples]\n()\n(1,)\n(1, foo)\na, b = 1, (2, 3)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    TupleExpr:1())\n  ExpressionStmt:2(\n    TupleExpr:2(\n      IntExpr(1)))\n  ExpressionStmt:3(\n    TupleExpr:3(\n      IntExpr(1)\n      NameExpr(foo)))\n  AssignmentStmt:4(\n    TupleExpr:4(\n      NameExpr(a)\n      NameExpr(b))\n    TupleExpr:4(\n      IntExpr(1)\n      TupleExpr:4(\n        IntExpr(2)\n        IntExpr(3)))))\n\n[case testSimpleFunction]\ndef main():\n  1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    main\n    Block:2(\n      ExpressionStmt:2(\n        IntExpr(1)))))\n\n[case testPass]\ndef f():\n    pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      PassStmt:2())))\n\n[case testIf]\nif 1:\n    2\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      ExpressionStmt:2(\n        IntExpr(2)))))\n\n[case testIfElse]\nif 1:\n    2\nelse:\n    3\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      ExpressionStmt:2(\n        IntExpr(2)))\n    Else(\n      ExpressionStmt:4(\n        IntExpr(3)))))\n\n[case testIfElif]\nif 1:\n    2\nelif 3:\n    4\nelif 5:\n    6\nelse:\n    7\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      ExpressionStmt:2(\n        IntExpr(2)))\n    Else(\n      IfStmt:3(\n        If(\n          IntExpr(3))\n        Then(\n          ExpressionStmt:4(\n            IntExpr(4)))\n        Else(\n          IfStmt:5(\n            If(\n              IntExpr(5))\n            Then(\n              ExpressionStmt:6(\n                IntExpr(6)))\n            Else(\n              ExpressionStmt:8(\n                IntExpr(7)))))))))\n\n[case testWhile]\nwhile 1:\n    pass\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(1)\n    Block:2(\n      PassStmt:2())))\n\n[case testReturn]\ndef f():\n    return 1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ReturnStmt:2(\n        IntExpr(1)))))\n\n\n[case testReturnWithoutValue]\ndef f():\n    return\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ReturnStmt:2())))\n\n[case testBreak]\nwhile 1:\n    break\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(1)\n    Block:2(\n      BreakStmt:2())))\n\n[case testLargeBlock]\nif 1:\n    x = 1\n    while 2:\n        pass\n    y = 2\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      AssignmentStmt:2(\n        NameExpr(x)\n        IntExpr(1))\n      WhileStmt:3(\n        IntExpr(2)\n        Block:4(\n          PassStmt:4()))\n      AssignmentStmt:5(\n        NameExpr(y)\n        IntExpr(2)))))\n\n[case testSimpleClass]\nclass A:\n    def f(self):\n        pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      f\n      Args(\n        Var(self))\n      Block:3(\n        PassStmt:3()))))\n\n[case testGlobalVarWithType]\nx = 0 # type: int\ny = False # type: bool\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(0)\n    int?)\n  AssignmentStmt:2(\n    NameExpr(y)\n    NameExpr(False)\n    bool?))\n\n[case testLocalVarWithType]\ndef f():\n  x = 0 # type: int\n  y = False # type: bool\n  a = None # type: Any\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(x)\n        IntExpr(0)\n        int?)\n      AssignmentStmt:3(\n        NameExpr(y)\n        NameExpr(False)\n        bool?)\n      AssignmentStmt:4(\n        NameExpr(a)\n        NameExpr(None)\n        Any?))))\n\n[case testFunctionDefWithType]\ndef f(y: str) -> int:\n  return\nclass A:\n  def f(self, a: int, b: Any) -> x:\n    pass\n  def g(self) -> Any:\n    pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(y))\n    def (y: str?) -> int?\n    Block:2(\n      ReturnStmt:2()))\n  ClassDef:3(\n    A\n    FuncDef:4(\n      f\n      Args(\n        Var(self)\n        Var(a)\n        Var(b))\n      def (self: Any, a: int?, b: Any?) -> x?\n      Block:5(\n        PassStmt:5()))\n    FuncDef:6(\n      g\n      Args(\n        Var(self))\n      def (self: Any) -> Any?\n      Block:7(\n        PassStmt:7()))))\n\n[case testFuncWithNoneReturn]\ndef f() -> None:\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> None?\n    Block:2(\n      PassStmt:2())))\n\n[case testVarDefWithGenericType]\nx = None # type: List[str]\ny = None # type: Dict[int, Any]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    NameExpr(None)\n    List?[str?])\n  AssignmentStmt:2(\n    NameExpr(y)\n    NameExpr(None)\n    Dict?[int?, Any?]))\n\n[case testSignatureWithGenericTypes]\ndef f(y: t[Any, x]) -> a[b[c], d]:\n    pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(y))\n    def (y: t?[Any?, x?]) -> a?[b?[c?], d?]\n    Block:2(\n      PassStmt:2())))\n\n[case testParsingExpressionsWithLessAndGreaterThan]\n# The operators < > can sometimes be confused with generic types.\nx = a < b > c\nf(x < b, y > c)\na < b > 1\nx < b, y > 2\n(a < b > c)\n[out]\nMypyFile:1(\n  AssignmentStmt:2(\n    NameExpr(x)\n    ComparisonExpr:2(\n      <\n      >\n      NameExpr(a)\n      NameExpr(b)\n      NameExpr(c)))\n  ExpressionStmt:3(\n    CallExpr:3(\n      NameExpr(f)\n      Args(\n        ComparisonExpr:3(\n          <\n          NameExpr(x)\n          NameExpr(b))\n        ComparisonExpr:3(\n          >\n          NameExpr(y)\n          NameExpr(c)))))\n  ExpressionStmt:4(\n    ComparisonExpr:4(\n      <\n      >\n      NameExpr(a)\n      NameExpr(b)\n      IntExpr(1)))\n  ExpressionStmt:5(\n    TupleExpr:5(\n      ComparisonExpr:5(\n        <\n        NameExpr(x)\n        NameExpr(b))\n      ComparisonExpr:5(\n        >\n        NameExpr(y)\n        IntExpr(2))))\n  ExpressionStmt:6(\n    ComparisonExpr:6(\n      <\n      >\n      NameExpr(a)\n      NameExpr(b)\n      NameExpr(c))))\n\n[case testLineContinuation]\nif (1 +\n    2):\n  pass\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      OpExpr:1(\n        +\n        IntExpr(1)\n        IntExpr(2)))\n    Then(\n      PassStmt:3())))\n\n[case testMultipleVarDef]\nx, y = z # type: int, a[c]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    TupleExpr:1(\n      NameExpr(x)\n      NameExpr(y))\n    NameExpr(z)\n    Tuple[int?, a?[c?]]))\n\n[case testMultipleVarDef2]\n(xx, z, i) = 1 # type: (a[c], Any, int)\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    TupleExpr:1(\n      NameExpr(xx)\n      NameExpr(z)\n      NameExpr(i))\n    IntExpr(1)\n    Tuple[a?[c?], Any?, int?]))\n\n[case testMultipleVarDef3]\n(xx, (z, i)) = 1 # type: (a[c], (Any, int))\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    TupleExpr:1(\n      NameExpr(xx)\n      TupleExpr:1(\n        NameExpr(z)\n        NameExpr(i)))\n    IntExpr(1)\n    Tuple[a?[c?], Tuple[Any?, int?]]))\n\n[case testAnnotateAssignmentViaSelf]\nclass A:\n    def __init__(self):\n        self.x = 1 # type: int\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      __init__\n      Args(\n        Var(self))\n      Block:3(\n        AssignmentStmt:3(\n          MemberExpr:3(\n            NameExpr(self)\n            x)\n          IntExpr(1)\n          int?)))))\n\n[case testCommentAfterTypeComment]\nx = 0 # type: int # bar!\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(0)\n    int?))\n\n[case testMultilineAssignmentAndAnnotations]\n(x,\n y) = (1,\n      2) # type: foo, bar\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    TupleExpr:1(\n      NameExpr(x)\n      NameExpr(y))\n    TupleExpr:2(\n      IntExpr(1)\n      IntExpr(2))\n    Tuple[foo?, bar?]))\n\n[case testWhitespaceAndCommentAnnotation]\nx = 1#type:int\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(1)\n    int?))\n\n[case testWhitespaceAndCommentAnnotation2]\nx = 1#   type:   int\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(1)\n    int?))\n\n[case testWhitespaceAndCommentAnnotation3]\nx = 1# type : int       # not recognized!\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(1)))\n\n[case testInvalidAnnotation]\nx=1 ##type: int\ny=1 #.type: int\nz=1 # Type: int\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    IntExpr(1))\n  AssignmentStmt:2(\n    NameExpr(y)\n    IntExpr(1))\n  AssignmentStmt:3(\n    NameExpr(z)\n    IntExpr(1)))\n\n[case testEmptyClass]\nclass C:\n  pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    C\n    PassStmt:2()))\n\n[case testOperatorPrecedence]\na | b ^ c\na & b << c\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    OpExpr:1(\n      |\n      NameExpr(a)\n      OpExpr:1(\n        ^\n        NameExpr(b)\n        NameExpr(c))))\n  ExpressionStmt:2(\n    OpExpr:2(\n      &\n      NameExpr(a)\n      OpExpr:2(\n        <<\n        NameExpr(b)\n        NameExpr(c)))))\n\n[case testOperatorAssociativity]\n1 - 2 + 3\n1 << 2 << 3\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    OpExpr:1(\n      +\n      OpExpr:1(\n        -\n        IntExpr(1)\n        IntExpr(2))\n      IntExpr(3)))\n  ExpressionStmt:2(\n    OpExpr:2(\n      <<\n      OpExpr:2(\n        <<\n        IntExpr(1)\n        IntExpr(2))\n      IntExpr(3))))\n\n[case testUnaryOperators]\n-2 * +3 * ~3 * 2\n~3**2\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    OpExpr:1(\n      *\n      OpExpr:1(\n        *\n        OpExpr:1(\n          *\n          UnaryExpr:1(\n            -\n            IntExpr(2))\n          UnaryExpr:1(\n            +\n            IntExpr(3)))\n        UnaryExpr:1(\n          ~\n          IntExpr(3)))\n      IntExpr(2)))\n  ExpressionStmt:2(\n    UnaryExpr:2(\n      ~\n      OpExpr:2(\n        **\n        IntExpr(3)\n        IntExpr(2)))))\n\n[case testSingleLineBodies]\nif 1: pass\nwhile 1: pass\ndef f(): pass\ndef g() -> int: return 1\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      PassStmt:1()))\n  WhileStmt:2(\n    IntExpr(1)\n    Block:2(\n      PassStmt:2()))\n  FuncDef:3(\n    f\n    Block:3(\n      PassStmt:3()))\n  FuncDef:4(\n    g\n    def () -> int?\n    Block:4(\n      ReturnStmt:4(\n        IntExpr(1)))))\n\n[case testForStatement]\nfor x in y:\n  pass\nfor x, (y, w) in z:\n  1\nfor [x, (y, w)] in z:\n  1\n[out]\nMypyFile:1(\n  ForStmt:1(\n    NameExpr(x)\n    NameExpr(y)\n    Block:2(\n      PassStmt:2()))\n  ForStmt:3(\n    TupleExpr:3(\n      NameExpr(x)\n      TupleExpr:3(\n        NameExpr(y)\n        NameExpr(w)))\n    NameExpr(z)\n    Block:4(\n      ExpressionStmt:4(\n        IntExpr(1))))\n  ForStmt:5(\n    TupleExpr:5(\n      NameExpr(x)\n      TupleExpr:5(\n        NameExpr(y)\n        NameExpr(w)))\n    NameExpr(z)\n    Block:6(\n      ExpressionStmt:6(\n        IntExpr(1)))))\n\n[case testGlobalDecl]\nglobal x\ndef f():\n  global x, y\n[out]\nMypyFile:1(\n  GlobalDecl:1(\n    x)\n  FuncDef:2(\n    f\n    Block:3(\n      GlobalDecl:3(\n        x\n        y))))\n\n[case testNonlocalDecl]\ndef f():\n  def g():\n    nonlocal x, y\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      FuncDef:2(\n        g\n        Block:3(\n          NonlocalDecl:3(\n            x\n            y))))))\n\n[case testRaiseStatement]\nraise foo\n[out]\nMypyFile:1(\n  RaiseStmt:1(\n    NameExpr(foo)))\n\n[case testRaiseWithoutArg]\ntry:\n  pass\nexcept:\n  raise\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    Block:4(\n      RaiseStmt:4())))\n\n[case testRaiseFrom]\nraise e from x\n[out]\nMypyFile:1(\n  RaiseStmt:1(\n    NameExpr(e)\n    NameExpr(x)))\n\n[case testBaseclasses]\nclass A(B):\n  pass\nclass A(B[T], C[Any, d[x]]):\n  pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    BaseTypeExpr(\n      NameExpr(B))\n    PassStmt:2())\n  ClassDef:3(\n    A\n    BaseTypeExpr(\n      IndexExpr:3(\n        NameExpr(B)\n        NameExpr(T))\n      IndexExpr:3(\n        NameExpr(C)\n        TupleExpr:3(\n          NameExpr(Any)\n          IndexExpr:3(\n            NameExpr(d)\n            NameExpr(x)))))\n    PassStmt:4()))\n\n[case testIsNot]\nx is not y\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    ComparisonExpr:1(\n      is not\n      NameExpr(x)\n      NameExpr(y))))\n\n[case testNotIn]\nx not in y\nnot x not in y\nx not in y | z\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    ComparisonExpr:1(\n      not in\n      NameExpr(x)\n      NameExpr(y)))\n  ExpressionStmt:2(\n    UnaryExpr:2(\n      not\n      ComparisonExpr:2(\n        not in\n        NameExpr(x)\n        NameExpr(y))))\n  ExpressionStmt:3(\n    ComparisonExpr:3(\n      not in\n      NameExpr(x)\n      OpExpr:3(\n        |\n        NameExpr(y)\n        NameExpr(z)))))\n\n[case testNotAsBinaryOp]\nx not y\n[out]\nmain:1: error: invalid syntax\n[out version==3.10.0]\nmain:1: error: invalid syntax. Perhaps you forgot a comma?\n\n[case testNotIs]\nx not is y # E: invalid syntax\n[out]\n\n[case testBinaryNegAsBinaryOp]\n1 ~ 2\n[out]\nmain:1: error: invalid syntax\n[out version==3.10.0]\nmain:1: error: invalid syntax. Perhaps you forgot a comma?\n\n[case testSliceInList39]\n# flags: --python-version 3.9\nx = [1, 2][1:2]\n[out]\nMypyFile:1(\n  AssignmentStmt:2(\n    NameExpr(x)\n    IndexExpr:2(\n      ListExpr:2(\n        IntExpr(1)\n        IntExpr(2))\n      SliceExpr:2(\n        IntExpr(1)\n        IntExpr(2)))))\n\n[case testDictionaryExpression]\n{}\n{1:x}\n{1:x, 2 or 1:2 and 3}\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    DictExpr:1())\n  ExpressionStmt:2(\n    DictExpr:2(\n      IntExpr(1)\n      NameExpr(x)))\n  ExpressionStmt:3(\n    DictExpr:3(\n      IntExpr(1)\n      NameExpr(x)\n      OpExpr:3(\n        or\n        IntExpr(2)\n        IntExpr(1))\n      OpExpr:3(\n        and\n        IntExpr(2)\n        IntExpr(3)))))\n\n[case testImport]\nimport x\nimport y.z.foo, __foo__.bar\n[out]\nMypyFile:1(\n  Import:1(x)\n  Import:2(y.z.foo, __foo__.bar))\n\n[case testVariableTypeWithQualifiedName]\nx = None # type: x.y\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    NameExpr(None)\n    x.y?))\n\n[case testTypeInSignatureWithQualifiedName]\ndef f() -> x.y[a.b.c]: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> x.y?[a.b.c?]\n    Block:1(\n      PassStmt:1())))\n\n[case testImportFrom]\nfrom m import x\nfrom m.n import x, y, z\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [x])\n  ImportFrom:2(m.n, [x, y, z]))\n\n[case testImportFromAs]\nfrom m import x as y\nfrom x import y, z as a, c as c\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [x : y])\n  ImportFrom:2(x, [y, z : a, c : c]))\n\n[case testImportStar]\nfrom x import *\n[out]\nMypyFile:1(\n  ImportAll:1(x))\n\n[case testImportsInDifferentPlaces]\n1\nimport x\ndef f():\n  from x import y\n  from z import *\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IntExpr(1))\n  Import:2(x)\n  FuncDef:3(\n    f\n    Block:4(\n      ImportFrom:4(x, [y])\n      ImportAll:5(z))))\n\n[case testImportWithExtraComma]\nfrom x import (y, z,)\n[out]\nMypyFile:1(\n  ImportFrom:1(x, [y, z]))\n\n[case testDefaultArgs]\ndef f(x=1):\n  pass\ndef g(x, y=1+2, z=(1, 2)):\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      default(\n        Var(x)\n        IntExpr(1)))\n    Block:2(\n      PassStmt:2()))\n  FuncDef:3(\n    g\n    Args(\n      Var(x)\n      default(\n        Var(y)\n        OpExpr:3(\n          +\n          IntExpr(1)\n          IntExpr(2)))\n      default(\n        Var(z)\n        TupleExpr:3(\n          IntExpr(1)\n          IntExpr(2))))\n    Block:4(\n      PassStmt:4())))\n\n[case testTryFinally]\ntry:\n  1\nfinally:\n  2\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      ExpressionStmt:2(\n        IntExpr(1)))\n    Finally(\n      ExpressionStmt:4(\n        IntExpr(2)))))\n\n[case testTry]\ntry:\n  1\nexcept x:\n  2\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      ExpressionStmt:2(\n        IntExpr(1)))\n    NameExpr(x)\n    Block:4(\n      ExpressionStmt:4(\n        IntExpr(2)))))\n\n[case testComplexTry]\ntry:\n  1\nexcept x as y:\n  2\nexcept x.y:\n  3\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      ExpressionStmt:2(\n        IntExpr(1)))\n    NameExpr(x)\n    NameExpr(y)\n    Block:4(\n      ExpressionStmt:4(\n        IntExpr(2)))\n    MemberExpr:5(\n      NameExpr(x)\n      y)\n    Block:6(\n      ExpressionStmt:6(\n        IntExpr(3)))))\n\n[case testGeneratorExpression]\n(x for y in z)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    GeneratorExpr:1(\n      NameExpr(x)\n      NameExpr(y)\n      NameExpr(z))))\n\n[case testGeneratorExpressionNested]\n(x for y, (p, q) in z)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    GeneratorExpr:1(\n      NameExpr(x)\n      TupleExpr:1(\n        NameExpr(y)\n        TupleExpr:1(\n          NameExpr(p)\n          NameExpr(q)))\n      NameExpr(z))))\n\n[case testListComprehension]\nx=[x for y in z]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    ListComprehension:1(\n      GeneratorExpr:1(\n        NameExpr(x)\n        NameExpr(y)\n        NameExpr(z)))))\n\n[case testComplexListComprehension]\nx=[(x, y) for y, z in (1, 2)]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    ListComprehension:1(\n      GeneratorExpr:1(\n        TupleExpr:1(\n          NameExpr(x)\n          NameExpr(y))\n        TupleExpr:1(\n          NameExpr(y)\n          NameExpr(z))\n        TupleExpr:1(\n          IntExpr(1)\n          IntExpr(2))))))\n\n[case testListComprehension2]\n([x + 1 for x in a])\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    ListComprehension:1(\n      GeneratorExpr:1(\n        OpExpr:1(\n          +\n          NameExpr(x)\n          IntExpr(1))\n        NameExpr(x)\n        NameExpr(a)))))\n\n[case testSlices]\nx[1:2]\nx[:1]\nx[1:]\nx[:]\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IndexExpr:1(\n      NameExpr(x)\n      SliceExpr:1(\n        IntExpr(1)\n        IntExpr(2))))\n  ExpressionStmt:2(\n    IndexExpr:2(\n      NameExpr(x)\n      SliceExpr:2(\n        <empty>\n        IntExpr(1))))\n  ExpressionStmt:3(\n    IndexExpr:3(\n      NameExpr(x)\n      SliceExpr:3(\n        IntExpr(1)\n        <empty>)))\n  ExpressionStmt:4(\n    IndexExpr:4(\n      NameExpr(x)\n      SliceExpr:4(\n        <empty>\n        <empty>))))\n\n[case testSliceWithStride]\nx[1:2:3]\nx[1::2]\nx[:1:2]\nx[::2]\nx[1:2:]\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IndexExpr:1(\n      NameExpr(x)\n      SliceExpr:1(\n        IntExpr(1)\n        IntExpr(2)\n        IntExpr(3))))\n  ExpressionStmt:2(\n    IndexExpr:2(\n      NameExpr(x)\n      SliceExpr:2(\n        IntExpr(1)\n        <empty>\n        IntExpr(2))))\n  ExpressionStmt:3(\n    IndexExpr:3(\n      NameExpr(x)\n      SliceExpr:3(\n        <empty>\n        IntExpr(1)\n        IntExpr(2))))\n  ExpressionStmt:4(\n    IndexExpr:4(\n      NameExpr(x)\n      SliceExpr:4(\n        <empty>\n        <empty>\n        IntExpr(2))))\n  ExpressionStmt:5(\n    IndexExpr:5(\n      NameExpr(x)\n      SliceExpr:5(\n        IntExpr(1)\n        IntExpr(2)))))\n\n[case testYield]\ndef f():\n    yield x + 1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ExpressionStmt:2(\n        YieldExpr:2(\n          OpExpr:2(\n            +\n            NameExpr(x)\n            IntExpr(1)))))))\n\n[case testYieldFrom]\ndef f():\n    yield from h()\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ExpressionStmt:2(\n        YieldFromExpr:2(\n          CallExpr:2(\n            NameExpr(h)\n            Args()))))))\n\n[case testYieldFromAssignment]\ndef f():\n    a = yield from h()\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(a)\n        YieldFromExpr:2(\n          CallExpr:2(\n            NameExpr(h)\n            Args()))))))\n\n[case testDel]\ndel x\ndel x[0], y[1]\n[out]\nMypyFile:1(\n  DelStmt:1(\n    NameExpr(x))\n  DelStmt:2(\n    TupleExpr:2(\n      IndexExpr:2(\n        NameExpr(x)\n        IntExpr(0))\n      IndexExpr:2(\n        NameExpr(y)\n        IntExpr(1)))))\n\n[case testExtraCommas]\n1, 2,\n+[1, 2,]\nf(1,)\n{1:2,}\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    TupleExpr:1(\n      IntExpr(1)\n      IntExpr(2)))\n  ExpressionStmt:2(\n    UnaryExpr:2(\n      +\n      ListExpr:2(\n        IntExpr(1)\n        IntExpr(2))))\n  ExpressionStmt:3(\n    CallExpr:3(\n      NameExpr(f)\n      Args(\n        IntExpr(1))))\n  ExpressionStmt:4(\n    DictExpr:4(\n      IntExpr(1)\n      IntExpr(2))))\n\n[case testExtraCommaInFunc]\ndef f(x,):\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    Block:2(\n      PassStmt:2())))\n\n[case testLambda]\nlambda: 1\nlambda x: y + 1\nlambda x, y: 1\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    LambdaExpr:1(\n      Block:1(\n        ReturnStmt:1(\n          IntExpr(1)))))\n  ExpressionStmt:2(\n    LambdaExpr:2(\n      Args(\n        Var(x))\n      Block:2(\n        ReturnStmt:2(\n          OpExpr:2(\n            +\n            NameExpr(y)\n            IntExpr(1))))))\n  ExpressionStmt:3(\n    LambdaExpr:3(\n      Args(\n        Var(x)\n        Var(y))\n      Block:3(\n        ReturnStmt:3(\n          IntExpr(1))))))\n\n[case testComplexLambda]\nlambda x=2: x\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    LambdaExpr:1(\n      Args(\n        default(\n          Var(x)\n          IntExpr(2)))\n      Block:1(\n        ReturnStmt:1(\n          NameExpr(x))))))\n\n[case testLambdaPrecedence]\nlambda x: 1, 2\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    TupleExpr:1(\n      LambdaExpr:1(\n        Args(\n          Var(x))\n        Block:1(\n          ReturnStmt:1(\n            IntExpr(1))))\n      IntExpr(2))))\n\n[case testForIndicesInParens]\nfor (i, j) in x:\n  pass\n[out]\nMypyFile:1(\n  ForStmt:1(\n    TupleExpr:1(\n      NameExpr(i)\n      NameExpr(j))\n    NameExpr(x)\n    Block:2(\n      PassStmt:2())))\n\n[case testForAndTrailingCommaAfterIndexVar]\nfor i, in x:\n    pass\n[out]\nMypyFile:1(\n  ForStmt:1(\n    TupleExpr:1(\n      NameExpr(i))\n    NameExpr(x)\n    Block:2(\n      PassStmt:2())))\n\n[case testListComprehensionAndTrailingCommaAfterIndexVar]\nx = [a for b, in c]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    ListComprehension:1(\n      GeneratorExpr:1(\n        NameExpr(a)\n        TupleExpr:1(\n          NameExpr(b))\n        NameExpr(c)))))\n\n[case testForAndTrailingCommaAfterIndexVars]\nfor i, j, in x:\n    pass\n[out]\nMypyFile:1(\n  ForStmt:1(\n    TupleExpr:1(\n      NameExpr(i)\n      NameExpr(j))\n    NameExpr(x)\n    Block:2(\n      PassStmt:2())))\n\n[case testGeneratorWithCondition]\n(x for y in z if 0)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    GeneratorExpr:1(\n      NameExpr(x)\n      NameExpr(y)\n      NameExpr(z)\n      IntExpr(0))))\n\n[case testListComprehensionWithCondition]\nraise [x for y in z if 0]\n[out]\nMypyFile:1(\n  RaiseStmt:1(\n    ListComprehension:1(\n      GeneratorExpr:1(\n        NameExpr(x)\n        NameExpr(y)\n        NameExpr(z)\n        IntExpr(0)))))\n\n[case testListComprehensionWithConditions]\nraise [x for y in z if 0 if 1]\n[out]\nMypyFile:1(\n  RaiseStmt:1(\n    ListComprehension:1(\n      GeneratorExpr:1(\n        NameExpr(x)\n        NameExpr(y)\n        NameExpr(z)\n        IntExpr(0)\n        IntExpr(1)))))\n\n[case testListComprehensionWithCrazyConditions]\nraise [x for y in z if (1 if 2 else 3) if 1]\n[out]\nMypyFile:1(\n  RaiseStmt:1(\n    ListComprehension:1(\n      GeneratorExpr:1(\n        NameExpr(x)\n        NameExpr(y)\n        NameExpr(z)\n        ConditionalExpr:1(\n          Condition(\n            IntExpr(2))\n          IntExpr(1)\n          IntExpr(3))\n        IntExpr(1)))))\n\n[case testDictionaryComprehension]\na = {x: y for x, y in xys}\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    DictionaryComprehension:1(\n      NameExpr(x)\n      NameExpr(y)\n      TupleExpr:1(\n        NameExpr(x)\n        NameExpr(y))\n      NameExpr(xys))))\n\n[case testDictionaryComprehensionComplex]\na = {x: y for x, y in xys for p, q in pqs if c}\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    DictionaryComprehension:1(\n      NameExpr(x)\n      NameExpr(y)\n      TupleExpr:1(\n        NameExpr(x)\n        NameExpr(y))\n      TupleExpr:1(\n        NameExpr(p)\n        NameExpr(q))\n      NameExpr(xys)\n      NameExpr(pqs)\n      NameExpr(c))))\n\n[case testSetComprehension]\na = {i for i in l}\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    SetComprehension:1(\n      GeneratorExpr:1(\n        NameExpr(i)\n        NameExpr(i)\n        NameExpr(l)))))\n\n[case testSetComprehensionComplex]\na = {x + p for x in xys for p in pqs if c}\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    SetComprehension:1(\n      GeneratorExpr:1(\n        OpExpr:1(\n          +\n          NameExpr(x)\n          NameExpr(p))\n        NameExpr(x)\n        NameExpr(p)\n        NameExpr(xys)\n        NameExpr(pqs)\n        NameExpr(c)))))\n\n[case testWithStatement]\nwith open('foo') as f:\n  pass\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      CallExpr:1(\n        NameExpr(open)\n        Args(\n          StrExpr(foo))))\n    Target(\n      NameExpr(f))\n    Block:2(\n      PassStmt:2())))\n\n[case testWithStatementWithoutTarget]\nwith foo:\n  pass\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      NameExpr(foo))\n    Block:2(\n      PassStmt:2())))\n\n[case testHexOctBinLiterals]\n0xa, 0Xaf, 0o7, 0O12, 0b1, 0B101\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    TupleExpr:1(\n      IntExpr(10)\n      IntExpr(175)\n      IntExpr(7)\n      IntExpr(10)\n      IntExpr(1)\n      IntExpr(5))))\n\n[case testImportFromWithParens]\nfrom x import (y)\nfrom x import (y,\n               z)\n[out]\nMypyFile:1(\n  ImportFrom:1(x, [y])\n  ImportFrom:2(x, [y, z]))\n\n[case testContinueStmt]\nwhile 1:\n  continue\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(1)\n    Block:2(\n      ContinueStmt:2())))\n\n[case testStrLiteralConcatenate]\n'f' 'bar'\n('x'\n 'y'\n 'z')\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StrExpr(fbar))\n  ExpressionStmt:2(\n    StrExpr(xyz)))\n\n[case testCatchAllExcept]\ntry:\n  1\nexcept:\n  pass\ntry:\n  1\nexcept x:\n  pass\nexcept:\n  2\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      ExpressionStmt:2(\n        IntExpr(1)))\n    Block:4(\n      PassStmt:4()))\n  TryStmt:5(\n    Block:6(\n      ExpressionStmt:6(\n        IntExpr(1)))\n    NameExpr(x)\n    Block:8(\n      PassStmt:8())\n    Block:10(\n      ExpressionStmt:10(\n        IntExpr(2)))))\n\n[case testTryElse]\ntry:\n  pass\nexcept x:\n  1\nelse:\n  2\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    NameExpr(x)\n    Block:4(\n      ExpressionStmt:4(\n        IntExpr(1)))\n    Else(\n      ExpressionStmt:6(\n        IntExpr(2)))))\n\n[case testExceptWithMultipleTypes]\ntry:\n  pass\nexcept (x, y):\n  pass\nexcept (a, b, c) as e:\n  pass\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    TupleExpr:3(\n      NameExpr(x)\n      NameExpr(y))\n    Block:4(\n      PassStmt:4())\n    TupleExpr:5(\n      NameExpr(a)\n      NameExpr(b)\n      NameExpr(c))\n    NameExpr(e)\n    Block:6(\n      PassStmt:6())))\n\n[case testNestedFunctions]\ndef f():\n  def g():\n    pass\ndef h() -> int:\n  def g() -> int:\n    pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      FuncDef:2(\n        g\n        Block:3(\n          PassStmt:3()))))\n  FuncDef:4(\n    h\n    def () -> int?\n    Block:5(\n      FuncDef:5(\n        g\n        def () -> int?\n        Block:6(\n          PassStmt:6())))))\n\n[case testStatementsAndDocStringsInClassBody]\nclass A:\n  \"doc string\"\n  x = y\n  def f(self):\n    pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    ExpressionStmt:2(\n      StrExpr(doc string))\n    AssignmentStmt:3(\n      NameExpr(x)\n      NameExpr(y))\n    FuncDef:4(\n      f\n      Args(\n        Var(self))\n      Block:5(\n        PassStmt:5()))))\n\n[case testSingleLineClass]\nclass a: pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    a\n    PassStmt:1()))\n\n[case testDecorator]\n@property\ndef f():\n  pass\n[out]\nMypyFile:1(\n  Decorator:1(\n    Var(f)\n    NameExpr(property)\n    FuncDef:2(\n      f\n      Block:3(\n        PassStmt:3()))))\n\n[case testComplexDecorator]\n@foo(bar, 1)\n@zar\ndef f() -> int:\n  pass\n[out]\nMypyFile:1(\n  Decorator:1(\n    Var(f)\n    CallExpr:1(\n      NameExpr(foo)\n      Args(\n        NameExpr(bar)\n        IntExpr(1)))\n    NameExpr(zar)\n    FuncDef:3(\n      f\n      def () -> int?\n      Block:4(\n        PassStmt:4()))))\n\n[case testKeywordArgInCall]\nf(x=1)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    CallExpr:1(\n      NameExpr(f)\n      Args()\n      KwArgs(\n        x\n        IntExpr(1)))))\n\n[case testComplexKeywordArgs]\nf(x, y=1 or 2, z=y)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    CallExpr:1(\n      NameExpr(f)\n      Args(\n        NameExpr(x))\n      KwArgs(\n        y\n        OpExpr:1(\n          or\n          IntExpr(1)\n          IntExpr(2)))\n      KwArgs(\n        z\n        NameExpr(y)))))\n\n[case testChainedAssignment]\nx = z = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x)\n      NameExpr(z))\n    IntExpr(1)))\n\n[case testVarArgs]\ndef f(x, *a): pass\nf(1, *2)\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    VarArg(\n      Var(a))\n    Block:1(\n      PassStmt:1()))\n  ExpressionStmt:2(\n    CallExpr:2(\n      NameExpr(f)\n      Args(\n        IntExpr(1)\n        IntExpr(2))\n      VarArg)))\n\n[case testVarArgWithType]\ndef f(x: str, *a: int): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: str?, *a: int?) -> Any\n    VarArg(\n      Var(a))\n    Block:1(\n      PassStmt:1())))\n\n[case testDictVarArgs]\ndef f(x, **a): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    DictVarArg(\n      Var(a))\n    Block:1(\n      PassStmt:1())))\n\n[case testBothVarArgs]\ndef f(x, *a, **b): pass\ndef g(*a, **b): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    VarArg(\n      Var(a))\n    DictVarArg(\n      Var(b))\n    Block:1(\n      PassStmt:1()))\n  FuncDef:2(\n    g\n    VarArg(\n      Var(a))\n    DictVarArg(\n      Var(b))\n    Block:2(\n      PassStmt:2())))\n\n[case testDictVarArgsWithType]\ndef f(x: X, **a: A) -> None: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: X?, **a: A?) -> None?\n    DictVarArg(\n      Var(a))\n    Block:1(\n      PassStmt:1())))\n\n[case testCallDictVarArgs]\nf(**x)\nf(x, **y)\nf(*x, **y)\nf(x, *y, **z)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    CallExpr:1(\n      NameExpr(f)\n      Args()\n      DictVarArg(\n        NameExpr(x))))\n  ExpressionStmt:2(\n    CallExpr:2(\n      NameExpr(f)\n      Args(\n        NameExpr(x))\n      DictVarArg(\n        NameExpr(y))))\n  ExpressionStmt:3(\n    CallExpr:3(\n      NameExpr(f)\n      Args(\n        NameExpr(x))\n      VarArg\n      DictVarArg(\n        NameExpr(y))))\n  ExpressionStmt:4(\n    CallExpr:4(\n      NameExpr(f)\n      Args(\n        NameExpr(x)\n        NameExpr(y))\n      VarArg\n      DictVarArg(\n        NameExpr(z)))))\n\n[case testAssert]\nassert x == y\n[out]\nMypyFile:1(\n  AssertStmt:1(\n    ComparisonExpr:1(\n      ==\n      NameExpr(x)\n      NameExpr(y))))\n\n[case testYieldWithoutExpressions]\ndef f():\n  yield\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ExpressionStmt:2(\n        YieldExpr:2()))))\n\n[case testConditionalExpression]\nx if y else z\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    ConditionalExpr:1(\n      Condition(\n        NameExpr(y))\n      NameExpr(x)\n      NameExpr(z))))\n\n[case testConditionalExpressionInListComprehension]\na = [x if y else z for a in b]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    ListComprehension:1(\n      GeneratorExpr:1(\n        ConditionalExpr:1(\n          Condition(\n            NameExpr(y))\n          NameExpr(x)\n          NameExpr(z))\n        NameExpr(a)\n        NameExpr(b)))))\n\n[case testConditionalExpressionInTuple]\n1 if 2 else 3, 4\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    TupleExpr:1(\n      ConditionalExpr:1(\n        Condition(\n          IntExpr(2))\n        IntExpr(1)\n        IntExpr(3))\n      IntExpr(4))))\n\n[case testSetLiteral]\n{x or y}\n{1, 2}\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    SetExpr:1(\n      OpExpr:1(\n        or\n        NameExpr(x)\n        NameExpr(y))))\n  ExpressionStmt:2(\n    SetExpr:2(\n      IntExpr(1)\n      IntExpr(2))))\n\n[case testSetLiteralWithExtraComma]\n{x,}\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    SetExpr:1(\n      NameExpr(x))))\n\n[case testImportAs]\nimport x as y\nimport x, z as y, a.b as c, d as d\n[out]\nMypyFile:1(\n  Import:1(x : y)\n  Import:2(x, z : y, a.b : c, d : d))\n\n[case testForAndElse]\nfor x in y:\n  pass\nelse:\n  x\n[out]\nMypyFile:1(\n  ForStmt:1(\n    NameExpr(x)\n    NameExpr(y)\n    Block:2(\n      PassStmt:2())\n    Else(\n      ExpressionStmt:4(\n        NameExpr(x)))))\n\n[case testWhileAndElse]\nwhile x:\n  pass\nelse:\n  y\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    NameExpr(x)\n    Block:2(\n      PassStmt:2())\n    Else(\n      ExpressionStmt:4(\n        NameExpr(y)))))\n\n[case testWithAndMultipleOperands]\nwith x as y, a as b:\n  pass\nwith x(), y():\n  pass\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      NameExpr(x))\n    Target(\n      NameExpr(y))\n    Expr(\n      NameExpr(a))\n    Target(\n      NameExpr(b))\n    Block:2(\n      PassStmt:2()))\n  WithStmt:3(\n    Expr(\n      CallExpr:3(\n        NameExpr(x)\n        Args()))\n    Expr(\n      CallExpr:3(\n        NameExpr(y)\n        Args()))\n    Block:4(\n      PassStmt:4())))\n\n[case testOperatorAssignment]\nx += 1\nx -= 1\nx *= 1\nx /= 1\nx //= 1\nx %= 1\nx **= 1\nx |= 1\nx &= 1\nx ^= 1\nx >>= 1\nx <<= 1\n[out]\nMypyFile:1(\n  OperatorAssignmentStmt:1(\n    +\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:2(\n    -\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:3(\n    *\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:4(\n    /\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:5(\n    //\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:6(\n    %\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:7(\n    **\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:8(\n    |\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:9(\n    &\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:10(\n    ^\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:11(\n    >>\n    NameExpr(x)\n    IntExpr(1))\n  OperatorAssignmentStmt:12(\n    <<\n    NameExpr(x)\n    IntExpr(1)))\n\n[case testNestedClasses]\nclass A:\n  class B:\n    pass\n  class C:\n    pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    ClassDef:2(\n      B\n      PassStmt:3())\n    ClassDef:4(\n      C\n      PassStmt:5())))\n\n[case testTryWithExceptAndFinally]\ntry:\n  pass\nexcept x:\n  x\nfinally:\n  y\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    NameExpr(x)\n    Block:4(\n      ExpressionStmt:4(\n        NameExpr(x)))\n    Finally(\n      ExpressionStmt:6(\n        NameExpr(y)))))\n\n[case testBareAsteriskInFuncDef]\ndef f(x, *, y=1): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    MaxPos(1)\n    Args(\n      Var(x)\n      default(\n        Var(y)\n        IntExpr(1)))\n    Block:1(\n      PassStmt:1())))\n\n[case testBareAsteriskInFuncDefWithSignature]\ndef f(x: A, *, y: B = 1) -> None: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    MaxPos(1)\n    Args(\n      Var(x)\n      default(\n        Var(y)\n        IntExpr(1)))\n    def (x: A?, *, y: B? =) -> None?\n    Block:1(\n      PassStmt:1())))\n\n[case testBareAsteriskNamedDefault]\ndef f(*, y: B = 1) -> None: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    MaxPos(0)\n    Args(\n      default(\n        Var(y)\n        IntExpr(1)))\n    def (*, y: B? =) -> None?\n    Block:1(\n      PassStmt:1())))\n\n[case testBareAsteriskNamedNoDefault]\ndef f(*, y: B) -> None: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    MaxPos(0)\n    Args(\n      Var(y))\n    def (*, y: B?) -> None?\n    Block:1(\n      PassStmt:1())))\n\n[case testSuperExpr]\nsuper().x\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    SuperExpr:1(\n      x\n      CallExpr:1(\n        NameExpr(super)\n        Args()))))\n\n[case testKeywordAndDictArgs]\nf(x = y, **kwargs)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    CallExpr:1(\n      NameExpr(f)\n      Args()\n      KwArgs(\n        x\n        NameExpr(y))\n      DictVarArg(\n        NameExpr(kwargs)))))\n\n[case testSimpleFunctionType]\nf = None # type: Callable[[], None]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(f)\n    NameExpr(None)\n    Callable?[<TypeList >, None?]))\n\n[case testFunctionTypeWithArgument]\nf = None # type: Callable[[str], int]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(f)\n    NameExpr(None)\n    Callable?[<TypeList str?>, int?]))\n\n[case testFunctionTypeWithTwoArguments]\nf = None # type: Callable[[a[b], x.y], List[int]]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(f)\n    NameExpr(None)\n    Callable?[<TypeList a?[b?], x.y?>, List?[int?]]))\n\n[case testFunctionTypeWithExtraComma]\ndef f(x: Callable[[str,], int]): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: Callable?[<TypeList str?>, int?]) -> Any\n    Block:1(\n      PassStmt:1())))\n\n[case testSimpleStringLiteralType]\ndef f() -> 'A': pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> A?\n    Block:1(\n      PassStmt:1())))\n\n[case testGenericStringLiteralType]\ndef f() -> 'A[B, C]': pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> A?[B?, C?]\n    Block:1(\n      PassStmt:1())))\n\n[case testPartialStringLiteralType]\ndef f() -> A['B', C]: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> A?[B?, C?]\n    Block:1(\n      PassStmt:1())))\n\n[case testWhitespaceInStringLiteralType]\ndef f() -> '  A  [  X  ]  ': pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> A?[X?]\n    Block:1(\n      PassStmt:1())))\n\n[case testEscapeInStringLiteralType]\ndef f() -> '\\x41': pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> A?\n    Block:1(\n      PassStmt:1())))\n\n[case testMetaclass]\nclass Foo(metaclass=Bar): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Foo\n    Metaclass(NameExpr(Bar))\n    PassStmt:1()))\n\n[case testQualifiedMetaclass]\nclass Foo(metaclass=foo.Bar): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Foo\n    Metaclass(MemberExpr:1(\n      NameExpr(foo)\n      Bar))\n    PassStmt:1()))\n\n[case testBaseAndMetaclass]\nclass Foo(foo.bar[x], metaclass=Bar): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Foo\n    Metaclass(NameExpr(Bar))\n    BaseTypeExpr(\n      IndexExpr:1(\n        MemberExpr:1(\n          NameExpr(foo)\n          bar)\n        NameExpr(x)))\n    PassStmt:1()))\n\n[case testClassKeywordArgs]\nclass Foo(_root=None): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Foo\n    PassStmt:1()))\n\n[case testClassKeywordArgsBeforeMeta]\nclass Foo(_root=None, metaclass=Bar): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Foo\n    Metaclass(NameExpr(Bar))\n    PassStmt:1()))\n\n[case testClassKeywordArgsAfterMeta]\nclass Foo(metaclass=Bar, _root=None): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Foo\n    Metaclass(NameExpr(Bar))\n    PassStmt:1()))\n\n[case testNamesThatAreNoLongerKeywords]\nany = interface\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(any)\n    NameExpr(interface)))\n\n[case testFunctionOverload]\n@overload\ndef f() -> x: pass\n@overload\ndef f() -> y: pass\n[out]\nMypyFile:1(\n  OverloadedFuncDef:1(\n    Decorator:1(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:2(\n        f\n        def () -> x?\n        Block:2(\n          PassStmt:2())))\n    Decorator:3(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:4(\n        f\n        def () -> y?\n        Block:4(\n          PassStmt:4())))))\n\n[case testFunctionOverloadAndOtherStatements]\nx\n@overload\ndef f() -> x: pass\n@overload\ndef f() -> y: pass\nx\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    NameExpr(x))\n  OverloadedFuncDef:2(\n    Decorator:2(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:3(\n        f\n        def () -> x?\n        Block:3(\n          PassStmt:3())))\n    Decorator:4(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:5(\n        f\n        def () -> y?\n        Block:5(\n          PassStmt:5()))))\n  ExpressionStmt:6(\n    NameExpr(x)))\n\n[case testFunctionOverloadWithThreeVariants]\n@overload\ndef f() -> x: pass\n@overload\ndef f() -> y: pass\n@overload\ndef f(y): pass\n[out]\nMypyFile:1(\n  OverloadedFuncDef:1(\n    Decorator:1(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:2(\n        f\n        def () -> x?\n        Block:2(\n          PassStmt:2())))\n    Decorator:3(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:4(\n        f\n        def () -> y?\n        Block:4(\n          PassStmt:4())))\n    Decorator:5(\n      Var(f)\n      NameExpr(overload)\n      FuncDef:6(\n        f\n        Args(\n          Var(y))\n        Block:6(\n          PassStmt:6())))))\n\n[case testDecoratorsThatAreNotOverloads]\n@foo\ndef f() -> x: pass\n@foo\ndef g() -> y: pass\n[out]\nMypyFile:1(\n  Decorator:1(\n    Var(f)\n    NameExpr(foo)\n    FuncDef:2(\n      f\n      def () -> x?\n      Block:2(\n        PassStmt:2())))\n  Decorator:3(\n    Var(g)\n    NameExpr(foo)\n    FuncDef:4(\n      g\n      def () -> y?\n      Block:4(\n        PassStmt:4()))))\n\n[case testFunctionOverloadWithinFunction]\ndef f():\n    @overload\n    def g(): pass\n    @overload\n    def g() -> x: pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      OverloadedFuncDef:2(\n        Decorator:2(\n          Var(g)\n          NameExpr(overload)\n          FuncDef:3(\n            g\n            Block:3(\n              PassStmt:3())))\n        Decorator:4(\n          Var(g)\n          NameExpr(overload)\n          FuncDef:5(\n            g\n            def () -> x?\n            Block:5(\n              PassStmt:5())))))))\n\n[case testCommentFunctionAnnotation]\ndef f(): # type: () -> A\n  pass\ndef g(x): # type: (A) -> B\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def () -> A?\n    Block:2(\n      PassStmt:2()))\n  FuncDef:3(\n    g\n    Args(\n      Var(x))\n    def (x: A?) -> B?\n    Block:4(\n      PassStmt:4())))\n\n[case testCommentMethodAnnotation]\nclass A:\n  def f(self): # type: () -> A\n    pass\n  def g(xself, x): # type: (A) -> B\n    pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      f\n      Args(\n        Var(self))\n      def (self: Any) -> A?\n      Block:3(\n        PassStmt:3()))\n    FuncDef:4(\n      g\n      Args(\n        Var(xself)\n        Var(x))\n      def (xself: Any, x: A?) -> B?\n      Block:5(\n        PassStmt:5()))))\n\n[case testCommentMethodAnnotationAndNestedFunction]\nclass A:\n  def f(self): # type: () -> A\n    def g(x): # type: (A) -> B\n      pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      f\n      Args(\n        Var(self))\n      def (self: Any) -> A?\n      Block:3(\n        FuncDef:3(\n          g\n          Args(\n            Var(x))\n          def (x: A?) -> B?\n          Block:4(\n            PassStmt:4()))))))\n\n[case testCommentFunctionAnnotationOnSeparateLine]\ndef f(x):\n  # type: (X) -> Y\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: X?) -> Y?\n    Block:3(\n      PassStmt:3())))\n\n[case testCommentFunctionAnnotationOnSeparateLine2]\ndef f(x):\n\n     # type: (X) -> Y       # bar\n\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: X?) -> Y?\n    Block:5(\n      PassStmt:5())))\n\n[case testCommentFunctionAnnotationAndVarArg]\ndef f(x, *y): # type: (X, *Y) -> Z\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: X?, *y: Y?) -> Z?\n    VarArg(\n      Var(y))\n    Block:2(\n      PassStmt:2())))\n\n[case testCommentFunctionAnnotationAndAllVarArgs]\ndef f(x, *y, **z): # type: (X, *Y, **Z) -> A\n  pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    def (x: X?, *y: Y?, **z: Z?) -> A?\n    VarArg(\n      Var(y))\n    DictVarArg(\n      Var(z))\n    Block:2(\n      PassStmt:2())))\n\n[case testClassDecorator]\n@foo\nclass X: pass\n@foo(bar)\n@x.y\nclass Z: pass\n[out]\nMypyFile:1(\n  ClassDef:2(\n    X\n    Decorators(\n      NameExpr(foo))\n    PassStmt:2())\n  ClassDef:5(\n    Z\n    Decorators(\n      CallExpr:3(\n        NameExpr(foo)\n        Args(\n          NameExpr(bar)))\n      MemberExpr:4(\n        NameExpr(x)\n        y))\n    PassStmt:5()))\n\n[case testTrailingSemicolon]\ndef x():\n    pass;\n\ndef y():\n    pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    x\n    Block:2(\n      PassStmt:2()))\n  FuncDef:4(\n    y\n    Block:5(\n      PassStmt:5())))\n\n[case testEmptySuperClass]\nclass A():\n    pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    PassStmt:2()))\n\n[case testStarExpression]\n*a\n*a, b\na, *b\na, (*x, y)\na, (x, *y)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StarExpr:1(\n      NameExpr(a)))\n  ExpressionStmt:2(\n    TupleExpr:2(\n      StarExpr:2(\n        NameExpr(a))\n      NameExpr(b)))\n  ExpressionStmt:3(\n    TupleExpr:3(\n      NameExpr(a)\n      StarExpr:3(\n        NameExpr(b))))\n  ExpressionStmt:4(\n    TupleExpr:4(\n      NameExpr(a)\n      TupleExpr:4(\n        StarExpr:4(\n          NameExpr(x))\n        NameExpr(y))))\n  ExpressionStmt:5(\n    TupleExpr:5(\n      NameExpr(a)\n      TupleExpr:5(\n        NameExpr(x)\n        StarExpr:5(\n          NameExpr(y))))))\n\n[case testStarExpressionParenthesis]\n*(a)\n*(a,b)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    StarExpr:1(\n      NameExpr(a)))\n  ExpressionStmt:2(\n    StarExpr:2(\n      TupleExpr:2(\n        NameExpr(a)\n        NameExpr(b)))))\n\n[case testStarExpressionInFor]\nfor *a in b:\n    pass\n\nfor a, *b in c:\n    pass\n\nfor *a, b in c:\n    pass\n[out]\nMypyFile:1(\n  ForStmt:1(\n    StarExpr:1(\n      NameExpr(a))\n    NameExpr(b)\n    Block:2(\n      PassStmt:2()))\n  ForStmt:4(\n    TupleExpr:4(\n      NameExpr(a)\n      StarExpr:4(\n        NameExpr(b)))\n    NameExpr(c)\n    Block:5(\n      PassStmt:5()))\n  ForStmt:7(\n    TupleExpr:7(\n      StarExpr:7(\n        NameExpr(a))\n      NameExpr(b))\n    NameExpr(c)\n    Block:8(\n      PassStmt:8())))\n\n[case testStarExprInGeneratorExpr]\n(x for y, *p in z)\n(x for *p, y in z)\n(x for y, *p, q in z)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    GeneratorExpr:1(\n      NameExpr(x)\n      TupleExpr:1(\n        NameExpr(y)\n        StarExpr:1(\n          NameExpr(p)))\n      NameExpr(z)))\n  ExpressionStmt:2(\n    GeneratorExpr:2(\n      NameExpr(x)\n      TupleExpr:2(\n        StarExpr:2(\n          NameExpr(p))\n        NameExpr(y))\n      NameExpr(z)))\n  ExpressionStmt:3(\n    GeneratorExpr:3(\n      NameExpr(x)\n      TupleExpr:3(\n        NameExpr(y)\n        StarExpr:3(\n          NameExpr(p))\n        NameExpr(q))\n      NameExpr(z))))\n\n[case testParseNamedtupleBaseclass]\nclass A(namedtuple('x', ['y'])): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    BaseTypeExpr(\n      CallExpr:1(\n        NameExpr(namedtuple)\n        Args(\n          StrExpr(x)\n          ListExpr:1(\n            StrExpr(y)))))\n    PassStmt:1()))\n\n[case testEllipsis]\n...\na[1,...,2]\n....__class__\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    Ellipsis)\n  ExpressionStmt:2(\n    IndexExpr:2(\n      NameExpr(a)\n      TupleExpr:2(\n        IntExpr(1)\n        Ellipsis\n        IntExpr(2))))\n  ExpressionStmt:3(\n    MemberExpr:3(\n      Ellipsis\n      __class__)))\n\n[case testFunctionWithManyKindsOfArgs]\ndef f(x, *args,  y=None, **kw): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    MaxPos(1)\n    Args(\n      Var(x)\n      default(\n        Var(y)\n        NameExpr(None)))\n    VarArg(\n      Var(args))\n    DictVarArg(\n      Var(kw))\n    Block:1(\n      PassStmt:1())))\n\n[case testIfWithSemicolons]\nif 1: a; b\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      ExpressionStmt:1(\n        NameExpr(a))\n      ExpressionStmt:1(\n        NameExpr(b)))))\n\n[case testIfWithSemicolonsNested]\nwhile 2:\n    if 1: a; b\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(2)\n    Block:2(\n      IfStmt:2(\n        If(\n          IntExpr(1))\n        Then(\n          ExpressionStmt:2(\n            NameExpr(a))\n          ExpressionStmt:2(\n            NameExpr(b)))))))\n\n[case testIfElseWithSemicolons]\nif 1: global x; y = 1\nelse: x = 1; return 3\n4\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      GlobalDecl:1(\n        x)\n      AssignmentStmt:1(\n        NameExpr(y)\n        IntExpr(1)))\n    Else(\n      AssignmentStmt:2(\n        NameExpr(x)\n        IntExpr(1))\n      ReturnStmt:2(\n        IntExpr(3))))\n  ExpressionStmt:3(\n    IntExpr(4)))\n\n[case testIfElseWithSemicolonsNested]\nwhile 2:\n    if 1: global x; y = 1\n    else: x = 1; return 3\n4\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(2)\n    Block:2(\n      IfStmt:2(\n        If(\n          IntExpr(1))\n        Then(\n          GlobalDecl:2(\n            x)\n          AssignmentStmt:2(\n            NameExpr(y)\n            IntExpr(1)))\n        Else(\n          AssignmentStmt:3(\n            NameExpr(x)\n            IntExpr(1))\n          ReturnStmt:3(\n            IntExpr(3))))))\n  ExpressionStmt:4(\n    IntExpr(4)))\n\n[case testKeywordArgumentAfterStarArgumentInCall]\nf(x=1, *y)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    CallExpr:1(\n      NameExpr(f)\n      Args(\n        NameExpr(y))\n      VarArg\n      KwArgs(\n        x\n        IntExpr(1)))))\n\n[case testConditionalExpressionInSetComprehension]\n{ 1 if x else 2 for x in y }\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    SetComprehension:1(\n      GeneratorExpr:1(\n        ConditionalExpr:1(\n          Condition(\n            NameExpr(x))\n          IntExpr(1)\n          IntExpr(2))\n        NameExpr(x)\n        NameExpr(y)))))\n\n[case testConditionalExpressionInListComprehension2]\na = [ 1 if x else 2 for x in y ]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a)\n    ListComprehension:1(\n      GeneratorExpr:1(\n        ConditionalExpr:1(\n          Condition(\n            NameExpr(x))\n          IntExpr(1)\n          IntExpr(2))\n        NameExpr(x)\n        NameExpr(y)))))\n\n[case testComplexWithLvalue]\nwith x as y.z: pass\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      NameExpr(x))\n    Target(\n      MemberExpr:1(\n        NameExpr(y)\n        z))\n    Block:1(\n      PassStmt:1())))\n\n[case testRelativeImportWithEllipsis]\nfrom ... import x\n[out]\nMypyFile:1(\n  ImportFrom:1(..., [x]))\n\n[case testRelativeImportWithEllipsis2]\nfrom .... import x\n[out]\nMypyFile:1(\n  ImportFrom:1(...., [x]))\n\n[case testParseExtendedSlicing]\na[:, :]\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IndexExpr:1(\n      NameExpr(a)\n      TupleExpr:1(\n        SliceExpr:1(\n          <empty>\n          <empty>)\n        SliceExpr:1(\n          <empty>\n          <empty>)))))\n\n[case testParseExtendedSlicing2]\na[1:2:, :,]\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IndexExpr:1(\n      NameExpr(a)\n      TupleExpr:1(\n        SliceExpr:1(\n          IntExpr(1)\n          IntExpr(2))\n        SliceExpr:1(\n          <empty>\n          <empty>)))))\n\n[case testParseExtendedSlicing3]\na[1:2:3, ..., 1]\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    IndexExpr:1(\n      NameExpr(a)\n      TupleExpr:1(\n        SliceExpr:1(\n          IntExpr(1)\n          IntExpr(2)\n          IntExpr(3))\n        Ellipsis\n        IntExpr(1)))))\n\n[case testParseExtendedSlicing4]\nm[*index, :]\n[out]\nmain:1: error: invalid syntax\n[out version>=3.11]\nMypyFile:1(\n  ExpressionStmt:1(\n    IndexExpr:1(\n      NameExpr(m)\n      TupleExpr:1(\n        StarExpr:1(\n          NameExpr(index))\n        SliceExpr:1(\n          <empty>\n          <empty>)))))\n\n[case testParseIfExprInDictExpr]\ntest =  { 'spam': 'eggs' if True else 'bacon' }\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(test)\n    DictExpr:1(\n      StrExpr(spam)\n      ConditionalExpr:1(\n        Condition(\n          NameExpr(True))\n        StrExpr(eggs)\n        StrExpr(bacon)))))\n\n[case testIgnoreLine]\nimport x # type: ignore\n[out]\nMypyFile:1(\n  Import:1(x)\n  IgnoredLines(1))\n\n[case testIgnore2Lines]\nx\ny # type: ignore\nz # type: ignore\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    NameExpr(x))\n  ExpressionStmt:2(\n    NameExpr(y))\n  ExpressionStmt:3(\n    NameExpr(z))\n  IgnoredLines(2, 3))\n\n[case testCommentedOutIgnoreAnnotation]\ny ## type: ignore\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    NameExpr(y)))\n\n[case testSpaceInIgnoreAnnotations]\ny #  type:  ignore    # foo\ny #type:ignore\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    NameExpr(y))\n  ExpressionStmt:2(\n    NameExpr(y))\n  IgnoredLines(1, 2))\n\n[case testIgnoreAnnotationAndMultilineStatement]\nx = {\n  1: 2  # type: ignore\n}\ny = {   # type: ignore\n  1: 2\n}       # type: ignore\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    DictExpr:1(\n      IntExpr(1)\n      IntExpr(2)))\n  AssignmentStmt:4(\n    NameExpr(y)\n    DictExpr:4(\n      IntExpr(1)\n      IntExpr(2)))\n  IgnoredLines(2, 4, 6))\n\n[case testIgnoreAnnotationAndMultilineStatement2]\nfrom m import ( # type: ignore\n  x, y\n)\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [x, y])\n  IgnoredLines(1))\n\n[case testYieldExpression]\ndef f():\n    x = yield f()\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(x)\n        YieldExpr:2(\n          CallExpr:2(\n            NameExpr(f)\n            Args()))))))\n\n[case testForWithSingleItemTuple]\nfor x in 1,: pass\n[out]\nMypyFile:1(\n  ForStmt:1(\n    NameExpr(x)\n    TupleExpr:1(\n      IntExpr(1))\n    Block:1(\n      PassStmt:1())))\n\n[case testIsoLatinUnixEncoding]\n# coding: iso-latin-1-unix\n[out]\nMypyFile:1()\n\n[case testLatinUnixEncoding]\n# coding: latin-1-unix\n[out]\nMypyFile:1()\n\n[case testLatinUnixEncoding2]\n# coding: iso-latin-1\n[out]\nMypyFile:1()\n\n[case testYieldExpressionInParens]\ndef f():\n    (yield)\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ExpressionStmt:2(\n        YieldExpr:2()))))\n\n[case testFStringSimple]\nx = 'mypy'\nf'Hello {x}'\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    StrExpr(mypy))\n  ExpressionStmt:2(\n    CallExpr:2(\n      MemberExpr:2(\n        StrExpr()\n        join)\n      Args(\n        ListExpr:2(\n          StrExpr(Hello )\n          CallExpr:2(\n            MemberExpr:2(\n              StrExpr({:{}})\n              format)\n            Args(\n              NameExpr(x)\n              StrExpr())))))))\n\n[case testFStringWithConversion]\nx = 'mypy'\nF'Hello {x!r}'\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    StrExpr(mypy))\n  ExpressionStmt:2(\n    CallExpr:2(\n      MemberExpr:2(\n        StrExpr()\n        join)\n      Args(\n        ListExpr:2(\n          StrExpr(Hello )\n          CallExpr:2(\n            MemberExpr:2(\n              StrExpr({!r:{}})\n              format)\n            Args(\n              NameExpr(x)\n              StrExpr())))))))\n\n[case testFStringWithOnlyFormatSpecifier]\nx = 'mypy'\nf'Hello {x:<30}'\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    StrExpr(mypy))\n  ExpressionStmt:2(\n    CallExpr:2(\n      MemberExpr:2(\n        StrExpr()\n        join)\n      Args(\n        ListExpr:2(\n          StrExpr(Hello )\n          CallExpr:2(\n            MemberExpr:2(\n              StrExpr({:{}})\n              format)\n            Args(\n              NameExpr(x)\n              StrExpr(<30))))))))\n\n[case testFStringWithFormatSpecifierAndConversion]\nx = 'mypy'\nf'Hello {x!s:<30}'\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    StrExpr(mypy))\n  ExpressionStmt:2(\n    CallExpr:2(\n      MemberExpr:2(\n        StrExpr()\n        join)\n      Args(\n        ListExpr:2(\n          StrExpr(Hello )\n          CallExpr:2(\n            MemberExpr:2(\n              StrExpr({!s:{}})\n              format)\n            Args(\n              NameExpr(x)\n              StrExpr(<30))))))))\n\n[case testFStringWithFormatSpecifierExpression]\nx = 'mypy'\ny = 30\nf'Hello {x!s:<{y+y}}'\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x)\n    StrExpr(mypy))\n  AssignmentStmt:2(\n    NameExpr(y)\n    IntExpr(30))\n  ExpressionStmt:3(\n    CallExpr:3(\n      MemberExpr:3(\n        StrExpr()\n        join)\n      Args(\n        ListExpr:3(\n          StrExpr(Hello )\n          CallExpr:3(\n            MemberExpr:3(\n              StrExpr({!s:{}})\n              format)\n            Args(\n              NameExpr(x)\n              CallExpr:3(\n                MemberExpr:3(\n                  StrExpr()\n                  join)\n                Args(\n                  ListExpr:3(\n                    StrExpr(<)\n                    CallExpr:3(\n                      MemberExpr:3(\n                        StrExpr({:{}})\n                        format)\n                      Args(\n                        OpExpr:3(\n                          +\n                          NameExpr(y)\n                          NameExpr(y))\n                        StrExpr()))))))))))))\n\n[case testStripFunctionBodiesIfIgnoringErrors]\n# mypy: ignore-errors=True\ndef f(self):\n    self.x = 1  # Cannot define an attribute\n    return 1\n[out]\nMypyFile:1(\n  FuncDef:2(\n    f\n    Args(\n      Var(self))\n    Block:3()))\n\n[case testStripMethodBodiesIfIgnoringErrors]\n# mypy: ignore-errors=True\nclass C:\n    def f(self):\n        x = self.x\n        for x in y:\n            pass\n        with a as y:\n            pass\n        while self.foo():\n            self.bah()\n            a[self.x] = 1\n[out]\nMypyFile:1(\n  ClassDef:2(\n    C\n    FuncDef:3(\n      f\n      Args(\n        Var(self))\n      Block:4())))\n\n[case testDoNotStripModuleTopLevelOrClassBody]\n# mypy: ignore-errors=True\nf()\nclass C:\n    x = 5\n[out]\nMypyFile:1(\n  ExpressionStmt:2(\n    CallExpr:2(\n      NameExpr(f)\n      Args()))\n  ClassDef:3(\n    C\n    AssignmentStmt:4(\n      NameExpr(x)\n      IntExpr(5))))\n\n[case testDoNotStripMethodThatAssignsToAttribute]\n# mypy: ignore-errors=True\nclass C:\n    def m1(self):\n        self.x = 0\n    def m2(self):\n        a, self.y = 0\n[out]\nMypyFile:1(\n  ClassDef:2(\n    C\n    FuncDef:3(\n      m1\n      Args(\n        Var(self))\n      Block:4(\n        AssignmentStmt:4(\n          MemberExpr:4(\n            NameExpr(self)\n            x)\n          IntExpr(0))))\n    FuncDef:5(\n      m2\n      Args(\n        Var(self))\n      Block:6(\n        AssignmentStmt:6(\n          TupleExpr:6(\n            NameExpr(a)\n            MemberExpr:6(\n              NameExpr(self)\n              y))\n          IntExpr(0))))))\n\n[case testDoNotStripMethodThatAssignsToAttributeWithinStatement]\n# mypy: ignore-errors=True\nclass C:\n    def m1(self):\n        for x in y:\n            self.x = 0\n    def m2(self):\n        with x:\n            self.y = 0\n    def m3(self):\n        if x:\n            self.y = 0\n        else:\n            x = 4\n[out]\nMypyFile:1(\n  ClassDef:2(\n    C\n    FuncDef:3(\n      m1\n      Args(\n        Var(self))\n      Block:4(\n        ForStmt:4(\n          NameExpr(x)\n          NameExpr(y)\n          Block:5(\n            AssignmentStmt:5(\n              MemberExpr:5(\n                NameExpr(self)\n                x)\n              IntExpr(0))))))\n    FuncDef:6(\n      m2\n      Args(\n        Var(self))\n      Block:7(\n        WithStmt:7(\n          Expr(\n            NameExpr(x))\n          Block:8(\n            AssignmentStmt:8(\n              MemberExpr:8(\n                NameExpr(self)\n                y)\n              IntExpr(0))))))\n    FuncDef:9(\n      m3\n      Args(\n        Var(self))\n      Block:10(\n        IfStmt:10(\n          If(\n            NameExpr(x))\n          Then(\n            AssignmentStmt:11(\n              MemberExpr:11(\n                NameExpr(self)\n                y)\n              IntExpr(0)))\n          Else(\n            AssignmentStmt:13(\n              NameExpr(x)\n              IntExpr(4))))))))\n\n[case testDoNotStripMethodThatDefinesAttributeWithoutAssignment]\n# mypy: ignore-errors=True\nclass C:\n    def m1(self):\n        with y as self.x:\n            pass\n    def m2(self):\n        for self.y in x:\n            pass\n[out]\nMypyFile:1(\n  ClassDef:2(\n    C\n    FuncDef:3(\n      m1\n      Args(\n        Var(self))\n      Block:4(\n        WithStmt:4(\n          Expr(\n            NameExpr(y))\n          Target(\n            MemberExpr:4(\n              NameExpr(self)\n              x))\n          Block:5(\n            PassStmt:5()))))\n    FuncDef:6(\n      m2\n      Args(\n        Var(self))\n      Block:7(\n        ForStmt:7(\n          MemberExpr:7(\n            NameExpr(self)\n            y)\n          NameExpr(x)\n          Block:8(\n            PassStmt:8()))))))\n\n[case testStripDecoratedFunctionOrMethod]\n# mypy: ignore-errors=True\n@deco\ndef f():\n    x = 0\n\nclass C:\n    @deco\n    def m1(self):\n        x = 0\n\n    @deco\n    def m2(self):\n        self.x = 0\n[out]\nMypyFile:1(\n  Decorator:2(\n    Var(f)\n    NameExpr(deco)\n    FuncDef:3(\n      f\n      Block:4()))\n  ClassDef:6(\n    C\n    Decorator:7(\n      Var(m1)\n      NameExpr(deco)\n      FuncDef:8(\n        m1\n        Args(\n          Var(self))\n        Block:9()))\n    Decorator:11(\n      Var(m2)\n      NameExpr(deco)\n      FuncDef:12(\n        m2\n        Args(\n          Var(self))\n        Block:13(\n          AssignmentStmt:13(\n            MemberExpr:13(\n              NameExpr(self)\n              x)\n            IntExpr(0)))))))\n\n[case testStripOverloadedMethod]\n# mypy: ignore-errors=True\nclass C:\n    @overload\n    def m1(self, x: int) -> None: ...\n    @overload\n    def m1(self, x: str) -> None: ...\n    def m1(self, x):\n        x = 0\n\n    @overload\n    def m2(self, x: int) -> None: ...\n    @overload\n    def m2(self, x: str) -> None: ...\n    def m2(self, x):\n        self.x = 0\n[out]\nMypyFile:1(\n  ClassDef:2(\n    C\n    OverloadedFuncDef:3(\n      Decorator:3(\n        Var(m1)\n        NameExpr(overload)\n        FuncDef:4(\n          m1\n          Args(\n            Var(self)\n            Var(x))\n          def (self: Any, x: int?) -> None?\n          Block:4(\n            ExpressionStmt:4(\n              Ellipsis))))\n      Decorator:5(\n        Var(m1)\n        NameExpr(overload)\n        FuncDef:6(\n          m1\n          Args(\n            Var(self)\n            Var(x))\n          def (self: Any, x: str?) -> None?\n          Block:6(\n            ExpressionStmt:6(\n              Ellipsis))))\n      FuncDef:7(\n        m1\n        Args(\n          Var(self)\n          Var(x))\n        Block:8()))\n    OverloadedFuncDef:10(\n      Decorator:10(\n        Var(m2)\n        NameExpr(overload)\n        FuncDef:11(\n          m2\n          Args(\n            Var(self)\n            Var(x))\n          def (self: Any, x: int?) -> None?\n          Block:11(\n            ExpressionStmt:11(\n              Ellipsis))))\n      Decorator:12(\n        Var(m2)\n        NameExpr(overload)\n        FuncDef:13(\n          m2\n          Args(\n            Var(self)\n            Var(x))\n          def (self: Any, x: str?) -> None?\n          Block:13(\n            ExpressionStmt:13(\n              Ellipsis))))\n      FuncDef:14(\n        m2\n        Args(\n          Var(self)\n          Var(x))\n        Block:15(\n          AssignmentStmt:15(\n            MemberExpr:15(\n              NameExpr(self)\n              x)\n            IntExpr(0)))))))\n\n[case testStripMethodInNestedClass]\n# mypy: ignore-errors=True\nclass C:\n    class D:\n        def m1(self):\n             self.x = 1\n        def m2(self):\n             return self.x\n[out]\nMypyFile:1(\n  ClassDef:2(\n    C\n    ClassDef:3(\n      D\n      FuncDef:4(\n        m1\n        Args(\n          Var(self))\n        Block:5(\n          AssignmentStmt:5(\n            MemberExpr:5(\n              NameExpr(self)\n              x)\n            IntExpr(1))))\n      FuncDef:6(\n        m2\n        Args(\n          Var(self))\n        Block:7()))))\n"
  },
  {
    "path": "test-data/unit/pep561.test",
    "content": "[case testTypedPkgNoSitePkgsIgnoredImports]\n# pkgs: typedpkg\n# flags: --no-site-packages\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[file mypy.ini]\n\\[mypy]\nignore_missing_imports = True\n[out]\ntestTypedPkgNoSitePkgsIgnoredImports.py:6: note: Revealed type is \"Any\"\n\n[case testTypedPkgSimple]\n# pkgs: typedpkg\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[out]\ntestTypedPkgSimple.py:5: note: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n\n[case testTypedPkgSimplePackageSearchPath]\n# pkgs: typedpkg\n# flags: -p typedpkg.pkg\n[out]\n\n[case testTypedPkg_config_nositepackages]\n# pkgs: typedpkg\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[file mypy.ini]\n\\[mypy]\nno_site_packages=True\n[out]\ntestTypedPkg_config_nositepackages.py:2: error: Cannot find implementation or library stub for module named \"typedpkg.sample\"\ntestTypedPkg_config_nositepackages.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\ntestTypedPkg_config_nositepackages.py:3: error: Cannot find implementation or library stub for module named \"typedpkg\"\ntestTypedPkg_config_nositepackages.py:5: note: Revealed type is \"Any\"\n\n[case testTypedPkg_args_nositepackages]\n# pkgs: typedpkg\n# flags: --no-site-packages\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[out]\ntestTypedPkg_args_nositepackages.py:3: error: Cannot find implementation or library stub for module named \"typedpkg.sample\"\ntestTypedPkg_args_nositepackages.py:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\ntestTypedPkg_args_nositepackages.py:4: error: Cannot find implementation or library stub for module named \"typedpkg\"\ntestTypedPkg_args_nositepackages.py:6: note: Revealed type is \"Any\"\n\n[case testTypedPkgStubs]\n# pkgs: typedpkg-stubs\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[out]\ntestTypedPkgStubs.py:3: error: Module \"typedpkg\" has no attribute \"dne\"\ntestTypedPkgStubs.py:5: note: Revealed type is \"builtins.list[builtins.str]\"\n\n[case testStubPrecedence]\n# pkgs: typedpkg, typedpkg-stubs\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[out]\ntestStubPrecedence.py:5: note: Revealed type is \"builtins.list[builtins.str]\"\n\n[case testTypedPkgSimpleEditable]\n# pkgs: typedpkg; editable\nfrom typedpkg.sample import ex\nfrom typedpkg import dne\na = ex([''])\nreveal_type(a)\n[out]\ntestTypedPkgSimpleEditable.py:5: note: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n\n[case testTypedPkgNamespaceImportFrom]\n# pkgs: typedpkg, typedpkg_ns_a\nfrom typedpkg.pkg.aaa import af\nfrom typedpkg_ns.a.bbb import bf\nfrom typedpkg_ns.a.dne import dne\n\naf(\"abc\")\nbf(False)\ndne(123)\n\naf(False)\nbf(2)\ndne(\"abc\")\n[out]\ntestTypedPkgNamespaceImportFrom.py:4: error: Cannot find implementation or library stub for module named \"typedpkg_ns.a.dne\"\ntestTypedPkgNamespaceImportFrom.py:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\ntestTypedPkgNamespaceImportFrom.py:10: error: Argument 1 to \"af\" has incompatible type \"bool\"; expected \"str\"\ntestTypedPkgNamespaceImportFrom.py:11: error: Argument 1 to \"bf\" has incompatible type \"int\"; expected \"bool\"\n\n[case testTypedPkgNamespaceImportAs]\n# pkgs: typedpkg, typedpkg_ns_a\nimport typedpkg.pkg.aaa as nm; af = nm.af\nimport typedpkg_ns.a.bbb as am; bf = am.bf\nfrom typedpkg_ns.a.dne import dne\n\naf(\"abc\")\nbf(False)\ndne(123)\n\naf(False)\nbf(2)\ndne(\"abc\")\n[out]\ntestTypedPkgNamespaceImportAs.py:4: error: Cannot find implementation or library stub for module named \"typedpkg_ns.a.dne\"\ntestTypedPkgNamespaceImportAs.py:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\ntestTypedPkgNamespaceImportAs.py:10: error: Argument 1 has incompatible type \"bool\"; expected \"str\"\ntestTypedPkgNamespaceImportAs.py:11: error: Argument 1 has incompatible type \"int\"; expected \"bool\"\n\n[case testTypedPkgNamespaceRegImport]\n# pkgs: typedpkg, typedpkg_ns_a\nimport typedpkg.pkg.aaa; af = typedpkg.pkg.aaa.af\nimport typedpkg_ns.a.bbb; bf = typedpkg_ns.a.bbb.bf\nfrom typedpkg_ns.a.dne import dne\n\naf(\"abc\")\nbf(False)\ndne(123)\n\naf(False)\nbf(2)\ndne(\"abc\")\n\n[out]\ntestTypedPkgNamespaceRegImport.py:4: error: Cannot find implementation or library stub for module named \"typedpkg_ns.a.dne\"\ntestTypedPkgNamespaceRegImport.py:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\ntestTypedPkgNamespaceRegImport.py:10: error: Argument 1 has incompatible type \"bool\"; expected \"str\"\ntestTypedPkgNamespaceRegImport.py:11: error: Argument 1 has incompatible type \"int\"; expected \"bool\"\n\n-- This is really testing the test framework to make sure incremental works\n[case testPep561TestIncremental]\n# pkgs: typedpkg\nimport a\n[file a.py]\n[file a.py.2]\n1 + 'no'\n[out]\n[out2]\na.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testTypedPkgNamespaceRegFromImportTwice]\n# pkgs: typedpkg_ns_a\nfrom typedpkg_ns import a\n-- dummy should trigger a second iteration\n[file dummy.py.2]\n[out]\n[out2]\n\n[case testNamespacePkgWStubs]\n# pkgs: typedpkg_ns_a, typedpkg_ns_b, typedpkg_ns_b-stubs\n# flags: --no-namespace-packages\nimport typedpkg_ns.a.bbb as a\nimport typedpkg_ns.b.bbb as b\na.bf(False)\nb.bf(False)\na.bf(1)\nb.bf(1)\nimport typedpkg_ns.whatever as c  # type: ignore[import-untyped]\n[out]\ntestNamespacePkgWStubs.py:4: error: Skipping analyzing \"typedpkg_ns.b.bbb\": module is installed, but missing library stubs or py.typed marker. To work around this error, see the 'ignore_missing_py_typed' option\ntestNamespacePkgWStubs.py:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\ntestNamespacePkgWStubs.py:4: error: Skipping analyzing \"typedpkg_ns.b\": module is installed, but missing library stubs or py.typed marker. To work around this error, see the 'ignore_missing_py_typed' option\ntestNamespacePkgWStubs.py:7: error: Argument 1 to \"bf\" has incompatible type \"int\"; expected \"bool\"\n\n[case testNamespacePkgWStubsWithNamespacePackagesFlag]\n# pkgs: typedpkg_ns_a, typedpkg_ns_b, typedpkg_ns_b-stubs\n# flags: --namespace-packages\nimport typedpkg_ns.a.bbb as a\nimport typedpkg_ns.b.bbb as b\na.bf(False)\nb.bf(False)\na.bf(1)\nb.bf(1)\n[out]\ntestNamespacePkgWStubsWithNamespacePackagesFlag.py:7: error: Argument 1 to \"bf\" has incompatible type \"int\"; expected \"bool\"\ntestNamespacePkgWStubsWithNamespacePackagesFlag.py:8: error: Argument 1 to \"bf\" has incompatible type \"int\"; expected \"bool\"\n\n[case testMissingPytypedFlag]\n# pkgs: typedpkg_ns_b\n# flags: --namespace-packages --follow-untyped-imports\nimport typedpkg_ns.b.bbb as b\nb.bf(\"foo\", \"bar\")\n[out]\ntestMissingPytypedFlag.py:4: error: Too many arguments for \"bf\"\n\n[case testTypedPkgNamespaceRegFromImportTwiceMissing]\n# pkgs: typedpkg_ns_a\nfrom typedpkg_ns import does_not_exist  # type: ignore\nfrom typedpkg_ns import a\n-- dummy should trigger a second iteration\n[file dummy.py.2]\n[out]\n[out2]\n\n\n[case testTypedPkgNamespaceRegFromImportTwiceMissing2]\n# pkgs: typedpkg_ns_a\nfrom typedpkg_ns import does_not_exist  # type: ignore\nfrom typedpkg_ns.a.bbb import bf\n-- dummy should trigger a second iteration\n[file dummy.py.2]\n[out]\n[out2]\n"
  },
  {
    "path": "test-data/unit/plugins/add_classmethod.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import ARG_POS, Argument, Var\nfrom mypy.plugin import ClassDefContext, Plugin\nfrom mypy.plugins.common import add_method\nfrom mypy.types import NoneType\n\n\nclass ClassMethodPlugin(Plugin):\n    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        if \"BaseAddMethod\" in fullname:\n            return add_extra_methods_hook\n        return None\n\n\ndef add_extra_methods_hook(ctx: ClassDefContext) -> None:\n    add_method(ctx, \"foo_classmethod\", [], NoneType(), is_classmethod=True)\n    add_method(\n        ctx,\n        \"foo_staticmethod\",\n        [Argument(Var(\"\"), ctx.api.named_type(\"builtins.int\"), None, ARG_POS)],\n        ctx.api.named_type(\"builtins.str\"),\n        is_staticmethod=True,\n    )\n\n\ndef plugin(version: str) -> type[ClassMethodPlugin]:\n    return ClassMethodPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/add_method.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import ClassDefContext, Plugin\nfrom mypy.plugins.common import add_method\nfrom mypy.types import NoneType\n\n\nclass AddOverrideMethodPlugin(Plugin):\n    def get_class_decorator_hook_2(self, fullname: str) -> Callable[[ClassDefContext], bool] | None:\n        if fullname == \"__main__.inject_foo\":\n            return add_extra_methods_hook\n        return None\n\n\ndef add_extra_methods_hook(ctx: ClassDefContext) -> bool:\n    add_method(ctx, \"foo_implicit\", [], NoneType())\n    return True\n\n\ndef plugin(version: str) -> type[AddOverrideMethodPlugin]:\n    return AddOverrideMethodPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/add_overloaded_method.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import ARG_POS, Argument, Var\nfrom mypy.plugin import ClassDefContext, Plugin\nfrom mypy.plugins.common import MethodSpec, add_overloaded_method_to_class\n\n\nclass OverloadedMethodPlugin(Plugin):\n    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        if \"AddOverloadedMethod\" in fullname:\n            return add_overloaded_method_hook\n        return None\n\n\ndef add_overloaded_method_hook(ctx: ClassDefContext) -> None:\n    add_overloaded_method_to_class(ctx.api, ctx.cls, \"method\", _generate_method_specs(ctx))\n    add_overloaded_method_to_class(\n        ctx.api, ctx.cls, \"clsmethod\", _generate_method_specs(ctx), is_classmethod=True\n    )\n    add_overloaded_method_to_class(\n        ctx.api, ctx.cls, \"stmethod\", _generate_method_specs(ctx), is_staticmethod=True\n    )\n\n\ndef _generate_method_specs(ctx: ClassDefContext) -> list[MethodSpec]:\n    return [\n        MethodSpec(\n            args=[Argument(Var(\"arg\"), ctx.api.named_type(\"builtins.int\"), None, ARG_POS)],\n            return_type=ctx.api.named_type(\"builtins.str\"),\n        ),\n        MethodSpec(\n            args=[Argument(Var(\"arg\"), ctx.api.named_type(\"builtins.str\"), None, ARG_POS)],\n            return_type=ctx.api.named_type(\"builtins.int\"),\n        ),\n    ]\n\n\ndef plugin(version: str) -> type[OverloadedMethodPlugin]:\n    return OverloadedMethodPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/arg_kinds.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import FunctionContext, MethodContext, Plugin\nfrom mypy.types import Type\n\n\nclass ArgKindsPlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if \"func\" in fullname:\n            return extract_arg_kinds_from_function\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if \"Class.method\" in fullname:\n            return extract_arg_kinds_from_method\n        return None\n\n\ndef extract_arg_kinds_from_function(ctx: FunctionContext) -> Type:\n    ctx.api.fail(str([[x.value for x in y] for y in ctx.arg_kinds]), ctx.context)\n    return ctx.default_return_type\n\n\ndef extract_arg_kinds_from_method(ctx: MethodContext) -> Type:\n    ctx.api.fail(str([[x.value for x in y] for y in ctx.arg_kinds]), ctx.context)\n    return ctx.default_return_type\n\n\ndef plugin(version: str) -> type[ArgKindsPlugin]:\n    return ArgKindsPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/arg_names.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import StrExpr\nfrom mypy.plugin import FunctionContext, MethodContext, Plugin\nfrom mypy.types import Type\n\n\nclass ArgNamesPlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname in {\n            \"mod.func\",\n            \"mod.func_unfilled\",\n            \"mod.func_star_expr\",\n            \"mod.ClassInit\",\n            \"mod.Outer.NestedClassInit\",\n        }:\n            return extract_classname_and_set_as_return_type_function\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if fullname in {\n            \"mod.Class.method\",\n            \"mod.Class.myclassmethod\",\n            \"mod.Class.mystaticmethod\",\n            \"mod.ClassUnfilled.method\",\n            \"mod.ClassStarExpr.method\",\n            \"mod.ClassChild.method\",\n            \"mod.ClassChild.myclassmethod\",\n        }:\n            return extract_classname_and_set_as_return_type_method\n        return None\n\n\ndef extract_classname_and_set_as_return_type_function(ctx: FunctionContext) -> Type:\n    arg = ctx.args[ctx.callee_arg_names.index(\"classname\")][0]\n    if not isinstance(arg, StrExpr):\n        return ctx.default_return_type\n    return ctx.api.named_generic_type(arg.value, [])\n\n\ndef extract_classname_and_set_as_return_type_method(ctx: MethodContext) -> Type:\n    arg = ctx.args[ctx.callee_arg_names.index(\"classname\")][0]\n    if not isinstance(arg, StrExpr):\n        return ctx.default_return_type\n    return ctx.api.named_generic_type(arg.value, [])\n\n\ndef plugin(version: str) -> type[ArgNamesPlugin]:\n    return ArgNamesPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/attrhook.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import AttributeContext, Plugin\nfrom mypy.types import Instance, Type\n\n\nclass AttrPlugin(Plugin):\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        if fullname == \"m.Signal.__call__\":\n            return signal_call_callback\n        return None\n\n\ndef signal_call_callback(ctx: AttributeContext) -> Type:\n    if isinstance(ctx.type, Instance):\n        return ctx.type.args[0]\n    return ctx.default_attr_type\n\n\ndef plugin(version: str) -> type[AttrPlugin]:\n    return AttrPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/attrhook2.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import AttributeContext, Plugin\nfrom mypy.types import AnyType, Type, TypeOfAny\n\n\nclass AttrPlugin(Plugin):\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        if fullname == \"m.Magic.magic_field\":\n            return magic_field_callback\n        if fullname == \"m.Magic.nonexistent_field\":\n            return nonexistent_field_callback\n        if fullname == \"m.Magic.no_assignment_field\":\n            return no_assignment_field_callback\n        return None\n\n\ndef magic_field_callback(ctx: AttributeContext) -> Type:\n    return ctx.api.named_generic_type(\"builtins.str\", [])\n\n\ndef nonexistent_field_callback(ctx: AttributeContext) -> Type:\n    ctx.api.fail(\"Field does not exist\", ctx.context)\n    return AnyType(TypeOfAny.from_error)\n\n\ndef no_assignment_field_callback(ctx: AttributeContext) -> Type:\n    if ctx.is_lvalue:\n        ctx.api.fail(f\"Cannot assign to field\", ctx.context)\n        return AnyType(TypeOfAny.from_error)\n    return ctx.default_attr_type\n\n\ndef plugin(version: str) -> type[AttrPlugin]:\n    return AttrPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/badreturn.py",
    "content": "def plugin(version: str) -> None:\n    pass\n"
  },
  {
    "path": "test-data/unit/plugins/badreturn2.py",
    "content": "from __future__ import annotations\n\n\nclass MyPlugin:\n    pass\n\n\ndef plugin(version: str) -> type[MyPlugin]:\n    return MyPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/callable_instance.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import MethodContext, Plugin\nfrom mypy.types import Instance, Type\n\n\nclass CallableInstancePlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> None:\n        assert not fullname.endswith(\" of Foo\")\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        # Ensure that all names are fully qualified\n        assert not fullname.endswith(\" of Foo\")\n\n        if fullname == \"__main__.Class.__call__\":\n            return my_hook\n\n        return None\n\n\ndef my_hook(ctx: MethodContext) -> Type:\n    if isinstance(ctx.type, Instance) and len(ctx.type.args) == 1:\n        return ctx.type.args[0]\n    return ctx.default_return_type\n\n\ndef plugin(version: str) -> type[CallableInstancePlugin]:\n    return CallableInstancePlugin\n"
  },
  {
    "path": "test-data/unit/plugins/class_attr_hook.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import AttributeContext, Plugin\nfrom mypy.types import Type as MypyType\n\n\nclass ClassAttrPlugin(Plugin):\n    def get_class_attribute_hook(\n        self, fullname: str\n    ) -> Callable[[AttributeContext], MypyType] | None:\n        if fullname == \"__main__.Cls.attr\":\n            return my_hook\n        return None\n\n\ndef my_hook(ctx: AttributeContext) -> MypyType:\n    return ctx.api.named_generic_type(\"builtins.int\", [])\n\n\ndef plugin(_version: str) -> type[ClassAttrPlugin]:\n    return ClassAttrPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/class_callable.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import NameExpr\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.types import Instance, NoneType, Type, UnionType, get_proper_type\n\n\nclass AttrPlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname.startswith(\"mod.Attr\"):\n            return attr_hook\n        return None\n\n\ndef attr_hook(ctx: FunctionContext) -> Type:\n    default = get_proper_type(ctx.default_return_type)\n    assert isinstance(default, Instance)\n    if default.type.fullname == \"mod.Attr\":\n        attr_base = default\n    else:\n        attr_base = None\n    for base in default.type.bases:\n        if base.type.fullname == \"mod.Attr\":\n            attr_base = base\n            break\n    assert attr_base is not None\n    last_arg_exprs = ctx.args[-1]\n    if any(isinstance(expr, NameExpr) and expr.name == \"True\" for expr in last_arg_exprs):\n        return attr_base\n    assert len(attr_base.args) == 1\n    arg_type = attr_base.args[0]\n    return Instance(\n        attr_base.type,\n        [UnionType([arg_type, NoneType()])],\n        line=default.line,\n        column=default.column,\n    )\n\n\ndef plugin(version: str) -> type[AttrPlugin]:\n    return AttrPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/common_api_incremental.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import GDEF, MDEF, Block, ClassDef, SymbolTable, SymbolTableNode, TypeInfo, Var\nfrom mypy.plugin import ClassDefContext, DynamicClassDefContext, Plugin\n\n\nclass DynPlugin(Plugin):\n    def get_dynamic_class_hook(\n        self, fullname: str\n    ) -> Callable[[DynamicClassDefContext], None] | None:\n        if fullname == \"lib.declarative_base\":\n            return add_info_hook\n        return None\n\n    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        sym = self.lookup_fully_qualified(fullname)\n        if sym and isinstance(sym.node, TypeInfo):\n            if sym.node.metadata.get(\"magic\"):\n                return add_magic_hook\n        return None\n\n\ndef add_info_hook(ctx: DynamicClassDefContext) -> None:\n    class_def = ClassDef(ctx.name, Block([]))\n    class_def.fullname = ctx.api.qualified_name(ctx.name)\n\n    info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)\n    class_def.info = info\n    obj = ctx.api.named_type(\"builtins.object\", [])\n    info.mro = [info, obj.type]\n    info.bases = [obj]\n    ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))\n    info.metadata[\"magic\"] = {\"value\": True}\n\n\ndef add_magic_hook(ctx: ClassDefContext) -> None:\n    info = ctx.cls.info\n    str_type = ctx.api.named_type_or_none(\"builtins.str\", [])\n    assert str_type is not None\n    var = Var(\"__magic__\", str_type)\n    var.info = info\n    info.names[\"__magic__\"] = SymbolTableNode(MDEF, var)\n\n\ndef plugin(version: str) -> type[DynPlugin]:\n    return DynPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/config_data.py",
    "content": "from __future__ import annotations\n\nimport json\nimport os\nfrom typing import Any\n\nfrom mypy.plugin import Plugin, ReportConfigContext\n\n\nclass ConfigDataPlugin(Plugin):\n    def report_config_data(self, ctx: ReportConfigContext) -> Any:\n        path = os.path.join(\"tmp/test.json\")\n        with open(path) as f:\n            data: Any = json.load(f)\n        return data.get(ctx.id)\n\n\ndef plugin(version: str) -> type[ConfigDataPlugin]:\n    return ConfigDataPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/custom_errorcode.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.types import AnyType, Type, TypeOfAny\n\nCUSTOM_ERROR = ErrorCode(code=\"custom\", description=\"\", category=\"Custom\")\n\n\nclass CustomErrorCodePlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname.endswith(\".main\"):\n            return self.emit_error\n        return None\n\n    def emit_error(self, ctx: FunctionContext) -> Type:\n        ctx.api.fail(\"Custom error\", ctx.context, code=CUSTOM_ERROR)\n        return AnyType(TypeOfAny.from_error)\n\n\ndef plugin(version: str) -> type[CustomErrorCodePlugin]:\n    return CustomErrorCodePlugin\n"
  },
  {
    "path": "test-data/unit/plugins/customentry.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.types import Type\n\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname == \"__main__.f\":\n            return my_hook\n        assert fullname\n        return None\n\n\ndef my_hook(ctx: FunctionContext) -> Type:\n    return ctx.api.named_generic_type(\"builtins.int\", [])\n\n\ndef register(version: str) -> type[MyPlugin]:\n    return MyPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/customize_mro.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import ClassDefContext, Plugin\n\n\nclass DummyPlugin(Plugin):\n    def get_customize_class_mro_hook(self, fullname: str) -> Callable[[ClassDefContext], None]:\n        def analyze(classdef_ctx: ClassDefContext) -> None:\n            pass\n\n        return analyze\n\n\ndef plugin(version: str) -> type[DummyPlugin]:\n    return DummyPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/decimal_to_int.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import AnalyzeTypeContext, Plugin\nfrom mypy.types import Type\n\n\nclass MyPlugin(Plugin):\n    def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:\n        if fullname in (\"decimal.Decimal\", \"_decimal.Decimal\"):\n            return decimal_to_int_hook\n        return None\n\n\ndef decimal_to_int_hook(ctx: AnalyzeTypeContext) -> Type:\n    return ctx.api.named_type(\"builtins.int\", [])\n\n\ndef plugin(version: str) -> type[MyPlugin]:\n    return MyPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/depshook.py",
    "content": "from __future__ import annotations\n\nfrom mypy.nodes import MypyFile\nfrom mypy.plugin import Plugin\n\n\nclass DepsPlugin(Plugin):\n    def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:\n        if file.fullname == \"__main__\":\n            return [(10, \"err\", -1)]\n        return []\n\n\ndef plugin(version: str) -> type[DepsPlugin]:\n    return DepsPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/descriptor.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import MethodContext, MethodSigContext, Plugin\nfrom mypy.types import CallableType, NoneType, Type, get_proper_type\n\n\nclass DescriptorPlugin(Plugin):\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if fullname == \"__main__.Desc.__get__\":\n            return get_hook\n        return None\n\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], CallableType] | None:\n        if fullname == \"__main__.Desc.__set__\":\n            return set_hook\n        return None\n\n\ndef get_hook(ctx: MethodContext) -> Type:\n    arg = get_proper_type(ctx.arg_types[0][0])\n    if isinstance(arg, NoneType):\n        return ctx.api.named_generic_type(\"builtins.str\", [])\n    return ctx.api.named_generic_type(\"builtins.int\", [])\n\n\ndef set_hook(ctx: MethodSigContext) -> CallableType:\n    return CallableType(\n        [\n            ctx.api.named_generic_type(\"__main__.Cls\", []),\n            ctx.api.named_generic_type(\"builtins.int\", []),\n        ],\n        ctx.default_signature.arg_kinds,\n        ctx.default_signature.arg_names,\n        ctx.default_signature.ret_type,\n        ctx.default_signature.fallback,\n    )\n\n\ndef plugin(version: str) -> type[DescriptorPlugin]:\n    return DescriptorPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/dyn_class.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import GDEF, Block, ClassDef, SymbolTable, SymbolTableNode, TypeInfo, Var\nfrom mypy.plugin import ClassDefContext, DynamicClassDefContext, Plugin\nfrom mypy.types import Instance, get_proper_type\n\nDECL_BASES: set[str] = set()\n\n\nclass DynPlugin(Plugin):\n    def get_dynamic_class_hook(\n        self, fullname: str\n    ) -> Callable[[DynamicClassDefContext], None] | None:\n        if fullname == \"mod.declarative_base\":\n            return add_info_hook\n        return None\n\n    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        if fullname in DECL_BASES:\n            return replace_col_hook\n        return None\n\n\ndef add_info_hook(ctx: DynamicClassDefContext) -> None:\n    class_def = ClassDef(ctx.name, Block([]))\n    class_def.fullname = ctx.api.qualified_name(ctx.name)\n\n    info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)\n    class_def.info = info\n    obj = ctx.api.named_type(\"builtins.object\")\n    info.mro = [info, obj.type]\n    info.bases = [obj]\n    ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))\n    DECL_BASES.add(class_def.fullname)\n\n\ndef replace_col_hook(ctx: ClassDefContext) -> None:\n    info = ctx.cls.info\n    for sym in info.names.values():\n        node = sym.node\n        if isinstance(node, Var) and isinstance(\n            (node_type := get_proper_type(node.type)), Instance\n        ):\n            if node_type.type.fullname == \"mod.Column\":\n                new_sym = ctx.api.lookup_fully_qualified_or_none(\"mod.Instr\")\n                if new_sym:\n                    new_info = new_sym.node\n                    assert isinstance(new_info, TypeInfo)\n                    node.type = Instance(\n                        new_info, node_type.args, node_type.line, node_type.column\n                    )\n\n\ndef plugin(version: str) -> type[DynPlugin]:\n    return DynPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/dyn_class_from_method.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.nodes import (\n    GDEF,\n    Block,\n    ClassDef,\n    IndexExpr,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    SymbolTable,\n    SymbolTableNode,\n    TypeApplication,\n    TypeInfo,\n)\nfrom mypy.plugin import DynamicClassDefContext, Plugin\nfrom mypy.types import Instance\n\n\nclass DynPlugin(Plugin):\n    def get_dynamic_class_hook(\n        self, fullname: str\n    ) -> Callable[[DynamicClassDefContext], None] | None:\n        if \"from_queryset\" in fullname:\n            return add_info_hook\n        if \"as_manager\" in fullname:\n            return as_manager_hook\n        return None\n\n\ndef add_info_hook(ctx: DynamicClassDefContext) -> None:\n    class_def = ClassDef(ctx.name, Block([]))\n    class_def.fullname = ctx.api.qualified_name(ctx.name)\n\n    info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)\n    class_def.info = info\n    assert isinstance(ctx.call.args[0], RefExpr)\n    queryset_type_fullname = ctx.call.args[0].fullname\n    queryset_node = ctx.api.lookup_fully_qualified_or_none(queryset_type_fullname)\n    assert queryset_node is not None\n    queryset_info = queryset_node.node\n    assert isinstance(queryset_info, TypeInfo)\n    obj = ctx.api.named_type(\"builtins.object\")\n    info.mro = [info, queryset_info, obj.type]\n    info.bases = [Instance(queryset_info, [])]\n    ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))\n\n\ndef as_manager_hook(ctx: DynamicClassDefContext) -> None:\n    class_def = ClassDef(ctx.name, Block([]))\n    class_def.fullname = ctx.api.qualified_name(ctx.name)\n\n    info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)\n    class_def.info = info\n    assert isinstance(ctx.call.callee, MemberExpr)\n    assert isinstance(ctx.call.callee.expr, IndexExpr)\n    assert isinstance(ctx.call.callee.expr.analyzed, TypeApplication)\n    assert isinstance(ctx.call.callee.expr.analyzed.expr, NameExpr)\n\n    queryset_type_fullname = ctx.call.callee.expr.analyzed.expr.fullname\n    queryset_node = ctx.api.lookup_fully_qualified_or_none(queryset_type_fullname)\n    assert queryset_node is not None\n    queryset_info = queryset_node.node\n    assert isinstance(queryset_info, TypeInfo)\n    parameter_type = ctx.call.callee.expr.analyzed.types[0]\n\n    obj = ctx.api.named_type(\"builtins.object\")\n    info.mro = [info, queryset_info, obj.type]\n    info.bases = [Instance(queryset_info, [parameter_type])]\n    ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))\n\n\ndef plugin(version: str) -> type[DynPlugin]:\n    return DynPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/fnplugin.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.types import Type\n\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname == \"__main__.f\":\n            return my_hook\n        assert fullname is not None\n        return None\n\n\ndef my_hook(ctx: FunctionContext) -> Type:\n    return ctx.api.named_generic_type(\"builtins.int\", [])\n\n\ndef plugin(version: str) -> type[MyPlugin]:\n    return MyPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/fully_qualified_test_hook.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import MethodSigContext, Plugin\nfrom mypy.types import CallableType\n\n\nclass FullyQualifiedTestPlugin(Plugin):\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], CallableType] | None:\n        # Ensure that all names are fully qualified\n        if \"FullyQualifiedTest\" in fullname:\n            assert fullname.startswith(\"__main__.\") and \" of \" not in fullname, fullname\n            return my_hook\n\n        return None\n\n\ndef my_hook(ctx: MethodSigContext) -> CallableType:\n    return ctx.default_signature.copy_modified(\n        ret_type=ctx.api.named_generic_type(\"builtins.int\", [])\n    )\n\n\ndef plugin(version: str) -> type[FullyQualifiedTestPlugin]:\n    return FullyQualifiedTestPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/function_sig_hook.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import FunctionSigContext, Plugin\nfrom mypy.types import CallableType\n\n\nclass FunctionSigPlugin(Plugin):\n    def get_function_signature_hook(\n        self, fullname: str\n    ) -> Callable[[FunctionSigContext], CallableType] | None:\n        if fullname == \"__main__.dynamic_signature\":\n            return my_hook\n        return None\n\n\ndef my_hook(ctx: FunctionSigContext) -> CallableType:\n    arg1_args = ctx.args[0]\n    if len(arg1_args) != 1:\n        return ctx.default_signature\n    arg1_type = ctx.api.get_expression_type(arg1_args[0])\n    return ctx.default_signature.copy_modified(arg_types=[arg1_type], ret_type=arg1_type)\n\n\ndef plugin(version: str) -> type[FunctionSigPlugin]:\n    return FunctionSigPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/method_in_decorator.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import MethodContext, Plugin\nfrom mypy.types import CallableType, Type, get_proper_type\n\n\nclass MethodDecoratorPlugin(Plugin):\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if \"Foo.a\" in fullname:\n            return method_decorator_callback\n        return None\n\n\ndef method_decorator_callback(ctx: MethodContext) -> Type:\n    default = get_proper_type(ctx.default_return_type)\n    if isinstance(default, CallableType):\n        str_type = ctx.api.named_generic_type(\"builtins.str\", [])\n        return default.copy_modified(ret_type=str_type)\n    return ctx.default_return_type\n\n\ndef plugin(version: str) -> type[MethodDecoratorPlugin]:\n    return MethodDecoratorPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/method_sig_hook.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import CheckerPluginInterface, MethodSigContext, Plugin\nfrom mypy.types import CallableType, Instance, Type, get_proper_type\n\n\nclass MethodSigPlugin(Plugin):\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], CallableType] | None:\n        # Ensure that all names are fully qualified\n        assert not fullname.endswith(\" of Foo\")\n\n        if fullname.startswith(\"__main__.Foo.\"):\n            return my_hook\n\n        return None\n\n\ndef _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type:\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        if typ.type.fullname == \"builtins.str\":\n            return api.named_generic_type(\"builtins.int\", [])\n        elif typ.args:\n            return typ.copy_modified(args=[_str_to_int(api, t) for t in typ.args])\n\n    return typ\n\n\ndef my_hook(ctx: MethodSigContext) -> CallableType:\n    return ctx.default_signature.copy_modified(\n        arg_types=[_str_to_int(ctx.api, t) for t in ctx.default_signature.arg_types],\n        ret_type=_str_to_int(ctx.api, ctx.default_signature.ret_type),\n    )\n\n\ndef plugin(version: str) -> type[MethodSigPlugin]:\n    return MethodSigPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/named_callable.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.types import CallableType, Type, get_proper_type\n\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname == \"m.decorator1\":\n            return decorator_call_hook\n        if fullname == \"m._decorated\":  # This is a dummy name generated by the plugin\n            return decorate_hook\n        return None\n\n\ndef decorator_call_hook(ctx: FunctionContext) -> Type:\n    default = get_proper_type(ctx.default_return_type)\n    if isinstance(default, CallableType):\n        return default.copy_modified(name=\"m._decorated\")\n    return ctx.default_return_type\n\n\ndef decorate_hook(ctx: FunctionContext) -> Type:\n    default = get_proper_type(ctx.default_return_type)\n    if isinstance(default, CallableType):\n        return default.copy_modified(ret_type=ctx.api.named_generic_type(\"builtins.str\", []))\n    return ctx.default_return_type\n\n\ndef plugin(version: str) -> type[MyPlugin]:\n    return MyPlugin\n"
  },
  {
    "path": "test-data/unit/plugins/noentry.py",
    "content": "# empty plugin\n"
  },
  {
    "path": "test-data/unit/plugins/plugin2.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.types import Type\n\n\nclass Plugin2(Plugin):\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname in (\"__main__.f\", \"__main__.g\"):\n            return str_hook\n        return None\n\n\ndef str_hook(ctx: FunctionContext) -> Type:\n    return ctx.api.named_generic_type(\"builtins.str\", [])\n\n\ndef plugin(version: str) -> type[Plugin2]:\n    return Plugin2\n"
  },
  {
    "path": "test-data/unit/plugins/type_anal_hook.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import AnalyzeTypeContext, Plugin\n\n# The official name changed to NoneType but we have an alias for plugin compat reasons\n# so we'll keep testing that here.\nfrom mypy.types import AnyType, CallableType, NoneTyp, Type, TypeList, TypeOfAny\n\n\nclass TypeAnalyzePlugin(Plugin):\n    def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:\n        if fullname == \"m.Signal\":\n            return signal_type_analyze_callback\n        return None\n\n\ndef signal_type_analyze_callback(ctx: AnalyzeTypeContext) -> Type:\n    if len(ctx.type.args) != 1 or not isinstance(ctx.type.args[0], TypeList):\n        ctx.api.fail('Invalid \"Signal\" type (expected \"Signal[[t, ...]]\")', ctx.context)\n        return AnyType(TypeOfAny.from_error)\n\n    args = ctx.type.args[0]\n    assert isinstance(args, TypeList)\n    analyzed = ctx.api.analyze_callable_args(args)\n    if analyzed is None:\n        return AnyType(TypeOfAny.from_error)  # Error generated elsewhere\n    arg_types, arg_kinds, arg_names = analyzed\n    arg_types = [ctx.api.analyze_type(arg) for arg in arg_types]\n    type_arg = CallableType(\n        arg_types, arg_kinds, arg_names, NoneTyp(), ctx.api.named_type(\"builtins.function\", [])\n    )\n    return ctx.api.named_type(\"m.Signal\", [type_arg])\n\n\ndef plugin(version: str) -> type[TypeAnalyzePlugin]:\n    return TypeAnalyzePlugin\n"
  },
  {
    "path": "test-data/unit/plugins/union_method.py",
    "content": "from __future__ import annotations\n\nfrom typing import Callable\n\nfrom mypy.plugin import CheckerPluginInterface, MethodContext, MethodSigContext, Plugin\nfrom mypy.types import CallableType, Instance, Type, get_proper_type\n\n\nclass MethodPlugin(Plugin):\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], CallableType] | None:\n        if fullname.startswith(\"__main__.Foo.\"):\n            return my_meth_sig_hook\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if fullname.startswith(\"__main__.Bar.\"):\n            return my_meth_hook\n        return None\n\n\ndef _str_to_int(api: CheckerPluginInterface, typ: Type) -> Type:\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        if typ.type.fullname == \"builtins.str\":\n            return api.named_generic_type(\"builtins.int\", [])\n        elif typ.args:\n            return typ.copy_modified(args=[_str_to_int(api, t) for t in typ.args])\n    return typ\n\n\ndef _float_to_int(api: CheckerPluginInterface, typ: Type) -> Type:\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        if typ.type.fullname == \"builtins.float\":\n            return api.named_generic_type(\"builtins.int\", [])\n        elif typ.args:\n            return typ.copy_modified(args=[_float_to_int(api, t) for t in typ.args])\n    return typ\n\n\ndef my_meth_sig_hook(ctx: MethodSigContext) -> CallableType:\n    return ctx.default_signature.copy_modified(\n        arg_types=[_str_to_int(ctx.api, t) for t in ctx.default_signature.arg_types],\n        ret_type=_str_to_int(ctx.api, ctx.default_signature.ret_type),\n    )\n\n\ndef my_meth_hook(ctx: MethodContext) -> Type:\n    return _float_to_int(ctx.api, ctx.default_return_type)\n\n\ndef plugin(version: str) -> type[MethodPlugin]:\n    return MethodPlugin\n"
  },
  {
    "path": "test-data/unit/pythoneval-asyncio.test",
    "content": "-- Test cases for type checking mypy programs using full stubs and running\n-- using CPython.\n--\n-- These are mostly regression tests -- no attempt is made to make these\n-- complete.\n--\n-- This test file checks Asyncio and await interaction\n\n[case testImportAsyncio]\nimport asyncio\nprint('Imported')\n[out]\nImported\n\n[case testSimpleCoroutineSleep]\nfrom typing import Any, Generator\nimport asyncio\nfrom asyncio import Future\n\nasync def greet_every_two_seconds() -> None:\n    n = 0\n    while n < 5:\n        print('Prev', n)\n        await asyncio.sleep(0.01)\n        print('After', n)\n        n += 1\n\nasyncio.run(greet_every_two_seconds())\n[out]\nPrev 0\nAfter 0\nPrev 1\nAfter 1\nPrev 2\nAfter 2\nPrev 3\nAfter 3\nPrev 4\nAfter 4\n\n[case testCoroutineCallingOtherCoroutine]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def compute(x: int, y: int) -> int:\n    print(\"Compute %s + %s ...\" % (x, y))\n    await asyncio.sleep(0.01)\n    return x + y   # Here the int is wrapped in Future[int]\n\nasync def print_sum(x: int, y: int) -> None:\n    result = await compute(x, y)  # The type of result will be int (is extracted from Future[int]\n    print(\"%s + %s = %s\" % (x, y, result))\n\nasyncio.run(print_sum(1, 2))\n[out]\nCompute 1 + 2 ...\n1 + 2 = 3\n\n[case testCoroutineChangingFuture]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def slow_operation(future: 'Future[str]') -> None:\n    await asyncio.sleep(0.01)\n    future.set_result('Future is done!')\n\nasync def main() -> None:\n    future = asyncio.Future()  # type: Future[str]\n    asyncio.Task(slow_operation(future))\n    await future\n    print(future.result())\n\nasyncio.run(main())\n[out]\nFuture is done!\n\n[case testFunctionAssignedAsCallback]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future, AbstractEventLoop\n\nasync def slow_operation(future: 'Future[str]') -> None:\n    await asyncio.sleep(1)\n    future.set_result('Callback works!')\n\ndef got_result(future: 'Future[str]') -> None:\n    print(future.result())\n    loop.stop()\n\nasync def main() -> None:\n    future = asyncio.Future()  # type: Future[str]\n    asyncio.Task(slow_operation(future))  # Here create a task with the function. (The Task need a Future[T] as first argument)\n    future.add_done_callback(got_result)  # and assign the callback to the future\n\nloop = asyncio.new_event_loop()  # type: AbstractEventLoop\nloop.run_until_complete(main())\ntry:\n    loop.run_forever()\nfinally:\n    loop.close()\n[out]\nCallback works!\n\n[case testMultipleTasks]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Task, Future\nasync def factorial(name, number) -> None:\n    f = 1\n    for i in range(2, number+1):\n        print(\"Task %s: Compute factorial(%s)...\" % (name, i))\n        await asyncio.sleep(0.01)\n        f *= i\n    print(\"Task %s: factorial(%s) = %s\" % (name, number, f))\n\nasync def main() -> None:\n    tasks = [\n        asyncio.Task(factorial(\"A\", 2)),\n        asyncio.Task(factorial(\"B\", 3)),\n        asyncio.Task(factorial(\"C\", 4))]\n    await asyncio.wait(tasks)\n\nasyncio.run(main())\n[out]\nTask A: Compute factorial(2)...\nTask B: Compute factorial(2)...\nTask C: Compute factorial(2)...\nTask A: factorial(2) = 2\nTask B: Compute factorial(3)...\nTask C: Compute factorial(3)...\nTask B: factorial(3) = 6\nTask C: Compute factorial(4)...\nTask C: factorial(4) = 24\n\n\n[case testConcatenatedCoroutines]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nfuture: Future[int]\n\nasync def h4() -> int:\n    x = await future\n    return x\n\nasync def h3() -> int:\n    x = await h4()\n    print(\"h3: %s\" % x)\n    return x\n\nasync def h2() -> int:\n    x = await h3()\n    print(\"h2: %s\" % x)\n    return x\n\nasync def h() -> None:\n    x = await h2()\n    print(\"h: %s\" % x)\n\nasync def main() -> None:\n    global future\n    future = asyncio.Future()\n    future.set_result(42)\n    await h()\n    print(\"Outside %s\" % future.result())\n\nasyncio.run(main())\n[out]\nh3: 42\nh2: 42\nh: 42\nOutside 42\n\n[case testConcatenatedCoroutinesReturningFutures]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def h4() -> \"Future[int]\":\n    await asyncio.sleep(0.01)\n    f = asyncio.Future()  # type: Future[int]\n    return f\n\nasync def h3() -> \"Future[Future[int]]\":\n    x = await h4()\n    x.set_result(42)\n    f = asyncio.Future()  # type: Future[Future[int]]\n    f.set_result(x)\n    return f\n\nasync def h() -> None:\n    print(\"Before\")\n    x = await h3()\n    y = await x\n    z = await y\n    print(z)\n    def normalize(future):\n        # The str conversion seems inconsistent; not sure exactly why. Normalize\n        # the result.\n        return str(future).replace('<Future finished ', 'Future<')\n    print(normalize(y))\n    print(normalize(x))\n\nasyncio.run(h())\n[out]\nBefore\n42\nFuture<result=42>\nFuture<result=Future<result=42>>\n\n\n[case testCoroutineWithOwnClass]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nfuture: Future[\"A\"]\n\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nasync def h() -> None:\n    x = await future\n    print(\"h: %s\" % x.x)\n\nasync def main() -> None:\n    global future\n    future = asyncio.Future()\n    future.set_result(A(42))\n    await h()\n    print(\"Outside %s\" % future.result().x)\n\nasyncio.run(main())\n[out]\nh: 42\nOutside 42\n\n\n-- Errors\n\n[case testErrorAssigningCoroutineThatDontReturn]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def greet() -> None:\n    await asyncio.sleep(0.2)\n    print('Hello World')\n\nasync def test() -> None:\n    await greet()\n    x = await greet()  # Error\n\nasyncio.run(test())\n[out]\n_program.py:11: error: Function does not return a value (it only ever returns None)\n\n[case testErrorReturnIsNotTheSameType]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def compute(x: int, y: int) -> int:\n    print(\"Compute %s + %s ...\" % (x, y))\n    await asyncio.sleep(0.01)\n    return str(x + y)   # Error\n\nasync def print_sum(x: int, y: int) -> None:\n    result = await compute(x, y)\n    print(\"%s + %s = %s\" % (x, y, result))\n\nasyncio.run(print_sum(1, 2))\n[out]\n_program.py:8: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testErrorSetFutureDifferentInternalType]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def slow_operation(future: 'Future[str]') -> None:\n    await asyncio.sleep(1)\n    future.set_result(42)  # Error\n\nasync def main() -> None:\n    future = asyncio.Future()  # type: Future[str]\n    asyncio.Task(slow_operation(future))\n    await future\n    print(future.result())\n\nasyncio.run(main())\n[out]\n_program.py:7: error: Argument 1 to \"set_result\" of \"Future\" has incompatible type \"int\"; expected \"str\"\n\n\n[case testErrorUsingDifferentFutureType]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def slow_operation(future: 'Future[int]') -> None:\n    await asyncio.sleep(1)\n    future.set_result(42)\n\nasync def main() -> None:\n    future = asyncio.Future()  # type: Future[str]\n    asyncio.Task(slow_operation(future))  # Error\n    await future\n    print(future.result())\n\nasyncio.run(main())\n[out]\n_program.py:11: error: Argument 1 to \"slow_operation\" has incompatible type \"Future[str]\"; expected \"Future[int]\"\n\n[case testErrorUsingDifferentFutureTypeAndSetFutureDifferentInternalType]\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def slow_operation(future: 'Future[int]') -> None:\n    await asyncio.sleep(1)\n    future.set_result('42')  # Try to set an str as result to a Future[int]\n\nasync def main() -> None:\n    future = asyncio.Future()  # type: Future[str]\n    asyncio.Task(slow_operation(future))  # Error\n    await future\n    print(future.result())\n\nasyncio.run(main())\n[out]\n_program.py:7: error: Argument 1 to \"set_result\" of \"Future\" has incompatible type \"str\"; expected \"int\"\n_program.py:11: error: Argument 1 to \"slow_operation\" has incompatible type \"Future[str]\"; expected \"Future[int]\"\n\n[case testErrorSettingCallbackWithDifferentFutureType]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future, AbstractEventLoop\n\nasync def slow_operation(future: 'Future[str]') -> None:\n    await asyncio.sleep(1)\n    future.set_result('Future is done!')\n\ndef got_result(future: 'Future[int]') -> None:\n    print(future.result())\n    loop.stop()\n\nasync def main() -> None:\n    future = asyncio.Future()  # type: Future[str]\n    asyncio.Task(slow_operation(future))\n    future.add_done_callback(got_result)  # Error\n\nloop = asyncio.new_event_loop()\nloop.run_until_complete(main())\ntry:\n    loop.run_forever()\nfinally:\n    loop.close()\n[out]\n_program.py:17: error: Argument 1 to \"add_done_callback\" of \"Future\" has incompatible type \"Callable[[Future[int]], None]\"; expected \"Callable[[Future[str]], object]\"\n\n[case testErrorOneMoreFutureInReturnType]\nimport typing\nfrom typing import Any, Generator\nimport asyncio\nfrom asyncio import Future\n\nasync def h4() -> Future[int]:\n    await asyncio.sleep(1)\n    f = asyncio.Future()  # type: Future[int]\n    return f\n\nasync def h3() -> Future[Future[Future[int]]]:\n    x = await h4()\n    x.set_result(42)\n    f = asyncio.Future()  # type: Future[Future[int]]\n    f.set_result(x)\n    return f\n\nasync def h() -> None:\n    print(\"Before\")\n    x = await h3()\n    y = await x\n    z = await y\n    print(z)\n    print(y)\n    print(x)\n\nasyncio.run(h())\n[out]\n_program.py:16: error: Incompatible return value type (got \"Future[Future[int]]\", expected \"Future[Future[Future[int]]]\")\n\n[case testErrorOneLessFutureInReturnType]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nasync def h4() -> Future[int]:\n    await asyncio.sleep(1)\n    f = asyncio.Future()  # type: Future[int]\n    return f\n\nasync def h3() -> Future[int]:\n    x = await h4()\n    x.set_result(42)\n    f = asyncio.Future()  # type: Future[Future[int]]\n    f.set_result(x)\n    return f\n\nasync def h() -> None:\n    print(\"Before\")\n    x = await h3()\n    y = await x\n    print(y)\n    print(x)\n\nasyncio.run(h())\n[out]\n_program.py:16: error: Incompatible return value type (got \"Future[Future[int]]\", expected \"Future[int]\")\n_program.py:16: note: Maybe you forgot to use \"await\"?\n\n[case testErrorAssignmentDifferentType]\nimport typing\nfrom typing import Any\nimport asyncio\nfrom asyncio import Future\n\nfuture: Future[\"A\"]\n\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass B:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nasync def h() -> None:\n    x = await future  # type: B  # Error\n    print(\"h: %s\" % x.x)\n\nasync def main() -> None:\n    global future\n    future = asyncio.Future()\n    future.set_result(A(42))\n    await h()\n\nasyncio.run(main())\n[out]\n_program.py:17: error: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testForwardRefToBadAsyncShouldNotCrash_newsemanal]\nfrom typing import TypeVar\nimport asyncio\n\nT = TypeVar('T')\nP = whatever  # type: ignore\n\ndef test() -> None:\n    reveal_type(bad)\n    bad(0)\n\nasync def bad(arg: P) -> T:\n    pass\n[out]\n_program.py:8: note: Revealed type is \"def [T] (arg: P?) -> typing.Coroutine[Any, Any, T`-1]\"\n_program.py:9: error: Value of type \"Coroutine[Any, Any, Never]\" must be used\n_program.py:9: note: Are you missing an await?\n_program.py:11: error: Variable \"_testForwardRefToBadAsyncShouldNotCrash_newsemanal.P\" is not valid as a type\n_program.py:11: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n"
  },
  {
    "path": "test-data/unit/pythoneval.test",
    "content": "-- Test cases for type checking mypy programs using full stubs and running\n-- using CPython.\n--\n-- These are mostly regression tests -- no attempt is made to make these\n-- complete.\n\n\n[case testHello]\nimport typing\nprint('hello, world')\n[out]\nhello, world\n\n[case testMiscStdlibFeatures]\n# Various legacy tests merged together to speed up test runtimes.\n\ndef f(x: object) -> None: pass\n\n# testReversed\nfrom typing import Reversible\nclass R(Reversible):\n    def __iter__(self): return iter('oof')\n    def __reversed__(self): return iter('foo')\nf(list(reversed(range(5))))\nf(list(reversed([1,2,3])))\nf(list(reversed('abc')))\nf(list(reversed(R())))\n\n# testIntAndFloatConversion\nfrom typing import SupportsInt, SupportsFloat\nclass A(SupportsInt):\n    def __int__(self): return 5\nclass B(SupportsFloat):\n    def __float__(self): return 1.2\nf(int(1))\nf(int(6.2))\nf(int('3'))\nf(int(b'4'))\nf(int(A()))\nf(float(-9))\nf(float(B()))\n\n# testAbs\nfrom typing import SupportsAbs\nclass Ab(SupportsAbs[float]):\n    def __abs__(self) -> float: return 5.5\n\nf(abs(-1))\nf(abs(-1.2))\nf(abs(Ab()))\n\n# testRound\nfrom typing import SupportsRound\nclass Ro(SupportsRound):\n    def __round__(self, ndigits=0): return 'x%d' % ndigits\nf(round(1.6))\nf(round(Ro()))\nf(round(Ro(), 2))\n\n# testCallMethodViaTypeObject\nlist.__add__([1, 2], [3, 4])\n\n# testInheritedClassAttribute\nimport typing\nclass AA:\n    x = 1\n    def f(self: typing.Optional[\"AA\"]) -> None: pass\nclass BB(AA):\n    pass\nBB.f(None)\nf(BB.x)\n\n# testSpecialAttributes\nclass Doc:\n    \"\"\"A docstring!\"\"\"\nf(Doc().__doc__)\nf(Doc().__class__)\n\n# testFunctionAttributes\nf(ord.__class__)\nf(type(ord.__doc__ or '' + ''))\nf(ord.__name__)\nf(ord.__module__)\n\n# testModuleAttributes\nimport math\nf(type(__spec__))\nf(math.__name__)\nf(math.__spec__.name)\nf(type(math.__dict__))\nf(type(math.__doc__ or ''))\nf(type(math.__spec__).__name__)\nf(math.__class__)\n\n[case testAbs2]\nn: int\nf: float\nn = abs(1)\nabs(1) + 'x'  # Error\nf = abs(1.1)\nabs(1.1) + 'x'  # Error\n[out]\n_program.py:4: error: Unsupported operand types for + (\"int\" and \"str\")\n_program.py:6: error: Unsupported operand types for + (\"float\" and \"str\")\n\n[case testTypeAttributes]\nimport typing\nprint(str.__class__)\nprint(type(str.__doc__))\nprint(str.__name__)\nprint(str.__module__)\nprint(str.__dict__ is not None)\n[out]\n<class 'type'>\n<class 'str'>\nstr\nbuiltins\nTrue\n\n[case testBoolCompatibilityWithInt]\nimport typing\nx = 0\nx = True\nprint(bool('x'))\nprint(bool(''))\n[out]\nTrue\nFalse\n\n[case testCannotExtendBoolUnlessIgnored]\nclass A(bool): pass\nclass B(bool): pass  # type: ignore\n[out]\n_program.py:1: error: Cannot inherit from final class \"bool\"\n\n[case testCallBuiltinTypeObjectsWithoutArguments]\nimport typing\nprint(int())\nprint(repr(str()))\nprint(repr(bytes()))\nprint(float())\nprint(bool())\n[out]\n0\n''\nb''\n0.0\nFalse\n\n[case testIntegerDivision]\nimport typing\nx = 1 / 2\nx = 1.5\n[out]\n\n[case testIntMethods]\nimport typing\nprint(int.from_bytes(b'ab', 'big'))\nn = 0\nprint(n.from_bytes(b'ac', 'big'))\nprint(n.from_bytes([2, 3], 'big'))\nprint(n.to_bytes(2, 'big'))\n[out]\n24930\n24931\n515\nb'\\x00\\x00'\n\n[case testFloatMethods]\nimport typing\nprint(1.5.as_integer_ratio())\nprint(1.5.hex())\nprint(2.0.is_integer())\nprint(float.fromhex('0x1.8'))\n[out]\n(3, 2)\n0x1.8000000000000p+0\nTrue\n1.5\n\n[case testDictFromkeys]\nimport typing\nd = dict.fromkeys('foo')\nd['x'] = 2\nd2 = dict.fromkeys([1, 2], b'')\nd2[2] = b'foo'\n[out]\n\n[case testIsinstanceWithTuple]\nfrom typing import cast, Any\nx = cast(Any, (1, 'x'))\nif isinstance(x, tuple):\n    print(x[0], x[1])\n[out]\n1 x\n\n[case testAnyStr]\nfrom typing import AnyStr\ndef f(x: AnyStr) -> AnyStr:\n    if isinstance(x, str):\n        return 'foo'\n    else:\n        return b'zar'\nprint(f(''))\nprint(f(b''))\n[out]\nfoo\nb'zar'\n\n[case testNameNotImportedFromTyping]\nimport typing\ncast(int, 2)\n[out]\n_program.py:2: error: Name \"cast\" is not defined\n_program.py:2: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import cast\")\n\n[case testBinaryIOType]\nfrom typing import BinaryIO\ndef f(f: BinaryIO) -> None:\n    f.write(b'foo')\n    f.write(bytearray(b'foo'))\n[out]\n\n[case testIOTypes]\nfrom typing import IO\nimport sys\ndef txt(f: IO[str]) -> None:\n    f.write('foo')\n    f.write(b'foo')\ndef bin(f: IO[bytes]) -> None:\n    f.write(b'foo')\n    f.write(bytearray(b'foo'))\ntxt(sys.stdout)\nbin(sys.stdout)\n[out]\n_program.py:5: error: Argument 1 to \"write\" of \"IO\" has incompatible type \"bytes\"; expected \"str\"\n_program.py:10: error: Argument 1 to \"bin\" has incompatible type \"Union[TextIO, Any]\"; expected \"IO[bytes]\"\n\n[case testBuiltinOpen]\nf = open('x')\nf.write('x')\nf.write(b'x')\nf.foobar()\n[out]\n_program.py:3: error: Argument 1 to \"write\" of \"_TextIOBase\" has incompatible type \"bytes\"; expected \"str\"\n_program.py:4: error: \"TextIOWrapper[_WrappedBuffer]\" has no attribute \"foobar\"\n\n[case testOpenReturnTypeInference]\nreveal_type(open('x'))\nreveal_type(open('x', 'r'))\nreveal_type(open('x', 'rb'))\nmode = 'rb'\nreveal_type(open('x', mode))\n[out]\n_program.py:1: note: Revealed type is \"_io.TextIOWrapper[_io._WrappedBuffer]\"\n_program.py:2: note: Revealed type is \"_io.TextIOWrapper[_io._WrappedBuffer]\"\n_program.py:3: note: Revealed type is \"_io.BufferedReader\"\n_program.py:5: note: Revealed type is \"typing.IO[Any]\"\n\n[case testOpenReturnTypeInferenceSpecialCases]\nreveal_type(open(mode='rb', file='x'))\nreveal_type(open(file='x', mode='rb'))\nmode = 'rb'\nreveal_type(open(mode=mode, file='r'))\n[out]\n_testOpenReturnTypeInferenceSpecialCases.py:1: note: Revealed type is \"_io.BufferedReader\"\n_testOpenReturnTypeInferenceSpecialCases.py:2: note: Revealed type is \"_io.BufferedReader\"\n_testOpenReturnTypeInferenceSpecialCases.py:4: note: Revealed type is \"typing.IO[Any]\"\n\n[case testPathOpenReturnTypeInference]\nfrom pathlib import Path\np = Path(\"x\")\nreveal_type(p.open())\nreveal_type(p.open('r'))\nreveal_type(p.open('rb'))\nmode = 'rb'\nreveal_type(p.open(mode))\n[out]\n_program.py:3: note: Revealed type is \"_io.TextIOWrapper[_io._WrappedBuffer]\"\n_program.py:4: note: Revealed type is \"_io.TextIOWrapper[_io._WrappedBuffer]\"\n_program.py:5: note: Revealed type is \"_io.BufferedReader\"\n_program.py:7: note: Revealed type is \"typing.IO[Any]\"\n\n[case testPathOpenReturnTypeInferenceSpecialCases]\nfrom pathlib import Path\np = Path(\"x\")\nreveal_type(p.open(mode='r', errors='replace'))\nreveal_type(p.open(errors='replace', mode='r'))\nmode = 'r'\nreveal_type(p.open(mode=mode, errors='replace'))\n[out]\n_program.py:3: note: Revealed type is \"_io.TextIOWrapper[_io._WrappedBuffer]\"\n_program.py:4: note: Revealed type is \"_io.TextIOWrapper[_io._WrappedBuffer]\"\n_program.py:6: note: Revealed type is \"typing.IO[Any]\"\n\n[case testGenericPatterns]\nfrom typing import Pattern\nimport re\np: Pattern[str]\np = re.compile('foo*')\nb: Pattern[bytes]\nb = re.compile(b'foo*')\nm = p.match('fooo')\nassert m\nprint(m.group(0))\n[out]\nfooo\n\n[case testGenericMatch]\nfrom typing import Match, Optional\nimport re\ndef f(m: Optional[Match[bytes]]) -> None:\n    assert m\n    print(m.group(0))\nf(re.match(b'x*', b'xxy'))\n[out]\nb'xx'\n\n[case testIntFloatDucktyping]\nx: float\nx = 2.2\nx = 2\ndef f(x: float) -> None: pass\nf(1.1)\nf(1)\n[out]\n\n[case testsFloatOperations]\nimport typing\nprint(1.5 + 1.5)\nprint(1.5 + 1)\n[out]\n3.0\n2.5\n\n[case testMathFunctionWithIntArgument]\nimport typing\nimport math\nmath.sin(2)\nmath.sin(2.2)\n\n[case testAbsReturnType]\nf: float\nn: int\nn = abs(2)\nf = abs(2.2)\nabs(2.2) + 'x'\n[out]\n_program.py:5: error: Unsupported operand types for + (\"float\" and \"str\")\n\n[case testROperatorMethods]\nb: bytes\ns: str\nif int():\n    s = b'foo' * 5 # Error\nif int():\n    b = 5 * b'foo'\nif int():\n    b = b'foo' * 5\nif int():\n    s = 5 * 'foo'\nif int():\n    s = 'foo' * 5\n[out]\n_program.py:4: error: Incompatible types in assignment (expression has type \"bytes\", variable has type \"str\")\n\n[case testROperatorMethods2]\nimport typing\nprint(2 / 0.5)\nprint(' ', 2 * [3, 4])\n[out]\n4.0\n  [3, 4, 3, 4]\n\n[case testNotImplemented]\nimport typing\nclass A:\n    def __add__(self, x: int) -> int:\n        if isinstance(x, int):\n            return x + 1\n        return NotImplemented\nclass B:\n    def __radd__(self, x: A) -> str:\n        return 'x'\nprint(A() + 1)\nprint(A() + B())\n[out]\n2\nx\n\n[case testMappingMethods]\n# Regression test\nfrom typing import Mapping\nx = {'x': 'y'} # type: Mapping[str, str]\nprint('x' in x)\nprint('y' in x)\n[out]\nTrue\nFalse\n\n[case testOverlappingOperatorMethods]\nclass X: pass\nclass A:\n    def __add__(self, x: object) -> int:\n        if isinstance(x, X):\n            return 1\n        return NotImplemented\nclass B:\n    def __radd__(self, x: A) -> str: return 'x'\nclass C(X, B): pass\nb: B\nb = C()\nprint(A() + b)\n[out]\n_program.py:8: error: Signatures of \"__radd__\" of \"B\" and \"__add__\" of \"A\" are unsafely overlapping\n\n[case testBytesAndBytearrayComparisons]\nimport typing\nprint(b'ab' < bytearray(b'b'))\nprint(bytearray(b'ab') < b'a')\n[out]\nTrue\nFalse\n\n[case testBytesAndBytearrayComparisons2]\nimport typing\n'' < b''\nb'' < ''\n'' < bytearray()\nbytearray() < ''\n[out]\n_program.py:2: error: Unsupported operand types for < (\"str\" and \"bytes\")\n_program.py:3: error: Unsupported operand types for < (\"bytes\" and \"str\")\n_program.py:4: error: Unsupported operand types for < (\"str\" and \"bytearray\")\n_program.py:5: error: Unsupported operand types for < (\"bytearray\" and \"str\")\n\n[case testInplaceOperatorMethod]\nimport typing\na = [1]\nprint('', a.__iadd__([2]))\nprint('', a)\n[out]\n [1, 2]\n [1, 2]\n\n[case testListInplaceAdd]\nimport typing\na = [1]\na += iter([2, 3])\nprint(tuple(a))\n[out]\n(1, 2, 3)\n\n[case testInferHeterogeneousListOfIterables]\nfrom typing import Sequence\ns = ['x', 'y'] # type: Sequence[str]\na = [['x', 'x'], 'fo', s, iter('foo'), {'aa'}]\nfor i, x in enumerate(a):\n    print(i, next(iter(x)))\n[out]\n0 x\n1 f\n2 x\n3 f\n4 aa\n\n[case testTextIOProperties]\nimport typing\nimport sys\nprint(type(sys.stdin.encoding))\nprint(type(sys.stdin.errors))\nsys.stdin.line_buffering\nsys.stdin.buffer\nsys.stdin.newlines\n[out]\n<class 'str'>\n<class 'str'>\n\n[case testIOProperties]\nimport typing\nimport sys\nprint(sys.stdin.name)\nprint(sys.stdin.buffer.mode)\n[out]\n<stdin>\nrb\n\n[case testFromFuturePrintFunction]\nfrom __future__ import print_function\nprint('a', 'b')\n[out]\na b\n\n[case testListMethods]\nimport typing\nimport sys\nl = [0, 1, 2, 3, 4]\nif sys.version >= '3.3':\n    l.clear()\nelse:\n    l = []\nl.append(0)\nprint('>', l)\nif sys.version >= '3.3':\n    m = l.copy()\nelse:\n    m = l[:]\nm.extend([1, 2, 3, 4])\nprint('>', m)\nprint(l.index(0))\nprint(l.index(0, 0))\nprint(l.index(0, 0, 1))\ntry:\n    print(l.index(1))\n    print('expected ValueError')\nexcept ValueError:\n    pass\nl.insert(0, 1)\nprint('>', l)\nprint(l.pop(0))\nprint(l.pop())\nm.remove(0)\ntry:\n    m.remove(0)\n    print('expected ValueError')\nexcept ValueError:\n    pass\nm.reverse()\nm.sort()\nm.sort(key=lambda x: -x)\nm.sort(reverse=False)\nm.sort(key=lambda x: -x, reverse=True)\nprint('>', m)\n[out]\n> [0]\n> [0, 1, 2, 3, 4]\n0\n0\n0\n> [1, 0]\n1\n0\n> [1, 2, 3, 4]\n\n[case testListOperators]\nimport typing\nl = [0, 1]\nprint('+', l + [2])\nprint('*', l * 2)\nprint('*', 2 * l)\nprint('in', 1 in l)\nprint('==', l == [1, 2])\nprint('!=', l != [1, 2])\nprint('>', l > [1, 2, 3])\nprint('>=', l >= [1, 2, 3])\nprint('<', l < [1, 2, 3])\nprint('<=', l <= [1, 2, 3])\nprint('>[0]', l[0])\nl += [2]\nprint('+=', l)\nl *= 2\nprint('*=', l)\nprint('iter', list(iter(l)))\nprint('len', len(l))\nprint('repr', repr(l))\nl[:3] = []\nprint('setslice', l)\nprint('reversed', list(reversed(l)))\n[out]\n+ [0, 1, 2]\n* [0, 1, 0, 1]\n* [0, 1, 0, 1]\nin True\n== False\n!= True\n> False\n>= False\n< True\n<= True\n>[0] 0\n+= [0, 1, 2]\n*= [0, 1, 2, 0, 1, 2]\niter [0, 1, 2, 0, 1, 2]\nlen 6\nrepr [0, 1, 2, 0, 1, 2]\nsetslice [0, 1, 2]\nreversed [2, 1, 0]\n\n[case testTupleAsSubtypeOfSequence]\nfrom typing import TypeVar, Sequence\nT = TypeVar('T')\ndef f(a: Sequence[T]) -> None: print(a)\nf(tuple())\n[out]\n()\n\n[case testMapWithLambdaSpecialCase]\nfrom typing import List, Iterator\na = [[1], [3]]\nb = map(lambda y: y[0], a)\nprint('>', list(b))\n[out]\n> [1, 3]\n\n[case testInternalBuiltinDefinition]\nimport typing\ndef f(x: _T) -> None: pass\ns: FrozenSet\n[out]\n_program.py:2: error: Name \"_T\" is not defined\n_program.py:3: error: Name \"FrozenSet\" is not defined\n\n[case testVarArgsFunctionSubtyping]\nimport typing\ndef f(*args: str) -> str: return args[0]\nmap(f, ['x'])\nmap(f, [1])\n[out]\n_program.py:4: error: Argument 1 to \"map\" has incompatible type \"Callable[[VarArg(str)], str]\"; expected \"Callable[[int], str]\"\n\n[case testMapStr]\nimport typing\nx = range(3)\na = list(map(str, x))\na + 1\n[out]\n_testMapStr.py:4: error: No overload variant of \"__add__\" of \"list\" matches argument type \"int\"\n_testMapStr.py:4: note: Possible overload variants:\n_testMapStr.py:4: note:     def __add__(self, List[str], /) -> List[str]\n_testMapStr.py:4: note:     def [_S] __add__(self, List[_S], /) -> List[Union[_S, str]]\n\n[case testRelativeImport]\nimport typing\nfrom m import x\nprint(x)\n[file m/__init__.py]\nfrom .n import x\n[file m/n.py]\nx = 1\n[out]\n1\n\n[case testRelativeImport2]\nimport typing\nfrom m.n import x\nprint(x)\n[file m/__init__.py]\n[file m/n.py]\nfrom .nn import x\n[file m/nn.py]\nx = 2\n[out]\n2\n\n[case testPyiTakesPrecedenceOverPy]\nimport m\nm.f(1)\n[file m.py]\ndef f(x):\n    print(x)\n[file m.pyi]\nimport typing\ndef f(x: str) -> None: pass\n[out]\n_program.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testComplexArithmetic]\nimport typing\nprint(5 + 8j)\nprint(3j * 2.0)\nprint(4J / 2.0)\n[out]\n(5+8j)\n6j\n2j\n\n[case testComplexArithmetic2]\nx = 5 + 8j\nif int():\n    x = '' # E\ny = 3j * 2.0\nif int():\n    y = '' # E\n[out]\n_program.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"complex\")\n_program.py:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"complex\")\n\n[case testSuperNew]\nfrom typing import Dict, Any\nclass MyType(type):\n    def __new__(cls, name: str, bases: tuple, namespace: Dict[str, Any]) -> Any:\n        return super().__new__(cls, name + 'x', bases, namespace)\nclass A(metaclass=MyType): pass\nprint(type(A()).__name__)\n[out]\nAx\n\n[case testSubclassBothGenericAndNonGenericABC]\nfrom typing import Generic, TypeVar\nfrom abc import ABCMeta\nT = TypeVar('T')\nclass A(metaclass=ABCMeta): pass\nclass B(Generic[T]): pass\nclass C(A, B): pass\nclass D(B, A): pass\nclass E(A, B[T], Generic[T]): pass\nclass F(B[T], A, Generic[T]): pass\ndef f(e: E[int], f: F[int]) -> None: pass\n[out]\n\n[case testTypeVariableTypeComparability]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef eq(x: T, y: T, z: T) -> T:\n    if x == y:\n        return y\n    else:\n        return z\nprint(eq(1, 2, 3))\nprint(eq('x', 'x', 'z'))\n[out]\n3\nx\n\n[case testIntDecimalCompatibility]\nimport typing\nfrom decimal import Decimal\nprint(Decimal(1) + 2)\nprint(Decimal(1) - 2)\nprint(1 + Decimal('2.34'))\nprint(1 - Decimal('2.34'))\nprint(2 * Decimal('2.34'))\n[out]\n3\n-1\n3.34\n-1.34\n4.68\n\n[case testInstantiateBuiltinTypes]\nfrom typing import Dict, Set, List\nd = dict()  # type: Dict[int, str]\ns = set()   # type: Set[int]\nl = list()  # type: List[int]\nstr()\nbytes()\nbytearray()\nint()\nfloat()\ncomplex()\nslice(1)\nbool()\n\n[case testVariableLengthTupleError]\nfrom typing import Tuple\ndef p(t: Tuple[str, ...]) -> None:\n    n = 5\n    print(t[n])\n    for s in t:\n        s()\n''.startswith(('x', 'y'))\n''.startswith(('x', b'y'))\n[out]\n_program.py:6: error: \"str\" not callable\n_program.py:8: error: Argument 1 to \"startswith\" of \"str\" has incompatible type \"Tuple[str, bytes]\"; expected \"Union[str, Tuple[str, ...]]\"\n\n[case testMultiplyTupleByInteger]\nn = 4\nt = ('',) * n\nt + 1\n[out]\n_program.py:3: error: No overload variant of \"__add__\" of \"tuple\" matches argument type \"int\"\n_program.py:3: note: Possible overload variants:\n_program.py:3: note:     def __add__(self, Tuple[str, ...], /) -> Tuple[str, ...]\n_program.py:3: note:     def [_T] __add__(self, Tuple[_T, ...], /) -> Tuple[Union[str, _T], ...]\n\n[case testMultiplyTupleByIntegerReverse]\nn = 4\nt = n * ('',)\nt + 1\n[out]\n_program.py:3: error: No overload variant of \"__add__\" of \"tuple\" matches argument type \"int\"\n_program.py:3: note: Possible overload variants:\n_program.py:3: note:     def __add__(self, Tuple[str, ...], /) -> Tuple[str, ...]\n_program.py:3: note:     def [_T] __add__(self, Tuple[_T, ...], /) -> Tuple[Union[str, _T], ...]\n\n[case testDictWithKeywordArgs]\nfrom typing import Dict, Any, List\nd1 = dict(a=1, b=2) # type: Dict[str, int]\nd2 = dict(a=1, b='') # type: Dict[str, int] # E\nd3 = dict(a=1, b=1)\nd3.xyz # E\nd4 = dict(a=1, b='') # type: Dict[str, Any]\nresult = dict(x=[], y=[]) # type: Dict[str, List[str]]\n[out]\n_program.py:3: error: Dict entry 1 has incompatible type \"str\": \"str\"; expected \"str\": \"int\"\n_program.py:5: error: \"Dict[str, int]\" has no attribute \"xyz\"\n\n[case testDefaultDict]\n# flags: --new-type-inference\nimport typing as t\nfrom collections import defaultdict\n\nT = t.TypeVar('T')\n\nd1 = defaultdict(list) # type: t.DefaultDict[int, str]\nd2 = defaultdict() # type: t.DefaultDict[int, str]\nd2[0] = '0'\nd2['0'] = 0\n\ndef tst(dct: t.DefaultDict[int, T]) -> T:\n    return dct[0]\n\ncollections = ['coins', 'stamps', 'comics'] # type: t.List[str]\nd3 = defaultdict(str) # type: t.DefaultDict[int, str]\ncollections[2]\n\ntst(defaultdict(list, {0: []}))\ntst(defaultdict(list, {'0': []}))\n\nclass MyDDict(t.DefaultDict[int,T], t.Generic[T]):\n    pass\nMyDDict(dict)['0']\nMyDDict(dict)[0]\n[out]\n_program.py:7: error: Argument 1 to \"defaultdict\" has incompatible type \"Type[List[_T]]\"; expected \"Optional[Callable[[], str]]\"\n_program.py:10: error: Invalid index type \"str\" for \"defaultdict[int, str]\"; expected type \"int\"\n_program.py:10: error: Incompatible types in assignment (expression has type \"int\", target has type \"str\")\n_program.py:20: error: Argument 1 to \"tst\" has incompatible type \"defaultdict[str, List[Never]]\"; expected \"defaultdict[int, List[Never]]\"\n_program.py:24: error: Invalid index type \"str\" for \"MyDDict[Dict[Never, Never]]\"; expected type \"int\"\n\n[case testCollectionsAliases]\nimport typing as t\nimport collections as c\n\no1 = c.Counter()  # type: t.Counter[int]\nreveal_type(o1)\no1['string']\n\no2 = c.ChainMap()  # type: t.ChainMap[int, str]\nreveal_type(o2)\n\no3 = c.deque()  # type: t.Deque[int]\nreveal_type(o3)\n\no4 = t.Counter[int]()\nreveal_type(o4)\n\no5 = t.ChainMap[int, str]()\nreveal_type(o5)\n\no6 = t.Deque[int]()\nreveal_type(o6)\n\n[out]\n_testCollectionsAliases.py:5: note: Revealed type is \"collections.Counter[builtins.int]\"\n_testCollectionsAliases.py:6: error: Invalid index type \"str\" for \"Counter[int]\"; expected type \"int\"\n_testCollectionsAliases.py:9: note: Revealed type is \"collections.ChainMap[builtins.int, builtins.str]\"\n_testCollectionsAliases.py:12: note: Revealed type is \"collections.deque[builtins.int]\"\n_testCollectionsAliases.py:15: note: Revealed type is \"collections.Counter[builtins.int]\"\n_testCollectionsAliases.py:18: note: Revealed type is \"collections.ChainMap[builtins.int, builtins.str]\"\n_testCollectionsAliases.py:21: note: Revealed type is \"collections.deque[builtins.int]\"\n\n[case testChainMapUnimported]\nChainMap[int, str]()\n\n[out]\n_testChainMapUnimported.py:1: error: Name \"ChainMap\" is not defined\n\n[case testDequeWrongCase]\nimport collections\nimport typing\n\ncollections.Deque()\ntyping.deque()\n\n[out]\n_testDequeWrongCase.py:4: error: Module has no attribute \"Deque\"; maybe \"deque\"?\n_testDequeWrongCase.py:5: error: Module has no attribute \"deque\"; maybe \"Deque\"?\n\n[case testDictUpdateInference]\nfrom typing import Dict, Optional\nd = {}  # type: Dict[str, Optional[int]]\nd.update({str(i): None for i in range(4)})\n\n[case testSuperAndSetattr]\nclass A:\n    def __init__(self) -> None:\n        super().__setattr__('a', 1)\n        super().__setattr__(1, 'a')\n[out]\n_program.py:4: error: Argument 1 to \"__setattr__\" of \"object\" has incompatible type \"int\"; expected \"str\"\n\n[case testMetaclassAndSuper]\nfrom typing import Any\n\nclass A(type):\n    def __new__(cls, name, bases, namespace) -> Any:\n        return super().__new__(cls, '', (object,), {'x': 7})\n\nclass B(metaclass=A):\n    pass\n\nprint(getattr(B(), 'x'))\n[out]\n7\n\n[case testSortedNoError]\nfrom typing import Iterable, Callable, TypeVar, List, Dict, Optional\nT = TypeVar('T')\ndef sorted(x: Iterable[T], *, key: Optional[Callable[[T], object]] = None) -> None: ...\na = []  # type: List[Dict[str, str]]\nsorted(a, key=lambda y: y[''])\n\n[case testAbstractProperty]\nfrom abc import abstractproperty, ABCMeta  # type: ignore[deprecated]\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\nclass B(A):\n    @property\n    def x(self) -> int:\n        return 3\nb = B()\nprint(b.x + 1)\n[out]\n4\n\n[case testInferenceWithLambda]\nfrom typing import TypeVar, Iterable, Iterator, List\nimport itertools\n\n_T = TypeVar('_T')\n\ndef f(iterable): # type: (Iterable[_T]) -> Iterator[List[_T]]\n    grouped = itertools.groupby(enumerate(iterable), lambda pair: pair[0] // 2)\n    return ([elem for _, elem in group] for _, group in grouped)\n\n[case testReModuleBytes]\n# Regression tests for various overloads in the re module -- bytes version\nimport re\nbre = b'a+'\nbpat = re.compile(bre)\nbpat = re.compile(bpat)\ns1 = re.search(bre, b'')\nassert s1\ns1.groups()\nre.search(bre, u'') # Error\ns2 = re.search(bpat, b'')\nassert s2\ns2.groups()\nre.search(bpat, u'') # Error\n# match(), split(), findall(), finditer() are much the same, so skip those.\n# sub(), subn() have more overloads and we are checking these:\nre.sub(bre, b'', b'') + b''\nre.sub(bpat, b'', b'') + b''\nre.sub(bre, lambda m: b'', b'') + b''\nre.sub(bpat, lambda m: b'', b'') + b''\nre.subn(bre, b'', b'')[0] + b''\nre.subn(bpat, b'', b'')[0] + b''\nre.subn(bre, lambda m: b'', b'')[0] + b''\nre.subn(bpat, lambda m: b'', b'')[0] + b''\n[out]\n_testReModuleBytes.py:9: error: No overload variant of \"search\" matches argument types \"bytes\", \"str\"\n_testReModuleBytes.py:9: note: Possible overload variants:\n_testReModuleBytes.py:9: note:     def search(pattern: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]]\n_testReModuleBytes.py:9: note:     def search(pattern: Union[bytes, Pattern[bytes]], string: Buffer, flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]]\n_testReModuleBytes.py:13: error: Argument 1 to \"search\" has incompatible type \"Pattern[bytes]\"; expected \"Union[str, Pattern[str]]\"\n\n[case testReModuleString]\n# Regression tests for various overloads in the re module -- string version\nimport re\nsre = 'a+'\nspat = re.compile(sre)\nspat = re.compile(spat)\ns1 = re.search(sre, '')\nassert s1\ns1.groups()\nre.search(sre, b'') # Error\ns2 = re.search(spat, '')\nassert s2\ns2.groups()\nre.search(spat, b'') # Error\n# match(), split(), findall(), finditer() are much the same, so skip those.\n# sus(), susn() have more overloads and we are checking these:\nre.sub(sre, '', '') + ''\nre.sub(spat, '', '') + ''\nre.sub(sre, lambda m: '', '') + ''\nre.sub(spat, lambda m: '', '') + ''\nre.subn(sre, '', '')[0] + ''\nre.subn(spat, '', '')[0] + ''\nre.subn(sre, lambda m: '', '')[0] + ''\nre.subn(spat, lambda m: '', '')[0] + ''\n[out]\n_testReModuleString.py:9: error: No overload variant of \"search\" matches argument types \"str\", \"bytes\"\n_testReModuleString.py:9: note: Possible overload variants:\n_testReModuleString.py:9: note:     def search(pattern: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]]\n_testReModuleString.py:9: note:     def search(pattern: Union[bytes, Pattern[bytes]], string: Buffer, flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]]\n_testReModuleString.py:13: error: Argument 1 to \"search\" has incompatible type \"Pattern[str]\"; expected \"Union[bytes, Pattern[bytes]]\"\n\n[case testListSetitemTuple]\nfrom typing import List, Tuple\na = []  # type: List[Tuple[str, int]]\na[0] = 'x', 1\na[1] = 2, 'y'\na[:] = [('z', 3)]\n[out]\n_program.py:4: error: Incompatible types in assignment (expression has type \"Tuple[int, str]\", target has type \"Tuple[str, int]\")\n\n[case testContextManager]\nimport contextlib\nfrom contextlib import contextmanager\nfrom typing import Iterator\n\n@contextmanager\ndef f(x: int) -> Iterator[str]:\n    yield 'foo'\n\n@contextlib.contextmanager\ndef g(*x: str) -> Iterator[int]:\n    yield 1\n\nreveal_type(f)\nreveal_type(g)\n\nwith f('') as s:\n    reveal_type(s)\n[out]\n_program.py:13: note: Revealed type is \"def (x: builtins.int) -> contextlib._GeneratorContextManager[builtins.str, None, None]\"\n_program.py:14: note: Revealed type is \"def (*x: builtins.str) -> contextlib._GeneratorContextManager[builtins.int, None, None]\"\n_program.py:16: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n_program.py:17: note: Revealed type is \"builtins.str\"\n\n[case testTypedDictGet]\n# Test that TypedDict get plugin works with typeshed stubs\nfrom mypy_extensions import TypedDict\nclass A: pass\nD = TypedDict('D', {'x': int, 'y': str})\nd: D\nreveal_type(d.get('x'))\nreveal_type(d.get('y'))\nreveal_type(d.get('z'))\nd.get()\ns = ''\nreveal_type(d.get(s))\n[out]\n_testTypedDictGet.py:6: note: Revealed type is \"Union[builtins.int, None]\"\n_testTypedDictGet.py:7: note: Revealed type is \"Union[builtins.str, None]\"\n_testTypedDictGet.py:8: note: Revealed type is \"builtins.object\"\n_testTypedDictGet.py:9: error: All overload variants of \"get\" of \"Mapping\" require at least one argument\n_testTypedDictGet.py:9: note: Possible overload variants:\n_testTypedDictGet.py:9: note:     def get(self, str, /) -> object\n_testTypedDictGet.py:9: note:     def [_T] get(self, str, /, default: object) -> object\n_testTypedDictGet.py:11: note: Revealed type is \"builtins.object\"\n\n[case testTypedDictMappingMethods]\nfrom mypy_extensions import TypedDict\nCell = TypedDict('Cell', {'value': int})\nc = Cell(value=42)\nfor x in c:\n    reveal_type(x)\nreveal_type(iter(c))\nreveal_type(len(c))\nreveal_type('value' in c)\nreveal_type(c.keys())\nreveal_type(c.items())\nreveal_type(c.values())\nreveal_type(c.copy())\nreveal_type(c.setdefault('value', False))\nc.update({'value': 2})\nc.update({'invalid': 2})\nc.pop('value')\nc == c\nc != c\nCell2 = TypedDict('Cell2', {'value': int}, total=False)\nc2 = Cell2()\nreveal_type(c2.pop('value'))\n[out]\n_testTypedDictMappingMethods.py:5: note: Revealed type is \"builtins.str\"\n_testTypedDictMappingMethods.py:6: note: Revealed type is \"typing.Iterator[builtins.str]\"\n_testTypedDictMappingMethods.py:7: note: Revealed type is \"builtins.int\"\n_testTypedDictMappingMethods.py:8: note: Revealed type is \"builtins.bool\"\n_testTypedDictMappingMethods.py:9: note: Revealed type is \"_collections_abc.dict_keys[builtins.str, builtins.object]\"\n_testTypedDictMappingMethods.py:10: note: Revealed type is \"_collections_abc.dict_items[builtins.str, builtins.object]\"\n_testTypedDictMappingMethods.py:11: note: Revealed type is \"_collections_abc.dict_values[builtins.str, builtins.object]\"\n_testTypedDictMappingMethods.py:12: note: Revealed type is \"TypedDict('_testTypedDictMappingMethods.Cell', {'value': builtins.int})\"\n_testTypedDictMappingMethods.py:13: note: Revealed type is \"builtins.int\"\n_testTypedDictMappingMethods.py:15: error: Unexpected TypedDict key \"invalid\"\n_testTypedDictMappingMethods.py:16: error: Key \"value\" of TypedDict \"Cell\" cannot be deleted\n_testTypedDictMappingMethods.py:21: note: Revealed type is \"builtins.int\"\n\n[case testCrashOnComplexCheckWithNamedTupleNext]\nfrom typing import NamedTuple, Optional\n\nMyNamedTuple = NamedTuple('MyNamedTuple', [('parent', 'MyNamedTuple')]) # type: ignore\ndef foo(mymap) -> Optional[MyNamedTuple]:\n    return next((mymap[key] for key in mymap), None)\n[out]\n\n[case testCanConvertTypedDictToAnySuperclassOfMapping]\nfrom mypy_extensions import TypedDict\nfrom typing import Sized, Iterable, Container\n\nPoint = TypedDict('Point', {'x': int, 'y': int})\n\np: Point\ns: Sized = p\nit: Iterable[str] = p\nc: Container[str] = p\no: object = p\nit2: Iterable[int] = p\n[out]\n_testCanConvertTypedDictToAnySuperclassOfMapping.py:11: error: Incompatible types in assignment (expression has type \"Point\", variable has type \"Iterable[int]\")\n_testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note: Following member(s) of \"Point\" have conflicts:\n_testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note:     Expected:\n_testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note:         def __iter__(self) -> Iterator[int]\n_testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note:     Got:\n_testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note:         def __iter__(self) -> Iterator[str]\n\n[case testAsyncioGatherPreciseType-xfail]\n# Mysteriously regressed in #11905\nimport asyncio\nfrom typing import Tuple\n\nasync def get_location(arg: str) -> Tuple[str, str]:\n    return arg, arg\n\nasync def main() -> None:\n    ((a_x, a_y),) = await asyncio.gather(get_location('start'))\n    reveal_type(a_x)\n    reveal_type(a_y)\nreveal_type(asyncio.gather(*[asyncio.sleep(1), asyncio.sleep(1)]))\n[out]\n_testAsyncioGatherPreciseType.py:9: note: Revealed type is \"builtins.str\"\n_testAsyncioGatherPreciseType.py:10: note: Revealed type is \"builtins.str\"\n_testAsyncioGatherPreciseType.py:11: note: Revealed type is \"asyncio.futures.Future[builtins.list[Any]]\"\n\n[case testMultipleInheritanceWorksWithTupleTypeGeneric]\nfrom typing import SupportsAbs, NamedTuple\n\nclass Point(NamedTuple('Point', [('x', int), ('y', int)]), SupportsAbs[int]):\n    def __abs__(p) -> int:\n        return abs(p.x) + abs(p.y)\n\ndef test(a: Point) -> bool:\n    return abs(a) == 2\n[out]\n\n[case testNoCrashOnGenericUnionUnpacking]\nfrom typing import Union, Dict\n\nTEST = {'key': ('a', 'b')}\ndef test() -> None:\n    a, b = TEST.get('foo', ('x', 'y'))\n    reveal_type(a)\n    reveal_type(b)\ndef test2() -> None:\n    a, b = TEST.get('foo', (1, 2))\n    reveal_type(a)\n    reveal_type(b)\n\nx: Union[Dict[int, int], Dict[str, str]]\nif bool():\n    x = dict(a='b')\nfor a, b in x.items():\n    reveal_type(a)\n    reveal_type(b)\n[out]\n_testNoCrashOnGenericUnionUnpacking.py:6: note: Revealed type is \"builtins.str\"\n_testNoCrashOnGenericUnionUnpacking.py:7: note: Revealed type is \"builtins.str\"\n_testNoCrashOnGenericUnionUnpacking.py:10: note: Revealed type is \"Union[builtins.str, builtins.int]\"\n_testNoCrashOnGenericUnionUnpacking.py:11: note: Revealed type is \"Union[builtins.str, builtins.int]\"\n_testNoCrashOnGenericUnionUnpacking.py:17: note: Revealed type is \"Union[builtins.int, builtins.str]\"\n_testNoCrashOnGenericUnionUnpacking.py:18: note: Revealed type is \"Union[builtins.int, builtins.str]\"\n\n[case testMetaclassOpAccess]\nfrom typing import Type\nclass A:\n    pass\n\nclass Meta(type):\n    def __mul__(self, other: int) -> Type[A]:\n        pass\n    def __add__(self, other: int) -> Type[C]:\n        pass\n    def __radd__(self, other: int) -> Type[C]:\n        pass\nclass C(metaclass=Meta):\n    pass\n\nbar: Type[C]\ndef get_c_type() -> Type[C]:\n    pass\n\nres = bar * 4\nother = 4 + get_c_type() + 5\nreveal_type(res)\nreveal_type(other)\n[out]\n_testMetaclassOpAccess.py:21: note: Revealed type is \"Type[_testMetaclassOpAccess.A]\"\n_testMetaclassOpAccess.py:22: note: Revealed type is \"Type[_testMetaclassOpAccess.C]\"\n\n[case testMetaclassOpAccessUnion]\nfrom typing import Type, Union\n\nclass MetaA(type):\n    def __mul__(self, other: int) -> str:\n        pass\nclass A(metaclass=MetaA):\n    pass\nclass MetaB(type):\n    def __mul__(self, other: int) -> int:\n        pass\nclass B(metaclass=MetaB):\n    pass\n\nbar: Type[Union[A, B]]\nres = bar * 4\nreveal_type(res)\n[out]\n_testMetaclassOpAccessUnion.py:16: note: Revealed type is \"Union[builtins.str, builtins.int]\"\n\n[case testMetaclassOpAccessAny]\nfrom typing import Type\nfrom nonexistent import C\nbar: Type[C]\n\nbar * 4 + bar + 3  # should not produce more errors\n[out]\n_testMetaclassOpAccessAny.py:2: error: Cannot find implementation or library stub for module named \"nonexistent\"\n_testMetaclassOpAccessAny.py:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testEnumIterationAndPreciseElementType]\n# Regression test for #2305\nfrom enum import Enum\nclass E(Enum):\n    A = 'a'\n(reveal_type(e) for e in E)\nfor e in E:\n    reveal_type(e)\n[out]\n_testEnumIterationAndPreciseElementType.py:5: note: Revealed type is \"_testEnumIterationAndPreciseElementType.E\"\n_testEnumIterationAndPreciseElementType.py:7: note: Revealed type is \"_testEnumIterationAndPreciseElementType.E\"\n\n[case testEnumIterable]\nfrom enum import Enum\nfrom typing import Iterable\nclass E(Enum):\n    A = 'a'\ndef f(ie: Iterable[E]):\n    pass\nf(E)\n\n[case testIntEnumIterable]\nfrom enum import IntEnum\nfrom typing import Iterable\nclass N(IntEnum):\n    X = 1\ndef f(ni: Iterable[N]):\n    pass\ndef g(ii: Iterable[int]):\n    pass\nf(N)\ng(N)\nreveal_type(list(N))\n[out]\n_testIntEnumIterable.py:11: note: Revealed type is \"builtins.list[_testIntEnumIterable.N]\"\n\n[case testDerivedEnumIterable]\nfrom enum import Enum\nfrom typing import Iterable\nclass E(str, Enum):\n    A = 'foo'\ndef f(ei: Iterable[E]):\n    pass\ndef g(si: Iterable[str]):\n    pass\nf(E)\ng(E)\n\n[case testInvalidSlots]\nfrom typing import List\nclass A:\n    __slots__ = 1\nclass B:\n    __slots__ = (1, 2)\nclass C:\n    __slots__: List[int] = []\n[out]\n_testInvalidSlots.py:3: error: Invalid type for \"__slots__\" (actual type \"int\", expected type \"Union[str, Iterable[str]]\")\n_testInvalidSlots.py:5: error: Invalid type for \"__slots__\" (actual type \"Tuple[int, int]\", expected type \"Union[str, Iterable[str]]\")\n_testInvalidSlots.py:7: error: Invalid type for \"__slots__\" (actual type \"List[int]\", expected type \"Union[str, Iterable[str]]\")\n\n[case testDictWithStarStarSpecialCase]\nfrom typing import Dict\n\ndef f() -> Dict[int, str]:\n    return {1: '', **d()}\n\ndef d() -> Dict[int, int]:\n    return {}\n[out]\n_testDictWithStarStarSpecialCase.py:4: error: Unpacked dict entry 1 has incompatible type \"Dict[int, int]\"; expected \"SupportsKeysAndGetItem[int, str]\"\n\n[case testLoadsOfOverloads]\nfrom typing import overload, Any, TypeVar, Iterable, List, Dict, Callable, Union\n\nS = TypeVar('S')\nT = TypeVar('T')\n\n@overload\ndef simple_map() -> None: ...\n@overload\ndef simple_map(func: Callable[[T], S], one: Iterable[T]) -> S: ...\n@overload\ndef simple_map(func: Callable[..., S], *iterables: Iterable[Any]) -> S: ...\ndef simple_map(*args): pass\n\ndef format_row(*entries: object) -> str: pass\n\nclass DateTime: pass\nJsonBlob = Dict[str, Any]\nColumn = Union[List[str], List[int], List[bool], List[float], List[DateTime], List[JsonBlob]]\n\ndef print_custom_table() -> None:\n    a: Column\n\n    for row in simple_map(format_row, a, a, a, a, a, a, a, a):  # 8 columns\n        reveal_type(row)\n[out]\n_testLoadsOfOverloads.py:24: note: Revealed type is \"builtins.str\"\n\n[case testReduceWithAnyInstance]\nfrom typing import Iterable\nfrom functools import reduce\nM = Iterable\ndef f(m1: M, m2):\n    ...\ndef g(ms: 'T[M]') -> None:\n    reduce(f, ms)\nT = Iterable\n[out]\n\n[case testNamedTupleNew]\n# This is an eval test because there was a snag found only with full stubs\nfrom typing import NamedTuple\n\nBase = NamedTuple('Base', [('param', int)])\n\nclass Child(Base):\n    def __new__(cls, param: int = 1) -> 'Child':\n        return Base.__new__(cls, param)\n\nBase(param=10)\nChild(param=10)\nreveal_type(Child())\n\nfrom collections import namedtuple\nX = namedtuple('X', ['a', 'b'])\nx = X(a=1, b='s')\n\n[out]\n_testNamedTupleNew.py:12: note: Revealed type is \"Tuple[builtins.int, fallback=_testNamedTupleNew.Child]\"\n\n[case testNamedTupleTypeInheritanceSpecialCase]\nfrom typing import NamedTuple, Tuple\nfrom collections import namedtuple\n\nA = NamedTuple('A', [('param', int)])\nB = namedtuple('B', ['param'])\n\ndef accepts_named_tuple(arg: NamedTuple):\n    reveal_type(arg._asdict())\n    reveal_type(arg._fields)\n    reveal_type(arg._field_defaults)\n\na = A(1)\nb = B(1)\n\naccepts_named_tuple(a)\naccepts_named_tuple(b)\naccepts_named_tuple(1)\naccepts_named_tuple((1, 2))\n[out]\n_testNamedTupleTypeInheritanceSpecialCase.py:8: note: Revealed type is \"builtins.dict[builtins.str, Any]\"\n_testNamedTupleTypeInheritanceSpecialCase.py:9: note: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n_testNamedTupleTypeInheritanceSpecialCase.py:10: note: Revealed type is \"builtins.dict[builtins.str, Any]\"\n_testNamedTupleTypeInheritanceSpecialCase.py:17: error: Argument 1 to \"accepts_named_tuple\" has incompatible type \"int\"; expected \"NamedTuple\"\n_testNamedTupleTypeInheritanceSpecialCase.py:18: error: Argument 1 to \"accepts_named_tuple\" has incompatible type \"Tuple[int, int]\"; expected \"NamedTuple\"\n\n[case testNewAnalyzerBasicTypeshed_newsemanal]\nfrom typing import Dict, List, Tuple\n\nx: Dict[str, List[int]]\nreveal_type(x['test'][0])\n[out]\n_testNewAnalyzerBasicTypeshed_newsemanal.py:4: note: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerTypedDictInStub_newsemanal]\nimport stub\nreveal_type(stub.thing)\n\n[file stub.pyi]\nfrom typing_extensions import TypedDict\n\nclass StuffDict(TypedDict):\n    foo: str\n    bar: int\n\ndef thing(stuff: StuffDict) -> int: ...\n\n[out]\n_testNewAnalyzerTypedDictInStub_newsemanal.py:2: note: Revealed type is \"def (stuff: TypedDict('stub.StuffDict', {'foo': builtins.str, 'bar': builtins.int})) -> builtins.int\"\n\n[case testStrictEqualityAllowlist]\n# mypy: strict-equality\n{1} == frozenset({1})\nfrozenset({1}) == {1}\n\nfrozenset({1}) == [1]  # Error\n\n{1: 2}.keys() == {1}\n{1: 2}.keys() == frozenset({1})\n{1: 2}.items() == {(1, 2)}\n\n{1: 2}.keys() == {'no'}  # OK\n{1: 2}.values() == {2}  # Error\n{1: 2}.keys() == [1]  # OK\n[out]\n_testStrictEqualityAllowlist.py:5: error: Non-overlapping equality check (left operand type: \"FrozenSet[int]\", right operand type: \"List[int]\")\n_testStrictEqualityAllowlist.py:12: error: Non-overlapping equality check (left operand type: \"dict_values[int, int]\", right operand type: \"Set[int]\")\n\n[case testUnreachableWithStdlibContextManagers]\n# mypy: warn-unreachable, strict-optional\n\nfrom contextlib import suppress\n\n# This test overlaps with some of the warn-unreachable tests in check-unreachable-code,\n# but 'open(...)' is a very common function so we want to make sure we don't regress\n# against it specifically\ndef f_open() -> str:\n    with open(\"foo.txt\", \"r\") as f:\n        return f.read()\n    print(\"noop\")\n\n# contextlib.suppress is less common, but it's a fairly prominent example of an\n# exception-suppressing context manager, so it'd be good to double-check.\ndef f_suppresses() -> int:\n    with suppress(Exception):\n        return 3\n    print(\"noop\")\n[out]\n_testUnreachableWithStdlibContextManagers.py:11: error: Statement is unreachable\n_testUnreachableWithStdlibContextManagers.py:15: error: Missing return statement\n\n[case testUnreachableWithStdlibContextManagersNoStrictOptional]\n# mypy: warn-unreachable, no-strict-optional\n\nfrom contextlib import suppress\n\n# When strict-optional is disabled, 'open' should still behave in the same way as before\ndef f_open() -> str:\n    with open(\"foo.txt\", \"r\") as f:\n        return f.read()\n    print(\"noop\")\n\n# ...but unfortunately, we can't\ndef f_suppresses() -> int:\n    with suppress(Exception):\n        return 3\n    print(\"noop\")\n[out]\n_testUnreachableWithStdlibContextManagersNoStrictOptional.py:9: error: Statement is unreachable\n_testUnreachableWithStdlibContextManagersNoStrictOptional.py:15: error: Statement is unreachable\n\n[case testIsInstanceAdHocIntersectionWithStrAndBytes]\n# mypy: warn-unreachable\nx: str\nif isinstance(x, bytes):\n    reveal_type(x)\ny: str\nif isinstance(x, int):\n    reveal_type(x)\n[out]\n_testIsInstanceAdHocIntersectionWithStrAndBytes.py:3: error: Subclass of \"str & bytes\" cannot exist: would have incompatible method signatures\n_testIsInstanceAdHocIntersectionWithStrAndBytes.py:4: error: Statement is unreachable\n_testIsInstanceAdHocIntersectionWithStrAndBytes.py:6: error: Subclass of \"str & int\" cannot exist: would have incompatible method signatures\n_testIsInstanceAdHocIntersectionWithStrAndBytes.py:7: error: Statement is unreachable\n\n[case testAsyncioFutureWait]\n# mypy: strict-optional\nfrom asyncio import Future, wait\nfrom typing import List\n\nasync def foo() -> None:\n    f = []  # type: List[Future[None]]\n    await wait(f)\n\n[case testShadowTypingModule]\n1 + ''\n[file typing.py]\nx = 0\n1 + ''\n[out]\nmypy: \"tmp/typing.py\" shadows library module \"typing\"\nnote: A user-defined top-level module with name \"typing\" is not supported\n\n[case testIgnoreImportIfNoPython3StubAvailable]\n# flags: --ignore-missing-imports\nimport scribe  # No Python 3 stubs available for scribe\nfrom scribe import x\nimport pytz  # Python 3 stubs available for pytz\nimport foobar_asdf\nimport jack  # This has a stubs package but was never bundled with mypy, so ignoring works\n[out]\n_testIgnoreImportIfNoPython3StubAvailable.py:4: error: Library stubs not installed for \"pytz\"\n_testIgnoreImportIfNoPython3StubAvailable.py:4: note: Hint: \"python3 -m pip install types-pytz\"\n_testIgnoreImportIfNoPython3StubAvailable.py:4: note: (or run \"mypy --install-types\" to install all missing stub packages)\n_testIgnoreImportIfNoPython3StubAvailable.py:4: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testNoPython3StubAvailable]\nimport scribe\nfrom scribe import x\nimport pytz\n[out]\n_testNoPython3StubAvailable.py:1: error: Cannot find implementation or library stub for module named \"scribe\"\n_testNoPython3StubAvailable.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n_testNoPython3StubAvailable.py:3: error: Library stubs not installed for \"pytz\"\n_testNoPython3StubAvailable.py:3: note: Hint: \"python3 -m pip install types-pytz\"\n_testNoPython3StubAvailable.py:3: note: (or run \"mypy --install-types\" to install all missing stub packages)\n\n\n[case testTypingOrderedDictAlias]\nfrom typing import OrderedDict\nx: OrderedDict[str, int] = OrderedDict({})\nreveal_type(x)\n[out]\n_testTypingOrderedDictAlias.py:3: note: Revealed type is \"collections.OrderedDict[builtins.str, builtins.int]\"\n\n[case testTypingExtensionsOrderedDictAlias]\nfrom typing_extensions import OrderedDict\nx: OrderedDict[str, str] = OrderedDict({})\nreveal_type(x)  # Revealed type is \"collections.OrderedDict[builtins.str, builtins.int]\"\n[out]\n_testTypingExtensionsOrderedDictAlias.py:3: note: Revealed type is \"collections.OrderedDict[builtins.str, builtins.str]\"\n\n[case testSpecialTypingProtocols]\n# flags: --warn-unreachable\nfrom typing import Awaitable, Hashable, Union, Tuple, List\n\nobj: Union[Tuple[int], List[int]]\nif isinstance(obj, Hashable):\n    reveal_type(obj)\nif isinstance(obj, Awaitable):\n    reveal_type(obj)\n[out]\n_testSpecialTypingProtocols.py:6: note: Revealed type is \"Tuple[builtins.int]\"\n_testSpecialTypingProtocols.py:8: error: Statement is unreachable\n\n[case testTypeshedRecursiveTypesExample]\nfrom typing import List, Union\n\nRecursive = Union[str, List[\"Recursive\"]]\n\ndef foo(r: Recursive) -> None:\n    if not isinstance(r, str):\n        if r:\n            foo(r[0])\n    if not isinstance(r, list):\n        r.casefold()\n\nfoo(\"\")\nfoo(list(\"\"))\nfoo(list((list(\"\"), \"\")))\n[out]\n\n[case testNarrowTypeForDictKeys]\nfrom typing import Dict, KeysView, Optional\n\nd: Dict[str, int]\nkey: Optional[str]\nif key in d.keys():\n    reveal_type(key)\nelse:\n    reveal_type(key)\n\nkv: KeysView[str]\nk: Optional[str]\nif k in kv:\n    reveal_type(k)\nelse:\n    reveal_type(k)\n\n[out]\n_testNarrowTypeForDictKeys.py:6: note: Revealed type is \"builtins.str\"\n_testNarrowTypeForDictKeys.py:8: note: Revealed type is \"Union[builtins.str, None]\"\n_testNarrowTypeForDictKeys.py:13: note: Revealed type is \"builtins.str\"\n_testNarrowTypeForDictKeys.py:15: note: Revealed type is \"Union[builtins.str, None]\"\n\n[case testTypeAliasWithNewStyleUnion]\n# flags: --python-version 3.10\nfrom typing import Literal, Type, TypeAlias, TypeVar\n\nFoo = Literal[1, 2]\nreveal_type(Foo)\nBar1 = Foo | Literal[3]\nBar2 = Literal[3] | Foo\nBar3 = Foo | Foo | Literal[3] | Foo\n\nU1 = int | str\nU2 = U1 | bytes\nU3 = bytes | U1\n\nOpt1 = None | int\nOpt2 = None | float\nOpt3 = int | None\nOpt4 = float | None\n\nA = Type[int] | str\nB: TypeAlias = Type[int] | str\nC = type[int] | str\n\nD = type[int] | str\nx: D\nreveal_type(x)\nE: TypeAlias = type[int] | str\ny: E\nreveal_type(y)\nF = list[type[int] | str]\n\nT = TypeVar(\"T\", int, str)\ndef foo(x: T) -> T:\n    A = type[int] | str\n    a: A\n    return x\n[out]\n_testTypeAliasWithNewStyleUnion.py:5: note: Revealed type is \"typing._SpecialForm\"\n_testTypeAliasWithNewStyleUnion.py:25: note: Revealed type is \"Union[Type[builtins.int], builtins.str]\"\n_testTypeAliasWithNewStyleUnion.py:28: note: Revealed type is \"Union[Type[builtins.int], builtins.str]\"\n\n[case testTypeAliasWithNewStyleUnionInStub]\nimport m\na: m.A\nreveal_type(a)\nb: m.B\nreveal_type(b)\nc: m.C\nreveal_type(c)\nd: m.D\nreveal_type(d)\ne: m.E\nreveal_type(e)\nf: m.F\nreveal_type(f)\n\n[file m.pyi]\nfrom typing import Type, Callable\nfrom typing_extensions import Literal, TypeAlias\n\nFoo = Literal[1, 2]\nreveal_type(Foo)\nBar1 = Foo | Literal[3]\nBar2 = Literal[3] | Foo\nBar3 = Foo | Foo | Literal[3] | Foo\n\nU1 = int | str\nU2 = U1 | bytes\nU3 = bytes | U1\n\nOpt1 = None | int\nOpt2 = None | float\nOpt3 = int | None\nOpt4 = float | None\n\nA = Type[int] | str\nB: TypeAlias = Type[int] | str\nC = type[int] | str\nreveal_type(C)\nD: TypeAlias = type[int] | str\nE = str | type[int]\nF: TypeAlias = str | type[int]\nG = list[type[int] | str]\nH = list[str | type[int]]\n\nCU1 = int | Callable[[], str | bool]\nCU2: TypeAlias = int | Callable[[], str | bool]\nCU3 = int | Callable[[str | bool], str]\nCU4: TypeAlias = int | Callable[[str | bool], str]\n[out]\nm.pyi:5: note: Revealed type is \"typing._SpecialForm\"\nm.pyi:22: note: Revealed type is \"typing._SpecialForm\"\n_testTypeAliasWithNewStyleUnionInStub.py:3: note: Revealed type is \"Union[Type[builtins.int], builtins.str]\"\n_testTypeAliasWithNewStyleUnionInStub.py:5: note: Revealed type is \"Union[Type[builtins.int], builtins.str]\"\n_testTypeAliasWithNewStyleUnionInStub.py:7: note: Revealed type is \"Union[Type[builtins.int], builtins.str]\"\n_testTypeAliasWithNewStyleUnionInStub.py:9: note: Revealed type is \"Union[Type[builtins.int], builtins.str]\"\n_testTypeAliasWithNewStyleUnionInStub.py:11: note: Revealed type is \"Union[builtins.str, Type[builtins.int]]\"\n_testTypeAliasWithNewStyleUnionInStub.py:13: note: Revealed type is \"Union[builtins.str, Type[builtins.int]]\"\n\n[case testEnumNameWorkCorrectlyOn311]\n# flags: --python-version 3.11\nimport enum\n\nclass E(enum.Enum):\n    X = 1\n    Y = 2\n    @enum.property\n    def foo(self) -> int: ...\n\ne: E\nreveal_type(e.name)\nreveal_type(e.value)\nreveal_type(E.X.name)\nreveal_type(e.foo)\nreveal_type(E.Y.foo)\n[out]\n_testEnumNameWorkCorrectlyOn311.py:11: note: Revealed type is \"builtins.str\"\n_testEnumNameWorkCorrectlyOn311.py:12: note: Revealed type is \"Union[Literal[1]?, Literal[2]?]\"\n_testEnumNameWorkCorrectlyOn311.py:13: note: Revealed type is \"Literal['X']?\"\n_testEnumNameWorkCorrectlyOn311.py:14: note: Revealed type is \"builtins.int\"\n_testEnumNameWorkCorrectlyOn311.py:15: note: Revealed type is \"builtins.int\"\n\n[case testTypeAliasNotSupportedWithNewStyleUnion]\n# flags: --python-version 3.9\nfrom typing_extensions import TypeAlias\nA = type[int] | str\nB = str | type[int]\nC = str | int\nD: TypeAlias = str | int\n[out]\n_testTypeAliasNotSupportedWithNewStyleUnion.py:3: error: `X | Y` syntax for unions requires Python 3.10 or above\n_testTypeAliasNotSupportedWithNewStyleUnion.py:3: error: Unsupported left operand type for | (\"GenericAlias\")\n_testTypeAliasNotSupportedWithNewStyleUnion.py:4: error: `X | Y` syntax for unions requires Python 3.10 or above\n_testTypeAliasNotSupportedWithNewStyleUnion.py:4: error: Unsupported left operand type for | (\"Type[str]\")\n_testTypeAliasNotSupportedWithNewStyleUnion.py:5: error: `X | Y` syntax for unions requires Python 3.10 or above\n_testTypeAliasNotSupportedWithNewStyleUnion.py:5: error: Unsupported left operand type for | (\"Type[str]\")\n_testTypeAliasNotSupportedWithNewStyleUnion.py:6: error: `X | Y` syntax for unions requires Python 3.10 or above\n_testTypeAliasNotSupportedWithNewStyleUnion.py:6: error: Unsupported left operand type for | (\"Type[str]\")\n\n[case testTypedDictUnionGetFull]\nfrom typing import Dict\nfrom typing_extensions import TypedDict\n\nclass TD(TypedDict, total=False):\n    x: int\n    y: int\n\nA = Dict[str, TD]\nx: A\ndef foo(k: str) -> TD:\n    reveal_type(x.get(k, {}))\n    return x.get(k, {})\n[out]\n_testTypedDictUnionGetFull.py:11: note: Revealed type is \"TypedDict('_testTypedDictUnionGetFull.TD', {'x'?: builtins.int, 'y'?: builtins.int})\"\n\n[case testTupleWithDifferentArgsPy310]\n# https://github.com/python/mypy/issues/11098\n# flags: --python-version 3.10\nCorrect1 = str | tuple[float, float, str]\nCorrect2 = tuple[float] | str\nCorrect3 = tuple[float, ...] | str\nCorrect4 = tuple[float, str]\nCorrect5 = tuple[float, ...]\nCorrect6 = list[tuple[int, str]]\nc1: Correct1\nc2: Correct2\nc3: Correct3\nc4: Correct4\nc5: Correct5\nc6: Correct6\nreveal_type(c1)\nreveal_type(c2)\nreveal_type(c3)\nreveal_type(c4)\nreveal_type(c5)\nreveal_type(c6)\n\nRHSAlias1: type = tuple[int, int]\nRHSAlias2: type = tuple[int]\nRHSAlias3: type = tuple[int, ...]\n\nWrongTypeElement = str | tuple[float, 1]  # Error\nWrongEllipsis = tuple[float, float, ...] | str  # Error\n\nreveal_type(tuple[int, str]((1, \"x\")))\n[out]\n_testTupleWithDifferentArgsPy310.py:15: note: Revealed type is \"Union[builtins.str, Tuple[builtins.float, builtins.float, builtins.str]]\"\n_testTupleWithDifferentArgsPy310.py:16: note: Revealed type is \"Union[Tuple[builtins.float], builtins.str]\"\n_testTupleWithDifferentArgsPy310.py:17: note: Revealed type is \"Union[builtins.tuple[builtins.float, ...], builtins.str]\"\n_testTupleWithDifferentArgsPy310.py:18: note: Revealed type is \"Tuple[builtins.float, builtins.str]\"\n_testTupleWithDifferentArgsPy310.py:19: note: Revealed type is \"builtins.tuple[builtins.float, ...]\"\n_testTupleWithDifferentArgsPy310.py:20: note: Revealed type is \"builtins.list[Tuple[builtins.int, builtins.str]]\"\n_testTupleWithDifferentArgsPy310.py:26: error: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?\n_testTupleWithDifferentArgsPy310.py:27: error: Unexpected \"...\"\n_testTupleWithDifferentArgsPy310.py:29: note: Revealed type is \"Tuple[builtins.int, builtins.str]\"\n\n[case testEnumIterMetaInference]\nimport socket\nfrom enum import Enum\nfrom typing import Iterable, Iterator, Type, TypeVar\n\n_E = TypeVar(\"_E\", bound=Enum)\n\ndef enum_iter(cls: Type[_E]) -> Iterable[_E]:\n    reveal_type(iter(cls))\n    reveal_type(next(iter(cls)))\n    return iter(cls)\n\nfor value in enum_iter(socket.SocketKind):\n    reveal_type(value)\n[out]\n_testEnumIterMetaInference.py:8: note: Revealed type is \"typing.Iterator[_E`-1]\"\n_testEnumIterMetaInference.py:9: note: Revealed type is \"_E`-1\"\n_testEnumIterMetaInference.py:13: note: Revealed type is \"socket.SocketKind\"\n\n[case testEnumUnpackedViaMetaclass]\nfrom enum import Enum\n\nclass FooEnum(Enum):\n    A = 1\n    B = 2\n    C = 3\n\na, b, c = FooEnum\nreveal_type(a)\nreveal_type(b)\nreveal_type(c)\n[out]\n_testEnumUnpackedViaMetaclass.py:9: note: Revealed type is \"_testEnumUnpackedViaMetaclass.FooEnum\"\n_testEnumUnpackedViaMetaclass.py:10: note: Revealed type is \"_testEnumUnpackedViaMetaclass.FooEnum\"\n_testEnumUnpackedViaMetaclass.py:11: note: Revealed type is \"_testEnumUnpackedViaMetaclass.FooEnum\"\n\n[case testNativeIntTypes]\n# Spot check various native int operations with full stubs.\nfrom mypy_extensions import i64, i32\n\nx: i64 = 0\ny: int = x\nx = i64(0)\ny = int(x)\ni64()\ni64(\"12\")\ni64(\"ab\", 16)\ni64(1.2)\nfloat(i64(1))\n\ni64(1) + i32(2)  # Error\nreveal_type(x + y)\nreveal_type(y + x)\na = [0]\na[x]\n[out]\n_testNativeIntTypes.py:14: error: Unsupported operand types for + (\"i64\" and \"i32\")\n_testNativeIntTypes.py:15: note: Revealed type is \"mypy_extensions.i64\"\n_testNativeIntTypes.py:16: note: Revealed type is \"mypy_extensions.i64\"\n\n[case testStarUnpackNestedUnderscore]\nfrom typing import Tuple, Dict, List\n\ndef crash() -> None:\n    d: Dict[int, Tuple[str, int, str]] = {}\n    k, (v1, *_) = next(iter(d.items()))\n\ndef test1() -> None:\n    vs: List[str]\n    d: Dict[int, Tuple[str, int, int]] = {}\n    k, (v1, *vs) = next(iter(d.items()))\n    reveal_type(vs)\n\ndef test2() -> None:\n    d: Dict[int, Tuple[str, int, str]] = {}\n    k, (v1, *vs) = next(iter(d.items()))\n    reveal_type(vs)\n[out]\n_testStarUnpackNestedUnderscore.py:10: error: List item 0 has incompatible type \"int\"; expected \"str\"\n_testStarUnpackNestedUnderscore.py:10: error: List item 1 has incompatible type \"int\"; expected \"str\"\n_testStarUnpackNestedUnderscore.py:11: note: Revealed type is \"builtins.list[builtins.str]\"\n_testStarUnpackNestedUnderscore.py:16: note: Revealed type is \"builtins.list[builtins.object]\"\n\n[case testStrictEqualitywithParamSpec]\n# flags: --strict-equality\nfrom typing import Generic\nfrom typing_extensions import Concatenate, ParamSpec\n\nP = ParamSpec(\"P\")\n\nclass Foo(Generic[P]): ...\nclass Bar(Generic[P]): ...\n\ndef bad(foo: Foo[[int]], bar: Bar[[int]]) -> bool:\n    return foo == bar\n\ndef bad1(foo1: Foo[[int]], foo2: Foo[[str]]) -> bool:\n    return foo1 == foo2\n\ndef bad2(foo1: Foo[[int, str]], foo2: Foo[[int, bytes]]) -> bool:\n    return foo1 == foo2\n\ndef bad3(foo1: Foo[[int]], foo2: Foo[[int, int]]) -> bool:\n    return foo1 == foo2\n\ndef good4(foo1: Foo[[int]], foo2: Foo[[int]]) -> bool:\n    return foo1 == foo2\n\ndef good5(foo1: Foo[[int]], foo2: Foo[[bool]]) -> bool:\n    return foo1 == foo2\n\ndef good6(foo1: Foo[[int, int]], foo2: Foo[[bool, bool]]) -> bool:\n    return foo1 == foo2\n\ndef good7(foo1: Foo[[int]], foo2: Foo[P], *args: P.args, **kwargs: P.kwargs) -> bool:\n    return foo1 == foo2\n\ndef good8(foo1: Foo[P], foo2: Foo[[int, str, bytes]], *args: P.args, **kwargs: P.kwargs) -> bool:\n    return foo1 == foo2\n\ndef good9(foo1: Foo[Concatenate[int, P]], foo2: Foo[[int, str, bytes]], *args: P.args, **kwargs: P.kwargs) -> bool:\n    return foo1 == foo2\n\n[out]\n_testStrictEqualitywithParamSpec.py:11: error: Non-overlapping equality check (left operand type: \"Foo[[int]]\", right operand type: \"Bar[[int]]\")\n_testStrictEqualitywithParamSpec.py:14: error: Non-overlapping equality check (left operand type: \"Foo[[int]]\", right operand type: \"Foo[[str]]\")\n_testStrictEqualitywithParamSpec.py:17: error: Non-overlapping equality check (left operand type: \"Foo[[int, str]]\", right operand type: \"Foo[[int, bytes]]\")\n_testStrictEqualitywithParamSpec.py:20: error: Non-overlapping equality check (left operand type: \"Foo[[int]]\", right operand type: \"Foo[[int, int]]\")\n\n[case testInferenceOfDunderDictOnClassObjects]\nclass Foo: ...\nreveal_type(Foo.__dict__)\nreveal_type(Foo().__dict__)\nFoo.__dict__ = {}\nFoo().__dict__ = {}\n\n[out]\n_testInferenceOfDunderDictOnClassObjects.py:2: note: Revealed type is \"types.MappingProxyType[builtins.str, builtins.object]\"\n_testInferenceOfDunderDictOnClassObjects.py:3: note: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\n_testInferenceOfDunderDictOnClassObjects.py:4: error: Property \"__dict__\" defined in \"type\" is read-only\n_testInferenceOfDunderDictOnClassObjects.py:4: error: Incompatible types in assignment (expression has type \"Dict[Never, Never]\", variable has type \"MappingProxyType[str, object]\")\n\n[case testTypeVarTuple]\n# flags: --python-version=3.11\nfrom typing import Any, Callable, Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\n\ndef foo(callback: Callable[[], Any]) -> None:\n    call(callback)\n\ndef call(callback: Callable[[Unpack[Ts]], Any], *args: Unpack[Ts]) -> Any:\n    ...\n\n[case testTypeVarTupleTypingExtensions]\nfrom typing_extensions import Unpack, TypeVarTuple\nfrom typing import Any, Callable\n\nTs = TypeVarTuple(\"Ts\")\n\ndef foo(callback: Callable[[], Any]) -> None:\n    call(callback)\n\ndef call(callback: Callable[[Unpack[Ts]], Any], *args: Unpack[Ts]) -> Any:\n    ...\n\n[case testDataclassReplace]\nfrom dataclasses import dataclass, replace\n\n@dataclass\nclass A:\n    x: int\n\na = A(x=42)\na2 = replace(a, x=42)\nreveal_type(a2)\na2 = replace()\na2 = replace(a, x='spam')\na2 = replace(a, x=42, q=42)\n[out]\n_testDataclassReplace.py:9: note: Revealed type is \"_testDataclassReplace.A\"\n_testDataclassReplace.py:10: error: Too few arguments for \"replace\"\n_testDataclassReplace.py:11: error: Argument \"x\" to \"replace\" of \"A\" has incompatible type \"str\"; expected \"int\"\n_testDataclassReplace.py:12: error: Unexpected keyword argument \"q\" for \"replace\" of \"A\"\n\n[case testGenericInferenceWithTuple]\n# flags: --new-type-inference\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[out]\n\n[case testGenericInferenceWithDataclass]\n# flags: --new-type-inference\nfrom typing import Any, Collection, List\nfrom dataclasses import dataclass, field\n\nclass Foo:\n    pass\n\n@dataclass\nclass A:\n    items: Collection[Foo] = field(default_factory=list)\n[out]\n\n[case testGenericInferenceWithItertools]\n# flags: --new-type-inference\nfrom typing import TypeVar, Tuple\nfrom itertools import groupby\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\ndef fst(kv: Tuple[K, V]) -> K:\n    k, v = kv\n    return k\n\npairs = [(len(s), s) for s in [\"one\", \"two\", \"three\"]]\ngrouped = groupby(pairs, key=fst)\n[out]\n\n[case testDataclassReplaceOptional]\nfrom dataclasses import dataclass, replace\nfrom typing import Optional\n\n@dataclass\nclass A:\n    x: Optional[int]\n\na = A(x=42)\nreveal_type(a)\na2 = replace(a, x=None)  # OK\nreveal_type(a2)\n[out]\n_testDataclassReplaceOptional.py:9: note: Revealed type is \"_testDataclassReplaceOptional.A\"\n_testDataclassReplaceOptional.py:11: note: Revealed type is \"_testDataclassReplaceOptional.A\"\n\n[case testDataclassStrictOptionalAlwaysSet]\nfrom dataclasses import dataclass\nfrom typing import Callable, Optional\n\n@dataclass\nclass Description:\n    name_fn: Callable[[Optional[int]], Optional[str]]\n\ndef f(d: Description) -> None:\n    reveal_type(d.name_fn)\n[out]\n_testDataclassStrictOptionalAlwaysSet.py:9: note: Revealed type is \"def (Union[builtins.int, None]) -> Union[builtins.str, None]\"\n\n[case testPEP695VarianceInference]\n# flags: --python-version=3.12\nfrom typing import Callable, Final\n\nclass Job[_R_co]:\n    def __init__(self, target: Callable[[], _R_co]) -> None:\n        self.target: Final = target\n\ndef func(\n    action: Job[int | None],\n    a1: Job[int | None],\n    a2: Job[int],\n    a3: Job[None],\n) -> None:\n    action = a1\n    action = a2\n    action = a3\n    a2 = action  # Error\n[out]\n_testPEP695VarianceInference.py:17: error: Incompatible types in assignment (expression has type \"Job[None]\", variable has type \"Job[int]\")\n\n[case testPEP695TypeAliasWithDifferentTargetTypes]\n# flags: --python-version=3.12\nfrom typing import Any, Callable, List, Literal, TypedDict, overload, TypeAlias, TypeVar, Never\n\nclass C[T]: pass\n\nclass O[T]:\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, x: int) -> None: ...\n    def __init__(self, x: int = 0) -> None:\n        pass\n\nclass TD(TypedDict):\n    x: int\n\nS = TypeVar(\"S\")\nA = list[S]\nB: TypeAlias = list[S]\n\ntype A1 = type[int]\ntype A2 = type[int] | None\ntype A3 = None | type[int]\ntype A4 = type[Any]\ntype A5 = type[C] | None\ntype A6 = None | type[C]\ntype A7 = type[O] | None\ntype A8 = None | type[O]\n\ntype B1[**P, R] = Callable[P, R] | None\ntype B2[**P, R] = None | Callable[P, R]\ntype B3 = Callable[[str], int]\ntype B4 = Callable[..., int]\n\ntype C1 = A1 | None\ntype C2 = None | A1\n\ntype D1 = Any | None\ntype D2 = None | Any\n\ntype E1 = List[int]\ntype E2 = List[int] | None\ntype E3 = None | List[int]\n\ntype F1 = Literal[1]\ntype F2 = Literal['x'] | None\ntype F3 = None | Literal[True]\n\ntype G1 = tuple[int, Any]\ntype G2 = tuple[int, Any] | None\ntype G3 = None | tuple[int, Any]\n\ntype H1 = TD\ntype H2 = TD | None\ntype H3 = None | TD\n\ntype I1 = C[int]\ntype I2 = C[Any] | None\ntype I3 = None | C[TD]\ntype I4 = O[int] | None\ntype I5 = None | O[int]\n\ntype J1[T] = T | None\ntype J2[T] = None | T\ntype J3[*Ts] = tuple[*Ts]\ntype J4[T] = J1[T] | None\ntype J5[T] = None | J1[T]\ntype J6[*Ts] = J3[*Ts] | None\n\ntype K1 = A[int] | None\ntype K2 = None | A[int]\ntype K3 = B[int] | None\ntype K4 = None | B[int]\n\ntype L1 = Never\ntype L2 = list[Never]\n\n[case testPEP695VarianceInferenceSpecialCaseWithTypeshed]\n# flags: --python-version=3.12\nclass C1[T1, T2](list[T1]):\n    def m(self, a: T2) -> None: ...\n\ndef func1(p: C1[int, object]):\n    x: C1[int, int] = p\n\nclass C2[T1, T2, T3](dict[T2, T3]):\n    def m(self, a: T1) -> None: ...\n\ndef func2(p: C2[object, int, int]):\n    x: C2[int, int, int] = p\n\nclass C3[T1, T2](tuple[T1, ...]):\n    def m(self, a: T2) -> None: ...\n\ndef func3(p: C3[int, object]):\n    x: C3[int, int] = p\n\n\n[case testDynamicClassAttribute]\n# Some things that can break if DynamicClassAttribute isn't handled properly\nfrom types import DynamicClassAttribute\nfrom enum import Enum\n\nclass TestClass:\n    @DynamicClassAttribute\n    def name(self) -> str: ...\n\nclass TestClass2(TestClass, Enum): ...\n\nclass Status(Enum):\n    ABORTED = -1\n\ndef imperfect(status: Status) -> str:\n    return status.name.lower()\n\n[case testUnpackIteratorBuiltins]\n# Regression test for https://github.com/python/mypy/issues/18320\n# Caused by https://github.com/python/typeshed/pull/12851\nx = [1, 2]\nreveal_type([*reversed(x)])\nreveal_type([*map(str, x)])\n[out]\n_testUnpackIteratorBuiltins.py:4: note: Revealed type is \"builtins.list[builtins.int]\"\n_testUnpackIteratorBuiltins.py:5: note: Revealed type is \"builtins.list[builtins.str]\"\n"
  },
  {
    "path": "test-data/unit/ref-info.test",
    "content": "[case testCallGlobalFunction]\ndef f() -> None:\n    g()\n\ndef g() -> None:\n    pass\n[out]\n2:4:__main__.g\n\n[case testCallMethod]\ndef f() -> None:\n    c = C()\n    if int():\n        c.method()\n\nclass C:\n    def method(self) -> None: pass\n[out]\n2:8:__main__.C\n3:7:builtins.int\n4:8:__main__.C.method\n\n[case testCallStaticMethod]\nclass C:\n    def f(self) -> None:\n        C.static()\n        self.static()\n\n    @classmethod\n    def cm(cls) -> None:\n        cls.static()\n\n    @staticmethod\n    def static() -> None: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n3:8:__main__.C\n3:8:__main__.C.static\n4:8:__main__.C.static\n8:8:__main__.C.static\n\n[case testCallClassMethod]\nclass C:\n    def f(self) -> None:\n        C.cm()\n        self.cm()\n\n    @classmethod\n    def cm(cls) -> None:\n        cls.cm()\n[builtins fixtures/classmethod.pyi]\n[out]\n3:8:__main__.C\n3:8:__main__.C.cm\n4:8:__main__.C.cm\n8:8:__main__.C.cm\n\n[case testTypeVarWithValueRestriction]\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", \"C\", \"D\")\n\ndef f(o: T) -> None:\n    f(o)\n    o.m()\n    o.x\n\nclass C:\n    x: int\n    def m(self) -> None: pass\n\nclass D:\n    x: str\n    def m(self) -> None: pass\n[out]\n3:4:typing.TypeVar\n3:0:__main__.T\n6:4:__main__.f\n7:4:__main__.C.m\n8:4:__main__.C.x\n6:4:__main__.f\n7:4:__main__.D.m\n8:4:__main__.D.x\n"
  },
  {
    "path": "test-data/unit/reports.test",
    "content": "-- Tests for reports\n--\n-- This file follows syntax of cmdline.test.\n\n[case testConfigErrorUnknownReport]\n# cmd: mypy -c pass\n[file mypy.ini]\n\\[mypy]\nbad_report = .\n[out]\nmypy.ini: [mypy]: Unrecognized report type: bad_report\n== Return code: 0\n\n[case testCoberturaParser]\n# cmd: mypy --cobertura-xml-report build pkg\n[file pkg/__init__.py]\n[file pkg/a.py]\nfrom typing import Dict\n\ndef foo() -> Dict:\n  z = {'hello': 'world'}\n  return z\n[file pkg/subpkg/__init__.py]\n[file pkg/subpkg/a.py]\ndef bar() -> str:\n  return 'world'\ndef untyped_function():\n  return 42\n[outfile build/cobertura.xml]\n<coverage timestamp=\"$TIMESTAMP\" version=\"$VERSION\" line-rate=\"0.7500\" branch-rate=\"0\" lines-covered=\"6\" lines-valid=\"8\">\n  <sources>\n    <source>$PWD</source>\n  </sources>\n  <packages>\n    <package complexity=\"1.0\" name=\"pkg\" branch-rate=\"0\" line-rate=\"1.0000\">\n      <classes>\n        <class complexity=\"1.0\" filename=\"pkg/__init__.py\" name=\"__init__.py\" branch-rate=\"0\" line-rate=\"1.0\">\n          <methods/>\n          <lines/>\n        </class>\n        <class complexity=\"1.0\" filename=\"pkg/a.py\" name=\"a.py\" branch-rate=\"0\" line-rate=\"1.0000\">\n          <methods/>\n          <lines>\n            <line branch=\"false\" hits=\"1\" number=\"1\" precision=\"precise\"/>\n            <line branch=\"true\" hits=\"1\" number=\"3\" precision=\"imprecise\" condition-coverage=\"50% (1/2)\"/>\n            <line branch=\"false\" hits=\"1\" number=\"4\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"5\" precision=\"precise\"/>\n          </lines>\n        </class>\n      </classes>\n    </package>\n    <package complexity=\"1.0\" name=\"pkg.subpkg\" branch-rate=\"0\" line-rate=\"0.5000\">\n      <classes>\n        <class complexity=\"1.0\" filename=\"pkg/subpkg/__init__.py\" name=\"__init__.py\" branch-rate=\"0\" line-rate=\"1.0\">\n          <methods/>\n          <lines/>\n        </class>\n        <class complexity=\"1.0\" filename=\"pkg/subpkg/a.py\" name=\"a.py\" branch-rate=\"0\" line-rate=\"0.5000\">\n          <methods/>\n          <lines>\n            <line branch=\"false\" hits=\"1\" number=\"1\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"2\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"0\" number=\"3\" precision=\"any\"/>\n            <line branch=\"false\" hits=\"0\" number=\"4\" precision=\"any\"/>\n          </lines>\n        </class>\n      </classes>\n    </package>\n  </packages>\n</coverage>\n\n[case testCoberturaStarUnpacking]\n# cmd: mypy --cobertura-xml-report build a.py\n[file a.py]\nfrom typing import TypedDict\n\nclass MyDict(TypedDict):\n    a: int\n\ndef foo(a: int) -> MyDict:\n    return {\"a\": a}\nmd: MyDict = MyDict(**foo(42))\n[outfile build/cobertura.xml]\n<coverage timestamp=\"$TIMESTAMP\" version=\"$VERSION\" line-rate=\"1.0000\" branch-rate=\"0\" lines-covered=\"6\" lines-valid=\"6\">\n  <sources>\n    <source>$PWD</source>\n  </sources>\n  <packages>\n    <package complexity=\"1.0\" name=\"a\" branch-rate=\"0\" line-rate=\"1.0000\">\n      <classes>\n        <class complexity=\"1.0\" filename=\"a.py\" name=\"a.py\" branch-rate=\"0\" line-rate=\"1.0000\">\n          <methods/>\n          <lines>\n            <line branch=\"false\" hits=\"1\" number=\"1\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"3\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"4\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"6\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"7\" precision=\"precise\"/>\n            <line branch=\"false\" hits=\"1\" number=\"8\" precision=\"precise\"/>\n          </lines>\n        </class>\n      </classes>\n    </package>\n  </packages>\n</coverage>\n\n[case testAnyExprReportDivisionByZero]\n# cmd: mypy --any-exprs-report=out -c 'pass'\n\n[case testClassDefIsNotTreatedAsEmpty]\n# cmd: mypy --html-report report n.py\n[file n.py]\nclass A(object):\n\tpass  # line indented with tab; hex 1f here: (\u001f)\n\n[file report/mypy-html.css]\n[file report/index.html]\n[outfile report/html/n.py.html]\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../mypy-html.css\">\n</head>\n<body>\n<h2>n</h2>\n<table>\n<caption>n.py</caption>\n<tbody><tr>\n<td class=\"table-lines\"><pre><span id=\"L1\" class=\"lineno\"><a class=\"lineno\" href=\"#L1\">1</a></span>\n<span id=\"L2\" class=\"lineno\"><a class=\"lineno\" href=\"#L2\">2</a></span>\n</pre></td>\n<td class=\"table-code\"><pre><span class=\"line-precise\" title=\"No Anys on this line!\">class A(object):</span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">\tpass  # line indented with tab; hex 1f here: (?)</span>\n</pre></td>\n</tr></tbody>\n</table>\n</body>\n</html>\n\n[case testNoCrashRecursiveAliasInReport]\n# cmd: mypy --any-exprs-report report n.py\n\n[file n.py]\nfrom typing import Union, List, Any, TypeVar\n\nNested = List[Union[Any, Nested]]\nT = TypeVar(\"T\")\nNestedGen = List[Union[T, NestedGen[T]]]\n\nx: Nested\ny: NestedGen[int]\nz: NestedGen[Any]\n\n[file report/any-exprs.txt]\n[outfile report/types-of-anys.txt]\n Name   Unannotated   Explicit   Unimported   Omitted Generics   Error   Special Form   Implementation Artifact\n-----------------------------------------------------------------------------------------------------------------\n    n             0          2            0                  8       0              0                         0\n-----------------------------------------------------------------------------------------------------------------\nTotal             0          2            0                  8       0              0                         0\n\n[case testTypeVarTreatedAsEmptyLine]\n# cmd: mypy --html-report report n.py\n\n[file n.py]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\n[file report/mypy-html.css]\n[file report/index.html]\n[outfile report/html/n.py.html]\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../mypy-html.css\">\n</head>\n<body>\n<h2>n</h2>\n<table>\n<caption>n.py</caption>\n<tbody><tr>\n<td class=\"table-lines\"><pre><span id=\"L1\" class=\"lineno\"><a class=\"lineno\" href=\"#L1\">1</a></span>\n<span id=\"L2\" class=\"lineno\"><a class=\"lineno\" href=\"#L2\">2</a></span>\n<span id=\"L3\" class=\"lineno\"><a class=\"lineno\" href=\"#L3\">3</a></span>\n</pre></td>\n<td class=\"table-code\"><pre><span class=\"line-precise\" title=\"No Anys on this line!\">from typing import TypeVar</span>\n<span class=\"line-empty\" title=\"No Anys on this line!\"></span>\n<span class=\"line-empty\" title=\"No Anys on this line!\">T = TypeVar('T')</span>\n</pre></td>\n</tr></tbody>\n</table>\n</body>\n</html>\n\n[case testUnreachableCodeMarkedAsAny]\n# cmd: mypy --html-report report n.py\n\n[file any.py]\nfrom typing import Any\ndef any_f(x: Any) -> None:\n    pass\n\n[file n.py]\nfrom any import any_f\ndef bar(x):\n    # type: (str) -> None\n    any_f(x)\n    assert False\n    any_f(x)\n\n[file report/mypy-html.css]\n[file report/index.html]\n[outfile report/html/n.py.html]\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../mypy-html.css\">\n</head>\n<body>\n<h2>n</h2>\n<table>\n<caption>n.py</caption>\n<tbody><tr>\n<td class=\"table-lines\"><pre><span id=\"L1\" class=\"lineno\"><a class=\"lineno\" href=\"#L1\">1</a></span>\n<span id=\"L2\" class=\"lineno\"><a class=\"lineno\" href=\"#L2\">2</a></span>\n<span id=\"L3\" class=\"lineno\"><a class=\"lineno\" href=\"#L3\">3</a></span>\n<span id=\"L4\" class=\"lineno\"><a class=\"lineno\" href=\"#L4\">4</a></span>\n<span id=\"L5\" class=\"lineno\"><a class=\"lineno\" href=\"#L5\">5</a></span>\n<span id=\"L6\" class=\"lineno\"><a class=\"lineno\" href=\"#L6\">6</a></span>\n</pre></td>\n<td class=\"table-code\"><pre><span class=\"line-precise\" title=\"No Anys on this line!\">from any import any_f</span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">def bar(x):</span>\n<span class=\"line-empty\" title=\"No Anys on this line!\">    # type: (str) -&gt; None</span>\n<span class=\"line-any\" title=\"Any Types on this line:\nExplicit (x1)\">    any_f(x)</span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">    assert False</span>\n<span class=\"line-unanalyzed\" title=\"No Anys on this line!\">    any_f(x)</span>\n</pre></td>\n</tr></tbody>\n</table>\n</body>\n</html>\n\n[case testHtmlReportMemberExprNoUnanalyzed]\n# cmd: mypy --html-report report n.py\n\n[file n.py]\nimport sys\n\nold_stdout = sys.stdout\n\n[file report/mypy-html.css]\n[file report/index.html]\n[outfile report/html/n.py.html]\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../mypy-html.css\">\n</head>\n<body>\n<h2>n</h2>\n<table>\n<caption>n.py</caption>\n<tbody><tr>\n<td class=\"table-lines\"><pre><span id=\"L1\" class=\"lineno\"><a class=\"lineno\" href=\"#L1\">1</a></span>\n<span id=\"L2\" class=\"lineno\"><a class=\"lineno\" href=\"#L2\">2</a></span>\n<span id=\"L3\" class=\"lineno\"><a class=\"lineno\" href=\"#L3\">3</a></span>\n</pre></td>\n<td class=\"table-code\"><pre><span class=\"line-precise\" title=\"No Anys on this line!\">import sys</span>\n<span class=\"line-empty\" title=\"No Anys on this line!\"></span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">old_stdout = sys.stdout</span>\n</pre></td>\n</tr></tbody>\n</table>\n</body>\n</html>\n\n[case testAnyExprReportIncludesDeadCode]\n# cmd: mypy --any-exprs-report report i.py j.py\n\n[file i.py]\ndef bar(x):\n    # type: (str) -> None\n    print(x)\n    assert False\n    print(x)  # dead code!\n\n[file j.py]\ndef bar(x):\n    # type: (str) -> None\n    print(x)\n    assert False\n\n[file report/types-of-anys.txt]\n[outfile report/any-exprs.txt]\n Name   Anys   Exprs   Coverage\n---------------------------------\n    i      1       6     83.33%\n    j      0       5    100.00%\n---------------------------------\nTotal      1      11     90.91%\n\n[case testAnyExprReportHigherKindedTypesAreNotAny]\n# cmd: mypy --any-exprs-report report i.py\n\n[file i.py]\nfrom enum import Enum\nfrom mypy_extensions import TypedDict\nfrom typing import NewType, NamedTuple, TypeVar\n\nfrom typing import TypeVar\n\nT = TypeVar('T')  # no error\n\ndef f(t: T) -> T:\n    return t\n\nPoint = NamedTuple('Point', [('x', int), ('y', int)])  # no error\n\ndef origin() -> Point:\n    return Point(x=0, y=0)\n\nNT = NewType('NT', int)  # no error\n\ndef nt() -> NT:\n    return NT(1)\n\nE = Enum('E', '1, 2, 3')  # no error\n\ndef k(s: E) -> None: pass\n\nMovie = TypedDict('Movie', {'name': str, 'year': int})\n\ndef g(m: Movie) -> Movie:\n    return m\n\n[file report/types-of-anys.txt]\n[outfile report/any-exprs.txt]\n Name   Anys   Exprs   Coverage\n---------------------------------\n    i      0      14    100.00%\n---------------------------------\nTotal      0      14    100.00%\n\n\n[case testAnyExpressionsReportTypesOfAny]\n# cmd: mypy --any-exprs-report report n.py\n\n[file n.py]\nfrom typing import Any, List\nfrom nonexistent import C  # type: ignore\n\ndef any_f(x: Any) -> None:  # Explicit\n    pass\n\ndef a(x) -> None:  # Unannotated\n    any_f(x)\n\nx: Any = 2  # Explicit\ny: C = None  # Unimported\n\ndef b() -> List:  # Omitted Generics\n    return [1, 2, 3]\n\ng = 1\nz = g.does_not_exist()  # type: ignore  # Error\n\n\n[file report/any-exprs.txt]\n[outfile report/types-of-anys.txt]\n Name   Unannotated   Explicit   Unimported   Omitted Generics   Error   Special Form   Implementation Artifact\n-----------------------------------------------------------------------------------------------------------------\n    n             2          3            1                  1       3              0                         0\n-----------------------------------------------------------------------------------------------------------------\nTotal             2          3            1                  1       3              0                         0\n\n[case testAnyExpressionsReportUnqualifiedError]\n# cmd: mypy --any-exprs-report report n.py\n\n[file n.py]\nz = does_not_exist()  # type: ignore  # Error\n\n[file report/any-exprs.txt]\n[outfile report/types-of-anys.txt]\n Name   Unannotated   Explicit   Unimported   Omitted Generics   Error   Special Form   Implementation Artifact\n-----------------------------------------------------------------------------------------------------------------\n    n             0          0            0                  0       3              0                         0\n-----------------------------------------------------------------------------------------------------------------\nTotal             0          0            0                  0       3              0                         0\n\n[case testAnyExpressionsReportUntypedDef]\n# cmd: mypy --any-exprs-report report n.py\n\n[file n.py]\ndef foo():\n    x = 0\n    f = 0\n\n[file report/any-exprs.txt]\n[outfile report/types-of-anys.txt]\n Name   Unannotated   Explicit   Unimported   Omitted Generics   Error   Special Form   Implementation Artifact\n-----------------------------------------------------------------------------------------------------------------\n    n             0          0            0                  0       0              0                         0\n-----------------------------------------------------------------------------------------------------------------\nTotal             0          0            0                  0       0              0                         0\n[case testTrickyCoverage]\n# cmd: mypy --linecoverage-report=report n.py\n[file n.py]\ndef blah(x): return x\n\n@blah\n\ndef f(x: int) -> None: pass\n\nclass Foo:\n    @blah\n    #hi\n    def f(self, x: int) -> None:\n        pass\n\n@blah\nclass Z(object):\n    pass\n\n[case testCoverageIgnoresCache]\n-- Performs two runs to verify that cached information does not prevent\n-- modules from being included in reports.\n# cmd: mypy --linecount-report report a.py\n[file a.py]\nempty = False\n[out]\n[out2]\n[outfile report/linecount.txt]\n      1       1      0      0 total\n      1       1      0      0 a\n\n[case testAnyExprReportIgnoresSpecialForms]\n# cmd: mypy --any-exprs-report report i.py j.py k.py l.py\n\n[file i.py]\nasync def some_function() -> None:\n    pass\n\n[file j.py]\nfrom typing import Any\n\nasync def some_function() -> Any:\n    pass\n\n[file k.py]\nfrom typing import NamedTuple\n\ndef a() -> None:\n    _FuzzyMatch(0, 0)\n\n_FuzzyMatch = NamedTuple('_FuzzyMatch', [\n    ('match_length', int),\n    ('start_pos', int),\n])\n\ndef b() -> None:\n    _FuzzyMatch(0, 0)\n\n[file l.py]\nasync def some_function(x) -> None:\n    pass\n\n[file report/any-exprs.txt]\n[outfile report/types-of-anys.txt]\n Name   Unannotated   Explicit   Unimported   Omitted Generics   Error   Special Form   Implementation Artifact\n-----------------------------------------------------------------------------------------------------------------\n    i             0          0            0                  0       0              0                         0\n    j             0          1            0                  0       0              0                         0\n    k             0          0            0                  0       0              0                         0\n    l             1          0            0                  0       0              0                         0\n-----------------------------------------------------------------------------------------------------------------\nTotal             1          1            0                  0       0              0                         0\n\n[case testSpecialAnyHtmlReport]\n# cmd: mypy --html-report report n.py\n[file n.py]\nfrom typing import Callable\n\nSourceToDisplay = Callable[[int], int]\nDisplayToSource = Callable[[int], int]\n\n[file report/mypy-html.css]\n[file report/index.html]\n[outfile report/html/n.py.html]\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../mypy-html.css\">\n</head>\n<body>\n<h2>n</h2>\n<table>\n<caption>n.py</caption>\n<tbody><tr>\n<td class=\"table-lines\"><pre><span id=\"L1\" class=\"lineno\"><a class=\"lineno\" href=\"#L1\">1</a></span>\n<span id=\"L2\" class=\"lineno\"><a class=\"lineno\" href=\"#L2\">2</a></span>\n<span id=\"L3\" class=\"lineno\"><a class=\"lineno\" href=\"#L3\">3</a></span>\n<span id=\"L4\" class=\"lineno\"><a class=\"lineno\" href=\"#L4\">4</a></span>\n</pre></td>\n<td class=\"table-code\"><pre><span class=\"line-precise\" title=\"No Anys on this line!\">from typing import Callable</span>\n<span class=\"line-empty\" title=\"No Anys on this line!\"></span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">SourceToDisplay = Callable[[int], int]</span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">DisplayToSource = Callable[[int], int]</span>\n</pre></td>\n</tr></tbody>\n</table>\n</body>\n</html>\n\n[case testHtmlReportOnNamespacePackagesWithExplicitBases]\n# cmd: mypy --html-report report -p folder\n[file folder/subfolder/something.py]\nclass Something:\n    pass\n[file folder/main.py]\nfrom .subfolder.something import Something\nprint(Something())\n[file folder/__init__.py]\n[file mypy.ini]\n\\[mypy]\nexplicit_package_bases = True\nnamespace_packages = True\n\n[file report/mypy-html.css]\n[file report/index.html]\n[outfile report/html/folder/subfolder/something.py.html]\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../../../mypy-html.css\">\n</head>\n<body>\n<h2>folder.subfolder.something</h2>\n<table>\n<caption>folder/subfolder/something.py</caption>\n<tbody><tr>\n<td class=\"table-lines\"><pre><span id=\"L1\" class=\"lineno\"><a class=\"lineno\" href=\"#L1\">1</a></span>\n<span id=\"L2\" class=\"lineno\"><a class=\"lineno\" href=\"#L2\">2</a></span>\n</pre></td>\n<td class=\"table-code\"><pre><span class=\"line-precise\" title=\"No Anys on this line!\">class Something:</span>\n<span class=\"line-precise\" title=\"No Anys on this line!\">    pass</span>\n</pre></td>\n</tr></tbody>\n</table>\n</body>\n</html>\n"
  },
  {
    "path": "test-data/unit/semanal-abstractclasses.test",
    "content": "[case testAbstractMethods]\nfrom abc import abstractmethod, ABCMeta\nimport typing\n\nclass A(metaclass=ABCMeta):\n  @abstractmethod\n  def g(self) -> 'A': pass\n  @abstractmethod\n  def f(self) -> 'A': return self\n[out]\nMypyFile:1(\n  ImportFrom:1(abc, [abstractmethod, ABCMeta])\n  Import:2(typing)\n  ClassDef:4(\n    A\n    Metaclass(NameExpr(ABCMeta [abc.ABCMeta]))\n    Decorator:5(\n      Var(g)\n      FuncDef:6(\n        g\n        Args(\n          Var(self))\n        def (self: __main__.A) -> __main__.A\n        Abstract\n        Block:6(\n          PassStmt:6())))\n    Decorator:7(\n      Var(f)\n      FuncDef:8(\n        f\n        Args(\n          Var(self))\n        def (self: __main__.A) -> __main__.A\n        Abstract\n        Block:8(\n          ReturnStmt:8(\n            NameExpr(self [l])))))))\n\n[case testClassInheritingTwoAbstractClasses]\nfrom abc import abstractmethod, ABCMeta\nimport typing\n\nclass A(metaclass=ABCMeta): pass\nclass B(metaclass=ABCMeta): pass\nclass C(A, B): pass\n[out]\nMypyFile:1(\n  ImportFrom:1(abc, [abstractmethod, ABCMeta])\n  Import:2(typing)\n  ClassDef:4(\n    A\n    Metaclass(NameExpr(ABCMeta [abc.ABCMeta]))\n    PassStmt:4())\n  ClassDef:5(\n    B\n    Metaclass(NameExpr(ABCMeta [abc.ABCMeta]))\n    PassStmt:5())\n  ClassDef:6(\n    C\n    BaseType(\n      __main__.A\n      __main__.B)\n    PassStmt:6()))\n\n[case testAbstractGenericClass]\nfrom abc import abstractmethod\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass A(Generic[T]):\n  @abstractmethod\n  def f(self) -> 'A[T]': pass\n[out]\nMypyFile:1(\n  ImportFrom:1(abc, [abstractmethod])\n  ImportFrom:2(typing, [Generic, TypeVar])\n  AssignmentStmt:3(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:3())\n  ClassDef:4(\n    A\n    TypeVars(\n      T`1)\n    Decorator:5(\n      Var(f)\n      FuncDef:6(\n        f\n        Args(\n          Var(self))\n        def (self: __main__.A[T`1]) -> __main__.A[T`1]\n        Abstract\n        Block:6(\n          PassStmt:6())))))\n\n[case testFullyQualifiedAbstractMethodDecl]\nimport abc\nfrom abc import ABCMeta\nimport typing\n\nclass A(metaclass=ABCMeta):\n  @abc.abstractmethod\n  def g(self) -> 'A': pass\n[out]\nMypyFile:1(\n  Import:1(abc)\n  ImportFrom:2(abc, [ABCMeta])\n  Import:3(typing)\n  ClassDef:5(\n    A\n    Metaclass(NameExpr(ABCMeta [abc.ABCMeta]))\n    Decorator:6(\n      Var(g)\n      FuncDef:7(\n        g\n        Args(\n          Var(self))\n        def (self: __main__.A) -> __main__.A\n        Abstract\n        Block:7(\n          PassStmt:7())))))\n"
  },
  {
    "path": "test-data/unit/semanal-basic.test",
    "content": "[case testEmptyFile]\n[out]\nMypyFile:1()\n\n[case testGlobalVariable]\nx = 1\nx\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  ExpressionStmt:2(\n    NameExpr(x [__main__.x])))\n\n[case testMultipleGlobals]\nx = y = 2\nz = 3\n(x, y, z)\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(2))\n  AssignmentStmt:2(\n    NameExpr(z [__main__.z])\n    IntExpr(3)\n    builtins.int)\n  ExpressionStmt:3(\n    TupleExpr:3(\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y])\n      NameExpr(z [__main__.z]))))\n\n[case testEmptyFunction]\ndef f(): pass\nf()\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:1(\n      PassStmt:1()))\n  ExpressionStmt:2(\n    CallExpr:2(\n      NameExpr(f [__main__.f])\n      Args())))\n\n[case testAccessingGlobalNameBeforeDefinition]\n# flags: --disable-error-code used-before-def\nx\nf()\nx = 1\ndef f(): pass\n[out]\nMypyFile:1(\n  ExpressionStmt:2(\n    NameExpr(x [__main__.x]))\n  ExpressionStmt:3(\n    CallExpr:3(\n      NameExpr(f [__main__.f])\n      Args()))\n  AssignmentStmt:4(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  FuncDef:5(\n    f\n    Block:5(\n      PassStmt:5())))\n\n[case testFunctionArgs]\ndef f(x, y):\n  (x, y)\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x)\n      Var(y))\n    Block:2(\n      ExpressionStmt:2(\n        TupleExpr:2(\n          NameExpr(x [l])\n          NameExpr(y [l]))))))\n\n[case testLocalVar]\ndef f():\n  x = 1\n  x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(x* [l])\n        IntExpr(1))\n      ExpressionStmt:3(\n        NameExpr(x [l])))))\n\n[case testAccessGlobalInFn]\ndef f():\n  x\n  g()\nx = 1\ndef g(): pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ExpressionStmt:2(\n        NameExpr(x [__main__.x]))\n      ExpressionStmt:3(\n        CallExpr:3(\n          NameExpr(g [__main__.g])\n          Args()))))\n  AssignmentStmt:4(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  FuncDef:5(\n    g\n    Block:5(\n      PassStmt:5())))\n\n[case testAssignmentAfterInit]\nx = 1\nx = 2\ndef f(y):\n  y = 1\n  z = 1\n  z = 2\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    IntExpr(2))\n  FuncDef:3(\n    f\n    Args(\n      Var(y))\n    Block:4(\n      AssignmentStmt:4(\n        NameExpr(y [l])\n        IntExpr(1))\n      AssignmentStmt:5(\n        NameExpr(z* [l])\n        IntExpr(1))\n      AssignmentStmt:6(\n        NameExpr(z [l])\n        IntExpr(2)))))\n\n[case testLocalAndGlobalAliasing]\nx = 1\ndef f():\n  x = 2\n  x\nx\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  FuncDef:2(\n    f\n    Block:3(\n      AssignmentStmt:3(\n        NameExpr(x* [l])\n        IntExpr(2))\n      ExpressionStmt:4(\n        NameExpr(x [l]))))\n  ExpressionStmt:5(\n    NameExpr(x [__main__.x])))\n\n[case testArgumentInitializers]\ndef f(x = f, y = object):\n  x, y\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      default(\n        Var(x)\n        NameExpr(f [__main__.f]))\n      default(\n        Var(y)\n        NameExpr(object [builtins.object])))\n    Block:2(\n      ExpressionStmt:2(\n        TupleExpr:2(\n          NameExpr(x [l])\n          NameExpr(y [l]))))))\n\n[case testVarArgs]\ndef f(x, *y):\n  x, y\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    VarArg(\n      Var(y))\n    Block:2(\n      ExpressionStmt:2(\n        TupleExpr:2(\n          NameExpr(x [l])\n          NameExpr(y [l]))))))\n\n[case testGlobalDecl]\nx = None\ndef f():\n    global x\n    x = None\n    x\nclass A: pass\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x* [__main__.x])\n    NameExpr(None [builtins.None]))\n  FuncDef:2(\n    f\n    Block:3(\n      GlobalDecl:3(\n        x)\n      AssignmentStmt:4(\n        NameExpr(x [__main__.x])\n        NameExpr(None [builtins.None]))\n      ExpressionStmt:5(\n        NameExpr(x [__main__.x]))))\n  ClassDef:6(\n    A\n    PassStmt:6()))\n\n[case testMultipleNamesInGlobalDecl]\nx, y = None, None\ndef f():\n    global x, y\n    x = y\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    TupleExpr:1(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    TupleExpr:1(\n      NameExpr(None [builtins.None])\n      NameExpr(None [builtins.None])))\n  FuncDef:2(\n    f\n    Block:3(\n      GlobalDecl:3(\n        x\n        y)\n      AssignmentStmt:4(\n        NameExpr(x [__main__.x])\n        NameExpr(y [__main__.y])))))\n\n[case testGlobalDeclScope]\nx = None\ndef f():\n    global x\ndef g():\n    x = None\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x* [__main__.x])\n    NameExpr(None [builtins.None]))\n  FuncDef:2(\n    f\n    Block:3(\n      GlobalDecl:3(\n        x)))\n  FuncDef:4(\n    g\n    Block:5(\n      AssignmentStmt:5(\n        NameExpr(x* [l])\n        NameExpr(None [builtins.None])))))\n\n[case testGlobalDeclScope2]\nx = None\ndef f():\n    global x\ndef g():\n    x = None\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x* [__main__.x])\n    NameExpr(None [builtins.None]))\n  FuncDef:2(\n    f\n    Block:3(\n      GlobalDecl:3(\n        x)))\n  FuncDef:4(\n    g\n    Block:5(\n      AssignmentStmt:5(\n        NameExpr(x* [l])\n        NameExpr(None [builtins.None])))))\n\n[case testGlobalWithinMethod]\nx = None\nclass A:\n  def f(self):\n    global x\n    x = self\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x* [__main__.x])\n    NameExpr(None [builtins.None]))\n  ClassDef:2(\n    A\n    FuncDef:3(\n      f\n      Args(\n        Var(self))\n      Block:4(\n        GlobalDecl:4(\n          x)\n        AssignmentStmt:5(\n          NameExpr(x [__main__.x])\n          NameExpr(self [l]))))))\n\n[case testGlobalDefinedInBlock]\n# flags: --allow-redefinition\nif object:\n    x = object()\n    x = x\nx\n[out]\nMypyFile:1(\n  IfStmt:2(\n    If(\n      NameExpr(object [builtins.object]))\n    Then(\n      AssignmentStmt:3(\n        NameExpr(x'* [__main__.x'])\n        CallExpr:3(\n          NameExpr(object [builtins.object])\n          Args()))\n      AssignmentStmt:4(\n        NameExpr(x* [__main__.x])\n        NameExpr(x' [__main__.x']))))\n  ExpressionStmt:5(\n    NameExpr(x [__main__.x])))\n\n[case testNonlocalDecl]\ndef g():\n    x = None\n    def f():\n        nonlocal x\n        x = None\n        x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    g\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(x* [l])\n        NameExpr(None [builtins.None]))\n      FuncDef:3(\n        f\n        Block:4(\n          NonlocalDecl:4(\n            x)\n          AssignmentStmt:5(\n            NameExpr(x [l])\n            NameExpr(None [builtins.None]))\n          ExpressionStmt:6(\n            NameExpr(x [l])))))))\n\n[case testNonlocalClass]\ndef f() -> None:\n    a = 0\n    class C:\n        nonlocal a\n        a = 1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def ()\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(a* [l])\n        IntExpr(0))\n      ClassDef:3(\n        C\n        NonlocalDecl:4(\n          a)\n        AssignmentStmt:5(\n          NameExpr(a* [m])\n          IntExpr(1))))))\n\n[case testMultipleNamesInNonlocalDecl]\ndef g():\n    x, y = None, None\n    def f(z):\n        nonlocal x, y\n        x = y\n[out]\nMypyFile:1(\n  FuncDef:1(\n    g\n    Block:2(\n      AssignmentStmt:2(\n        TupleExpr:2(\n          NameExpr(x* [l])\n          NameExpr(y* [l]))\n        TupleExpr:2(\n          NameExpr(None [builtins.None])\n          NameExpr(None [builtins.None])))\n      FuncDef:3(\n        f\n        Args(\n          Var(z))\n        Block:4(\n          NonlocalDecl:4(\n            x\n            y)\n          AssignmentStmt:5(\n            NameExpr(x [l])\n            NameExpr(y [l])))))))\n\n[case testNestedFunctions]\ndef f(x):\n    def g(y):\n        z = y + x\n    return g\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    Block:2(\n      FuncDef:2(\n        g\n        Args(\n          Var(y))\n        Block:3(\n          AssignmentStmt:3(\n            NameExpr(z* [l])\n            OpExpr:3(\n              +\n              NameExpr(y [l])\n              NameExpr(x [l])))))\n      ReturnStmt:4(\n        NameExpr(g [l])))))\n\n[case testNestedFunctionWithOverlappingName]\ndef f(x):\n    def g():\n        x = 1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    Block:2(\n      FuncDef:2(\n        g\n        Block:3(\n          AssignmentStmt:3(\n            NameExpr(x* [l])\n            IntExpr(1)))))))\n\n[case testFinalValuesOnVar]\nfrom typing import Final, Any\n\ndef func() -> Any: ...\nx: Final = 1\ny: Final = 1.0\ns: Final = \"hi\"\nt: Final = True\nn: Final = func()\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Final, Any])\n  FuncDef:3(\n    func\n    def () -> Any\n    Block:3(\n      ExpressionStmt:3(\n        Ellipsis)))\n  AssignmentStmt:4(\n    NameExpr(x [__main__.x] = 1)\n    IntExpr(1)\n    Literal[1]?)\n  AssignmentStmt:5(\n    NameExpr(y [__main__.y] = 1.0)\n    FloatExpr(1.0)\n    Literal[1.0]?)\n  AssignmentStmt:6(\n    NameExpr(s [__main__.s] = hi)\n    StrExpr(hi)\n    Literal['hi']?)\n  AssignmentStmt:7(\n    NameExpr(t [__main__.t] = True)\n    NameExpr(True [builtins.True])\n    Literal[True]?)\n  AssignmentStmt:8(\n    NameExpr(n* [__main__.n] = None)\n    CallExpr:8(\n      NameExpr(func [__main__.func])\n      Args())))\n"
  },
  {
    "path": "test-data/unit/semanal-classes.test",
    "content": "-- Test cases related to classes for the semantic analyzer.\n\n[case testSimpleClass]\nclass A: pass\nx = A\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    PassStmt:1())\n  AssignmentStmt:2(\n    NameExpr(x* [__main__.x])\n    NameExpr(A [__main__.A])))\n\n[case testMethods]\nclass A:\n  def __init__(self, x):\n    y = x\n  def f(self):\n    y = self\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      __init__\n      Args(\n        Var(self)\n        Var(x))\n      Block:3(\n        AssignmentStmt:3(\n          NameExpr(y* [l])\n          NameExpr(x [l]))))\n    FuncDef:4(\n      f\n      Args(\n        Var(self))\n      Block:5(\n        AssignmentStmt:5(\n          NameExpr(y* [l])\n          NameExpr(self [l]))))))\n\n[case testMemberDefinitionInInit]\nclass A:\n  def __init__(self):\n    self.x = 1\n    self.y = 2\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      __init__\n      Args(\n        Var(self))\n      Block:3(\n        AssignmentStmt:3(\n          MemberExpr:3(\n            NameExpr(self [l])\n            x*)\n          IntExpr(1))\n        AssignmentStmt:4(\n          MemberExpr:4(\n            NameExpr(self [l])\n            y*)\n          IntExpr(2))))))\n\n[case testMemberAssignmentViaSelfOutsideInit]\nclass A:\n  def f(self):\n    self.x = 1\ndef __init__(self):\n  self.y = 1\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      f\n      Args(\n        Var(self))\n      Block:3(\n        AssignmentStmt:3(\n          MemberExpr:3(\n            NameExpr(self [l])\n            x*)\n          IntExpr(1)))))\n  FuncDef:4(\n    __init__\n    Args(\n      Var(self))\n    Block:5(\n      AssignmentStmt:5(\n        MemberExpr:5(\n          NameExpr(self [l])\n          y)\n        IntExpr(1)))))\n\n[case testMemberAssignmentNotViaSelf]\nclass A:\n  def __init__(x, self):\n    self.y = 1 # not really self\nclass B:\n  def __init__(x):\n    self = x\n    self.z = 1\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      __init__\n      Args(\n        Var(x)\n        Var(self))\n      Block:3(\n        AssignmentStmt:3(\n          MemberExpr:3(\n            NameExpr(self [l])\n            y)\n          IntExpr(1)))))\n  ClassDef:4(\n    B\n    FuncDef:5(\n      __init__\n      Args(\n        Var(x))\n      Block:6(\n        AssignmentStmt:6(\n          NameExpr(self* [l])\n          NameExpr(x [l]))\n        AssignmentStmt:7(\n          MemberExpr:7(\n            NameExpr(self [l])\n            z)\n          IntExpr(1))))))\n\n[case testNonStandardNameForSelfAndInit]\nclass A:\n  def __init__(x):\n    x.y = 1\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      __init__\n      Args(\n        Var(x))\n      Block:3(\n        AssignmentStmt:3(\n          MemberExpr:3(\n            NameExpr(x [l])\n            y*)\n          IntExpr(1))))))\n\n[case testAssignmentAfterAttributeInit]\nclass A:\n  def __init__(self):\n    self.x = 1\n    self.x = 2\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      __init__\n      Args(\n        Var(self))\n      Block:3(\n        AssignmentStmt:3(\n          MemberExpr:3(\n            NameExpr(self [l])\n            x*)\n          IntExpr(1))\n        AssignmentStmt:4(\n          MemberExpr:4(\n            NameExpr(self [l])\n            x)\n          IntExpr(2))))))\n\n[case testOverloadedMethod]\nfrom typing import overload\nclass A:\n  @overload\n  def f(self) -> None: self\n  @overload\n  def f(self, x: 'A') -> None: self\n  def f(self, *args): self\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [overload])\n  ClassDef:2(\n    A\n    OverloadedFuncDef:3(\n      FuncDef:7(\n        f\n        Args(\n          Var(self))\n        VarArg(\n          Var(args))\n        Block:7(\n          ExpressionStmt:7(\n            NameExpr(self [l]))))\n      Overload(def (self: __main__.A), \\\n               def (self: __main__.A, x: __main__.A))\n      Decorator:3(\n        Var(f)\n        NameExpr(overload [typing.overload])\n        FuncDef:4(\n          f\n          Args(\n            Var(self))\n          def (self: __main__.A)\n          Block:4(\n            ExpressionStmt:4(\n              NameExpr(self [l])))))\n      Decorator:5(\n        Var(f)\n        NameExpr(overload [typing.overload])\n        FuncDef:6(\n          f\n          Args(\n            Var(self)\n            Var(x))\n          def (self: __main__.A, x: __main__.A)\n          Block:6(\n            ExpressionStmt:6(\n              NameExpr(self [l]))))))))\n\n[case testAttributeWithoutType]\nclass A:\n    a = object\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    AssignmentStmt:2(\n      NameExpr(a* [m])\n      NameExpr(object [builtins.object]))))\n\n[case testDataAttributeRefInClassBody]\nclass A:\n    x = 1\n    y = x\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    AssignmentStmt:2(\n      NameExpr(x [m])\n      IntExpr(1)\n      builtins.int)\n    AssignmentStmt:3(\n      NameExpr(y* [m])\n      NameExpr(x [__main__.A.x]))))\n\n[case testMethodRefInClassBody]\nclass A:\n    def f(self): pass\n    g = f\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      f\n      Args(\n        Var(self))\n      Block:2(\n        PassStmt:2()))\n    AssignmentStmt:3(\n      NameExpr(g* [m])\n      NameExpr(f [__main__.A.f]))))\n\n[case testIfStatementInClassBody]\nclass A:\n    if A:\n        x = 1\n    else:\n        x = 2\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    IfStmt:2(\n      If(\n        NameExpr(A [__main__.A]))\n      Then(\n        AssignmentStmt:3(\n          NameExpr(x [m])\n          IntExpr(1)\n          builtins.int))\n      Else(\n        AssignmentStmt:5(\n          NameExpr(x [__main__.A.x])\n          IntExpr(2))))))\n\n[case testForStatementInClassBody]\nclass A:\n    for x in [1, 2]:\n        y = x\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    ForStmt:2(\n      NameExpr(x* [m])\n      ListExpr:2(\n        IntExpr(1)\n        IntExpr(2))\n      Block:3(\n        AssignmentStmt:3(\n          NameExpr(y* [m])\n          NameExpr(x [__main__.A.x]))))))\n\n[case testReferenceToClassWithinFunction]\ndef f():\n    class A: pass\n    A\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ClassDef:2(\n        A\n        PassStmt:2())\n      ExpressionStmt:3(\n        NameExpr(A [__main__.A@2])))))\n\n[case testReferenceToClassWithinClass]\nclass A:\n    class B: pass\n    B\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    ClassDef:2(\n      B\n      PassStmt:2())\n    ExpressionStmt:3(\n      NameExpr(B [__main__.A.B]))))\n\n[case testClassWithBaseClassWithinClass]\nclass A:\n    class B: pass\n    class C(B): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    ClassDef:2(\n      B\n      PassStmt:2())\n    ClassDef:3(\n      C\n      BaseType(\n        __main__.A.B)\n      PassStmt:3())))\n\n[case testDeclarationReferenceToNestedClass]\ndef f() -> None:\n    class A: pass\n    x = None # type: A\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def ()\n    Block:2(\n      ClassDef:2(\n        A\n        PassStmt:2())\n      AssignmentStmt:3(\n        NameExpr(x [l])\n        NameExpr(None [builtins.None])\n        __main__.A@2))))\n\n[case testAccessToLocalInOuterScopeWithinNestedClass]\ndef f(x):\n    class A:\n        y = x\n        def g(self):\n            z = x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    Block:2(\n      ClassDef:2(\n        A\n        AssignmentStmt:3(\n          NameExpr(y* [m])\n          NameExpr(x [l]))\n        FuncDef:4(\n          g\n          Args(\n            Var(self))\n          Block:5(\n            AssignmentStmt:5(\n              NameExpr(z* [l])\n              NameExpr(x [l]))))))))\n\n[case testQualifiedMetaclass]\nimport abc\nclass A(metaclass=abc.ABCMeta): pass\n[out]\nMypyFile:1(\n  Import:1(abc)\n  ClassDef:2(\n    A\n    Metaclass(MemberExpr:2(\n      NameExpr(abc)\n      ABCMeta [abc.ABCMeta]))\n    PassStmt:2()))\n\n[case testStaticMethod]\nclass A:\n  @staticmethod\n  def f(z: int) -> str: pass\n[builtins fixtures/staticmethod.pyi]\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    Decorator:2(\n      Var(f)\n      FuncDef:3(\n        f\n        Args(\n          Var(z))\n        def (z: builtins.int) -> builtins.str\n        Static\n        Block:3(\n          PassStmt:3())))))\n\n[case testStaticMethodWithNoArgs]\nclass A:\n  @staticmethod\n  def f() -> str: pass\n[builtins fixtures/staticmethod.pyi]\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    Decorator:2(\n      Var(f)\n      FuncDef:3(\n        f\n        def () -> builtins.str\n        Static\n        Block:3(\n          PassStmt:3())))))\n\n[case testClassMethod]\nclass A:\n  @classmethod\n  def f(cls, z: int) -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    Decorator:2(\n      Var(f)\n      FuncDef:3(\n        f\n        Args(\n          Var(cls)\n          Var(z))\n        def (cls: Type[__main__.A], z: builtins.int) -> builtins.str\n        Class\n        Block:3(\n          PassStmt:3())))))\n\n[case testClassMethodWithNoArgs]\nclass A:\n  @classmethod\n  def f(cls) -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    Decorator:2(\n      Var(f)\n      FuncDef:3(\n        f\n        Args(\n          Var(cls))\n        def (cls: Type[__main__.A]) -> builtins.str\n        Class\n        Block:3(\n          PassStmt:3())))))\n\n[case testProperty]\nimport typing\nclass A:\n  @property\n  def f(self) -> str: pass\n[builtins fixtures/property.pyi]\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    Decorator:3(\n      Var(f)\n      FuncDef:4(\n        f\n        Args(\n          Var(self))\n        def (self: __main__.A) -> builtins.str\n        Property\n        Block:4(\n          PassStmt:4())))))\n\n[case testClassDecorator]\nimport typing\n@object\nclass A: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:3(\n    A\n    Decorators(\n      NameExpr(object [builtins.object]))\n    PassStmt:3()))\n\n[case testClassAttributeAsMethodDefaultArgumentValue]\nimport typing\nclass A:\n    X = 1\n    def f(self, x : int = X) -> None: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    AssignmentStmt:3(\n      NameExpr(X [m])\n      IntExpr(1)\n      builtins.int)\n    FuncDef:4(\n      f\n      Args(\n        Var(self)\n        default(\n          Var(x)\n          NameExpr(X [__main__.A.X])))\n      def (self: __main__.A, x: builtins.int =)\n      Block:4(\n        PassStmt:4()))))\n\n[case testInvalidBaseClass]\n\nfrom typing import Any, Callable\nclass A(None): pass\nclass B(Any): pass\na: Callable[[], int]\nclass C(a): pass\n[out]\nmain:3: error: Invalid base class \"None\"\nmain:6: error: Variable \"__main__.a\" is not valid as a type\nmain:6: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\nmain:6: error: Invalid base class \"a\"\n\n[case testTupleAsBaseClass]\n\nimport m\n[file m.pyi]\nfrom typing import Tuple\nclass A(Tuple[int, str]): pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  Import:2(m))\nMypyFile:1(\n  tmp/m.pyi\n  ImportFrom:1(typing, [Tuple])\n  ClassDef:2(\n    A\n    TupleType(\n      Tuple[builtins.int, builtins.str])\n    BaseType(\n      builtins.tuple[Union[builtins.int, builtins.str], ...])\n    PassStmt:2()))\n\n[case testBaseClassFromIgnoredModule]\nimport m # type: ignore\nclass B(m.A):\n   pass\n[out]\nMypyFile:1(\n  Import:1(m)\n  ClassDef:2(\n    B\n    FallbackToAny\n    PassStmt:3())\n  IgnoredLines(1))\n\n[case testBaseClassFromIgnoredModuleUsingImportFrom]\nfrom m import A # type: ignore\nclass B(A, int):\n   pass\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [A])\n  ClassDef:2(\n    B\n    FallbackToAny\n    BaseType(\n      builtins.int)\n    PassStmt:3())\n  IgnoredLines(1))\n\n[case testBaseClassWithExplicitAnyType]\nfrom typing import Any\nA = 1 # type: Any\nclass B(A):\n   pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Any])\n  AssignmentStmt:2(\n    NameExpr(A [__main__.A])\n    IntExpr(1)\n    Any)\n  ClassDef:3(\n    B\n    FallbackToAny\n    PassStmt:4()))\n"
  },
  {
    "path": "test-data/unit/semanal-classvar.test",
    "content": "[case testClassVarDef]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [ClassVar])\n  ClassDef:2(\n    A\n    AssignmentStmt:3(\n      NameExpr(x [m])\n      IntExpr(1)\n      builtins.int)))\n\n[case testClassVarDefInModuleScope]\nfrom typing import ClassVar\nx = None  # type: ClassVar[int]\n[out]\nmain:2: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarDefInFuncScope]\nfrom typing import ClassVar\ndef f() -> None:\n    x = None  # type: ClassVar[int]\n[out]\nmain:3: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarDefInMethod]\nfrom typing import ClassVar\nclass A:\n    def f(self) -> None:\n        x = None  # type: ClassVar\n[out]\nmain:4: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarTooManyArguments]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int, str]\n[out]\nmain:3: error: ClassVar[...] must have at most one type argument\n\n[case testClassVarWithoutArguments]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [ClassVar])\n  ClassDef:2(\n    A\n    AssignmentStmt:3(\n      NameExpr(x [m])\n      IntExpr(1)\n      Any)))\n\n[case testClassVarWithTypeVar]\n\nfrom typing import ClassVar, TypeVar\nT = TypeVar('T')\nclass A:\n    x = None  # type: ClassVar[T]\n[out]\nmain:5: error: Type variable \"__main__.T\" is unbound\nmain:5: note: (Hint: Use \"Generic[T]\" or \"Protocol[T]\" base class to bind \"T\" inside a class)\nmain:5: note: (Hint: Use \"T\" in function signature to bind \"T\" inside a function)\n\n[case testClassVarInFunctionArgs]\nfrom typing import ClassVar\ndef f(x: str, y: ClassVar) -> None: pass\n[out]\nmain:2: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarInMethodArgs]\nfrom typing import ClassVar\nclass A:\n    def f(x: str, y: ClassVar) -> None: pass\n[out]\nmain:3: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarFunctionRetType]\nfrom typing import ClassVar\ndef f() -> ClassVar: pass\n[out]\nmain:2: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarMethodRetType]\nfrom typing import ClassVar\nclass A:\n    def f(self) -> ClassVar: pass\n[out]\nmain:3: error: ClassVar can only be used for assignments in class body\n\n[case testMultipleClassVarInFunctionSig]\nfrom typing import ClassVar\ndef f(x: ClassVar, y: ClassVar) -> ClassVar: pass\n[out]\nmain:2: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarInCallableArgs]\nfrom typing import Callable, ClassVar, Any\nf = None  # type: Callable[[int, ClassVar], Any]\n[out]\nmain:2: error: Invalid type: ClassVar nested inside other type\n\n[case testClassVarInCallableRet]\nfrom typing import Callable, ClassVar\nf = None  # type: Callable[..., ClassVar]\n[out]\nmain:2: error: Invalid type: ClassVar nested inside other type\n\n[case testClassVarInUnion]\nfrom typing import ClassVar, Union\nx = None  # type: Union[ClassVar, str]\n[out]\nmain:2: error: Invalid type: ClassVar nested inside other type\n\n[case testClassVarInUnionAsAttribute]\nfrom typing import ClassVar, Union\nclass A:\n    x = None  # type: Union[ClassVar, str]\n[out]\nmain:3: error: Invalid type: ClassVar nested inside other type\n\n[case testListWithClassVars]\nfrom typing import ClassVar, List\nx = []  # type: List[ClassVar]\n[builtins fixtures/list.pyi]\n[out]\nmain:2: error: Invalid type: ClassVar nested inside other type\n\n[case testTupleClassVar]\nfrom typing import ClassVar, Tuple\nx = None  # type: Tuple[ClassVar, int]\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: error: Invalid type: ClassVar nested inside other type\n\n[case testMultipleLvaluesWithList]\nfrom typing import ClassVar, Tuple\nclass A:\n    [x, y] = None, None  # type: Tuple[ClassVar, ClassVar]\n[builtins fixtures/tuple.pyi]\n[out]\nmain:3: error: Invalid type: ClassVar nested inside other type\n\n[case testDeeplyNested]\nfrom typing import Callable, ClassVar, Union\nclass A: pass\nclass B:\n    x = None  # type: Union[str, Callable[[A, ClassVar], int]]\n[out]\nmain:4: error: Invalid type: ClassVar nested inside other type\n\n[case testClassVarInClassVar]\nfrom typing import ClassVar\nclass A:\n    x = None  # type: ClassVar[ClassVar[int]]\n[out]\nmain:3: error: Invalid type: ClassVar nested inside other type\n\n[case testInsideGeneric]\nfrom typing import ClassVar, Generic, TypeVar\nT = TypeVar('T')\nclass A(Generic[T]): pass\nclass B:\n    x = None  # type: A[ClassVar]\n[out]\nmain:5: error: Invalid type: ClassVar nested inside other type\n\n[case testDefineOnSelf]\nfrom typing import ClassVar\nclass A:\n    def __init__(self) -> None:\n        self.x = None  # type: ClassVar\n[out]\nmain:4: error: ClassVar can only be used for assignments in class body\n\n[case testForIndex]\nfrom typing import ClassVar\nfor i in []:  # type: ClassVar\n    pass\n[out]\nmain:2: error: ClassVar can only be used for assignments in class body\n\n[case testForIndexInClassBody]\nfrom typing import ClassVar\nclass A:\n    for i in []:  # type: ClassVar\n        pass\n[out]\nmain:3: error: ClassVar can only be used for assignments in class body\n\n[case testWithStmt]\nfrom typing import ClassVar\nclass A: pass\nwith A() as x:  # type: ClassVar\n    pass\n[out]\nmain:3: error: ClassVar can only be used for assignments in class body\n\n[case testWithStmtInClassBody]\nfrom typing import ClassVar\nclass A: pass\nclass B:\n    with A() as x:  # type: ClassVar\n        pass\n[out]\nmain:4: error: ClassVar can only be used for assignments in class body\n\n[case testClassVarWithTypeVariable]\nfrom typing import ClassVar, TypeVar, Generic, List\n\nT = TypeVar('T')\n\nclass Some(Generic[T]):\n    error: ClassVar[T]  # E: ClassVar cannot contain type variables\n    nested: ClassVar[List[List[T]]]  # E: ClassVar cannot contain type variables\n    ok: ClassVar[int]\n[out]\n"
  },
  {
    "path": "test-data/unit/semanal-errors-python310.test",
    "content": "[case testMatchUndefinedSubject]\nimport typing\nmatch x:\n    case _:\n        pass\n[out]\nmain:2: error: Name \"x\" is not defined\n\n[case testMatchUndefinedValuePattern]\nimport typing\nx = 1\nmatch x:\n    case a.b:\n        pass\n[out]\nmain:4: error: Name \"a\" is not defined\n\n[case testMatchUndefinedClassPattern]\nimport typing\nx = 1\nmatch x:\n    case A():\n        pass\n[out]\nmain:4: error: Name \"A\" is not defined\n\n[case testNoneBindingWildcardPattern]\nimport typing\nx = 1\nmatch x:\n    case _:\n        _\n[out]\nmain:5: error: Name \"_\" is not defined\n\n[case testNoneBindingStarredWildcardPattern]\nimport typing\nx = 1\nmatch x:\n    case [*_]:\n        _\n[out]\nmain:5: error: Name \"_\" is not defined\n"
  },
  {
    "path": "test-data/unit/semanal-errors.test",
    "content": "[case testUndefinedVariableInGlobalStatement]\nimport typing\nx\ny\n[out]\nmain:2: error: Name \"x\" is not defined\nmain:3: error: Name \"y\" is not defined\n\n[case testUndefinedVariableWithinFunctionContext]\nimport typing\ndef f() -> None:\n  x\ny\n[out]\nmain:3: error: Name \"x\" is not defined\nmain:4: error: Name \"y\" is not defined\n\n[case testMethodScope]\nimport typing\nclass A:\n  def f(self): pass\nf\n[out]\nmain:4: error: Name \"f\" is not defined\n\n[case testMethodScope2]\nimport typing\nclass A:\n  def f(self): pass\nclass B:\n  def g(self) -> None:\n    f # error\n    g # error\n[out]\nmain:6: error: Name \"f\" is not defined\nmain:7: error: Name \"g\" is not defined\n\n[case testInvalidType]\nimport typing\nx = None # type: X\n[out]\nmain:2: error: Name \"X\" is not defined\n\n[case testInvalidGenericArg]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\nx = 0 # type: A[y]\n[out]\nmain:4: error: Name \"y\" is not defined\n\n[case testInvalidNumberOfGenericArgsInTypeDecl]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A: pass\nclass B(Generic[t]): pass\nx = 0 # type: B[A, A]\ny = 0 # type: A[A]\n[out]\nmain:5: error: \"B\" expects 1 type argument, but 2 given\nmain:6: error: \"A\" expects no type arguments, but 1 given\n\n[case testInvalidNumberOfGenericArgsInUndefinedArg]\n\nclass A: pass\nx = None  # type: A[int] # E: \"A\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfGenericArgsInNestedBlock]\n\nclass A: pass\nclass B:\n    def f(self) -> None:\n        while 1:\n            x = None  # type: A[int] \\\n                # E: \"A\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfGenericArgsInSignature]\nimport typing\nclass A: pass\ndef f() -> A[int]: pass # E: \"A\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfGenericArgsInOverloadedSignature]\nfrom typing import overload\nclass A: pass\n@overload\ndef f(): pass\n@overload\ndef f(x: A[int]) -> None: pass # E: \"A\" expects no type arguments, but 1 given\ndef f(*args): pass\n[out]\n\n[case testInvalidNumberOfGenericArgsInBaseType]\nimport typing\nclass A: pass\nclass B(A[int]): pass # E: \"A\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfGenericArgsInCast]\nfrom typing import cast\nclass A: pass\nx = cast(A[int], 1) # E: \"A\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfGenericArgsInNestedGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): pass\nclass B: pass\ndef f() -> A[B[int]]: pass # E: \"B\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfGenericArgsInTupleType]\nfrom typing import Tuple\nclass A: pass\nx = None # type: Tuple[A[int]] # E: \"A\" expects no type arguments, but 1 given\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testInvalidNumberOfGenericArgsInFunctionType]\nfrom typing import Callable\nclass A: pass\nx = None # type: Callable[[A[int]], int]  # E: \"A\" expects no type arguments, but 1 given\ny = None # type: Callable[[], A[int]]  # E: \"A\" expects no type arguments, but 1 given\n[out]\n\n[case testVarOrFuncAsType]\n\nimport typing\ndef f(): pass\nx = 1\ny = 0 # type: f\nz = 0 # type: x\n[out]\nmain:5: error: Function \"__main__.f\" is not valid as a type\nmain:5: note: Perhaps you need \"Callable[...]\" or a callback protocol?\nmain:6: error: Variable \"__main__.x\" is not valid as a type\nmain:6: note: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testGlobalVarRedefinition]\nimport typing\nclass A: pass\nx = 0 # type: A\nx = 0 # type: A\n[out]\nmain:4: error: Name \"x\" already defined on line 3\n\n[case testLocalVarRedefinition]\nimport typing\nclass A: pass\ndef f() -> None:\n  x = 0 # type: A\n  x = 0 # type: A\n[out]\nmain:5: error: Name \"x\" already defined on line 4\n\n[case testClassVarRedefinition]\nimport typing\nclass A:\n  x = 0 # type: object\n  x = 0 # type: object\n[out]\nmain:4: error: Name \"x\" already defined on line 3\n\n[case testMultipleClassDefinitions]\nimport typing\nclass A: pass\nclass A: pass\n[out]\nmain:3: error: Name \"A\" already defined on line 2\n\n[case testMultipleMixedDefinitions]\nimport typing\nx = 1\ndef x(): pass\nclass x: pass\n[out]\nmain:3: error: Name \"x\" already defined on line 2\nmain:4: error: Name \"x\" already defined on line 2\n\n[case testNameNotImported]\nimport typing\nfrom m import y\nx\n[file m.py]\nx = y = 1\n[out]\nmain:3: error: Name \"x\" is not defined\n\n[case testMissingNameInImportFrom]\nimport typing\nfrom m import y\n[file m.py]\nx = 1\n[out]\nmain:2: error: Module \"m\" has no attribute \"y\"\n\n[case testMissingModule]\nimport typing\nimport m\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"m\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testMissingModule2]\nimport typing\nfrom m import x\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"m\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testMissingModule3]\nimport typing\nfrom m import *\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"m\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testMissingModuleRelativeImport]\nimport typing\nimport m\n[file m/__init__.py]\nfrom .x import y\n[out]\ntmp/m/__init__.py:1: error: Cannot find implementation or library stub for module named \"m.x\"\ntmp/m/__init__.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testMissingModuleRelativeImport2]\nimport typing\nimport m.a\n[file m/__init__.py]\n[file m/a.py]\nfrom .x import y\n[out]\ntmp/m/a.py:1: error: Cannot find implementation or library stub for module named \"m.x\"\ntmp/m/a.py:1: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\n\n[case testModuleNotImported]\nimport typing\nimport _m\n_n.x\n[file _m.py]\nimport _n\n[file _n.py]\nx = 1\n[out]\nmain:3: error: Name \"_n\" is not defined\n\n[case testImportAsteriskPlusUnderscore]\nimport typing\nfrom _m import *\n_x\n__x__\n[file _m.py]\n_x = __x__ = 1\n[out]\nmain:3: error: Name \"_x\" is not defined\nmain:4: error: Name \"__x__\" is not defined\n\n[case testRelativeImportAtTopLevelModule]\nfrom . import m\n[out]\nmain:1: error: No parent module -- cannot perform relative import\n\n[case testRelativeImportAtTopLevelModule2]\nfrom .. import m\n[out]\nmain:1: error: No parent module -- cannot perform relative import\n\n[case testUndefinedTypeWithQualifiedName]\nimport typing\nimport m\ndef f() -> m.c: pass\ndef g() -> n.c: pass\n[file m.py]\n[out]\nmain:3: error: Name \"m.c\" is not defined\nmain:4: error: Name \"n\" is not defined\n\n[case testMissingPackage]\nimport typing\nimport m.n\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"m.n\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:2: error: Cannot find implementation or library stub for module named \"m\"\n\n[case testMissingPackage2]\nimport typing\nfrom m.n import x\nfrom a.b import *\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"m.n\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:3: error: Cannot find implementation or library stub for module named \"a.b\"\n\n[case testErrorInImportedModule]\nimport m\n[file m.py]\nimport typing\nx = y\n[out]\ntmp/m.py:2: error: Name \"y\" is not defined\n\n[case testErrorInImportedModule2]\nimport m.n\n[file m/__init__.py]\n[file m/n.py]\nimport k\n[file k.py]\nimport typing\nx = y\n[out]\ntmp/k.py:2: error: Name \"y\" is not defined\n\n[case testPackageWithoutInitFile]\n# flags: --no-namespace-packages\nimport typing\nimport m.n\nm.n.x\n[file m/n.py]\nx = 1\n[out]\nmain:3: error: Cannot find implementation or library stub for module named \"m.n\"\nmain:3: note: See https://kotlinisland.github.io/basedmypy/running_mypy.html#missing-imports\nmain:3: error: Cannot find implementation or library stub for module named \"m\"\n\n[case testBreakOutsideLoop]\nbreak\ndef f():\n  break\n[out]\nmain:1: error: \"break\" outside loop\nmain:3: error: \"break\" outside loop\n\n[case testContinueOutsideLoop]\ncontinue\ndef f():\n  continue\n[out]\nmain:1: error: \"continue\" outside loop\nmain:3: error: \"continue\" outside loop\n\n[case testReturnOutsideFunction]\ndef f(): pass\nreturn\nreturn 1\n[out]\nmain:2: error: \"return\" outside function\nmain:3: error: \"return\" outside function\n\n[case testYieldOutsideFunction]\nyield 1\nyield\n[out]\nmain:1: error: \"yield\" outside function\nmain:2: error: \"yield\" outside function\n\n[case testInvalidLvalues1]\n1 = 1\n[out]\nmain:1: error: cannot assign to literal\n[out version>=3.10]\nmain:1: error: cannot assign to literal here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalues2]\n(1) = 1\n[out]\nmain:1: error: cannot assign to literal\n[out version>=3.10]\nmain:1: error: cannot assign to literal here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalues3]\n(1, 1) = 1\n[out]\nmain:1: error: cannot assign to literal\n\n[case testInvalidLvalues4]\n[1, 1] = 1\n[out]\nmain:1: error: cannot assign to literal\n\n[case testInvalidLvalues6]\nx = y = z = 1  # ok\nx, (y, 1) = 1\n[out]\nmain:2: error: cannot assign to literal\n\n[case testInvalidLvalues7]\nx, [y, 1] = 1\n[out]\nmain:1: error: cannot assign to literal\n\n[case testInvalidLvalues8]\nx, [y, [z, 1]] = 1\n[out]\nmain:1: error: cannot assign to literal\n\n[case testInvalidLvalues9]\nx, (y) = 1 # ok\nx, (y, (z, z)) = 1 # ok\nx, (y, (z, 1)) = 1\n[out]\nmain:3: error: cannot assign to literal\n\n[case testInvalidLvalues10]\nx + x = 1\n[out]\nmain:1: error: cannot assign to operator\n[out version>=3.10]\nmain:1: error: cannot assign to expression here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalues11]\n-x = 1\n[out]\nmain:1: error: cannot assign to operator\n[out version>=3.10]\nmain:1: error: cannot assign to expression here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalues12]\n1.1 = 1\n[out]\nmain:1: error: cannot assign to literal\n[out version>=3.10]\nmain:1: error: cannot assign to literal here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalues13]\n'x' = 1\n[out]\nmain:1: error: cannot assign to literal\n[out version>=3.10]\nmain:1: error: cannot assign to literal here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalues14]\nx() = 1\n[out]\nmain:1: error: cannot assign to function call\n[out version>=3.10]\nmain:1: error: cannot assign to function call here. Maybe you meant '==' instead of '='?\n\n[case testTwoStarExpressions]\na, *b, *c = 1\n*a, (*b, c) = 1\na, (*b, *c) = 1\n[*a, *b] = 1\n[out]\nmain:1: error: Two starred expressions in assignment\nmain:3: error: Two starred expressions in assignment\nmain:4: error: Two starred expressions in assignment\n\n[case testTwoStarExpressionsInForStmt]\nz = 1\nfor a, *b, *c in z:\n    pass\nfor *a, (*b, c) in z:\n    pass\nfor a, (*b, *c) in z:\n    pass\nfor [*a, *b] in z:\n    pass\n[out]\nmain:2: error: Two starred expressions in assignment\nmain:6: error: Two starred expressions in assignment\nmain:8: error: Two starred expressions in assignment\n\n[case testTwoStarExpressionsInGeneratorExpr]\n(a for a, *b, *c in [])\n(a for *a, (*b, c) in [])\n(a for a, (*b, *c) in [])\n[out]\nmain:1: error: Name \"a\" is not defined\nmain:1: error: Two starred expressions in assignment\nmain:3: error: Two starred expressions in assignment\n\n[case testStarExpressionRhs]\nb = 1\nc = 1\nd = 1\na = *b\n[out]\nmain:4: error: can't use starred expression here\n\n[case testStarExpressionInExp]\na = 1\n*a + 1\n[out]\nmain:2: error: can't use starred expression here\n\n[case testInvalidDel1]\nx = 1\ndel x(1)\n[out]\nmain:2: error: cannot delete function call\n\n[case testInvalidDel2]\nx = 1\ndel x + 1\n[out]\nmain:2: error: cannot delete operator\n[out version>=3.10]\nmain:2: error: cannot delete expression\n\n[case testInvalidDel3]\ndel z     # E: Name \"z\" is not defined\n\n[case testFunctionTvarScope]\n\nfrom typing import TypeVar\nt = TypeVar('t')\ndef f(x: t) -> t: pass\nx = 0 # type: t\n[out]\nmain:5: error: Type variable \"__main__.t\" is unbound\nmain:5: note: (Hint: Use \"Generic[t]\" or \"Protocol[t]\" base class to bind \"t\" inside a class)\nmain:5: note: (Hint: Use \"t\" in function signature to bind \"t\" inside a function)\n\n[case testClassTvarScope]\n\nfrom typing import Generic, TypeVar\nt = TypeVar('t')\nclass c(Generic[t]): pass\nx = 0 # type: t\n[out]\nmain:5: error: Type variable \"__main__.t\" is unbound\nmain:5: note: (Hint: Use \"Generic[t]\" or \"Protocol[t]\" base class to bind \"t\" inside a class)\nmain:5: note: (Hint: Use \"t\" in function signature to bind \"t\" inside a function)\n\n[case testExpressionRefersToTypeVariable]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass c(Generic[t]):\n    def f(self) -> None: x = t\ndef f(y: t): x = t\n[out]\nmain:4: error: \"t\" is a type variable and only valid in type context\nmain:5: error: \"t\" is a type variable and only valid in type context\n\n[case testMissingSelf]\nimport typing\nclass A:\n  def f(): pass\n[out]\nmain:3: error: Method must have at least one argument. Did you forget the \"self\" argument?\n\n[case testInvalidBaseClass]\nimport typing\nclass A(B): pass\n[out]\nmain:2: error: Name \"B\" is not defined\n\n[case testSuperOutsideClass]\nclass A: pass\nsuper().x\ndef f() -> None: super().y\n[out]\nmain:2: error: \"super\" used outside class\nmain:3: error: \"super\" used outside class\n\n[case testMissingSelfInMethod]\nimport typing\nclass A:\n  def f() -> None: pass\n  def g(): pass\n[out]\nmain:3: error: Method must have at least one argument. Did you forget the \"self\" argument?\nmain:4: error: Method must have at least one argument. Did you forget the \"self\" argument?\n\n[case testMultipleMethodDefinition]\nimport typing\nclass A:\n  def f(self) -> None: pass\n  def g(self) -> None: pass\n  def f(self, x: object) -> None: pass\n[out]\nmain:5: error: Name \"f\" already defined on line 3\n\n[case testInvalidGlobalDecl]\nimport typing\ndef f() -> None:\n    global x\n    x = None\n[out]\nmain:4: error: Name \"x\" is not defined\n\n[case testInvalidNonlocalDecl]\nimport typing\ndef f():\n    def g() -> None:\n       nonlocal x\n       x = None\n[out]\nmain:4: error: No binding for nonlocal \"x\" found\nmain:5: error: Name \"x\" is not defined\n\n[case testNonlocalDeclNotMatchingGlobal]\nimport typing\nx = None\ndef f() -> None:\n    nonlocal x\n    x = None\n[out]\nmain:4: error: No binding for nonlocal \"x\" found\nmain:5: error: Name \"x\" is not defined\n\n[case testNonlocalDeclConflictingWithParameter]\nimport typing\ndef g():\n    x = None\n    def f(x) -> None:\n        nonlocal x\n        x = None\n[out]\nmain:5: error: Name \"x\" is already defined in local scope before nonlocal declaration\n\n[case testNonlocalDeclOutsideFunction]\nx = 2\nnonlocal x\n[out]\nmain:2: error: nonlocal declaration not allowed at module level\n\n[case testGlobalAndNonlocalDecl]\nimport typing\nx = 1\ndef f():\n    x = 1\n    def g() -> None:\n       global x\n       nonlocal x\n       x = None\n[out]\nmain:7: error: Name \"x\" is nonlocal and global\n\n[case testNonlocalAndGlobalDecl]\nimport typing\nx = 1\ndef f():\n    x = 1\n    def g() -> None:\n       nonlocal x\n       global x\n       x = None\n[out]\nmain:7: error: Name \"x\" is nonlocal and global\n\n[case testNestedFunctionAndScoping]\nimport typing\ndef f(x) -> None:\n    def g(y):\n        z = x\n    z\n    y\n    x\n[out]\nmain:5: error: Name \"z\" is not defined\nmain:6: error: Name \"y\" is not defined\n\n[case testMultipleNestedFunctionDef]\nimport typing\ndef f(x) -> None:\n    def g(): pass\n    x = 1\n    def g(): pass\n[out]\nmain:5: error: Name \"g\" already defined on line 3\n\n[case testRedefinedOverloadedFunction]\nfrom typing import overload, Any\ndef f() -> None:\n    @overload\n    def p(o: object) -> None: pass # no error\n    @overload\n    def p(o: Any) -> None: pass    # no error\n    x = 1\n    def p(): pass # fail\n[out]\nmain:3: error: An overloaded function outside a stub file must have an implementation\nmain:8: error: Name \"p\" already defined on line 3\n\n[case testNestedFunctionInMethod]\nimport typing\nclass A:\n   def f(self) -> None:\n       def g() -> None:\n           x\n       y\n[out]\nmain:5: error: Name \"x\" is not defined\nmain:6: error: Name \"y\" is not defined\n\n[case testImportScope]\nimport typing\ndef f() -> None:\n    import x\nx.y # E: Name \"x\" is not defined\n[file x.py]\ny = 1\n[out]\n\n[case testImportScope2]\nimport typing\ndef f() -> None:\n    from x import y\n    y\ny # E: Name \"y\" is not defined\n[file x.py]\ny = 1\n[out]\n\n[case testImportScope3]\nimport typing\ndef f() -> None:\n    from x import *\n    y\ny # E: Name \"y\" is not defined\n[file x.py]\ny = 1\n[out]\n\n[case testImportScope4]\nimport typing\nclass A:\n    from x import *\n    y\ny # E: Name \"y\" is not defined\n[file x.py]\ny = 1\n[out]\n\n[case testScopeOfNestedClass]\nimport typing\ndef f():\n    class A: pass\n    A\nA # E: Name \"A\" is not defined\n[out]\n\n[case testScopeOfNestedClass2]\nimport typing\nclass A:\n    class B: pass\nB # E: Name \"B\" is not defined\n[out]\n\n[case testScopeOfNestedClass3]\nimport typing\nclass A:\n    def f(self):\n        class B: pass\n    B # E: Name \"B\" is not defined\nB # E: Name \"B\" is not defined\n[out]\n\n[case testInvalidNestedClassReferenceInDecl]\nimport typing\nclass A: pass\nfoo = 0 # type: A.x      # E: Name \"A.x\" is not defined\n[out]\n\n[case testTvarScopingWithNestedClass]\n\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\ns = TypeVar('s')\nclass A(Generic[t]):\n    class B(Generic[s]):\n        x = 0 # type: A[s]\n        y = 0 # type: A[t]        # 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)\n    z = 0 # type: A[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    a = 0 # type: A[t]\n[out]\n\n[case testTestExtendPrimitives]\n# Extending bool is not checked here as it should be typed\n# as final meaning the type checker will detect it.\nclass C(bool): pass # ok\nclass A(int): pass # ok\nclass B(float): pass # ok\nclass D(str): pass # ok\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testCyclicInheritance1]\n\nclass A(A): pass # E: Cannot resolve name \"A\" (possible cyclic definition)\n[out]\n\n[case testCyclicInheritance2]\n\nclass A(B): pass # E: Cannot resolve name \"B\" (possible cyclic definition)\nclass B(A): pass\n[out]\n\n[case testAssignToTypeDef]\nimport typing\nclass A: pass\nA = None # E: Cannot assign to a type\n[out]\n\n[case testInvalidCastTargetSyntax]\n\nfrom typing import cast, TypeVar, Generic\nt = TypeVar('t')\nclass C(Generic[t]): pass\ncast(str + str, None)    # E: Cast target is not a type\ncast(C[str][str], None)  # E: Cast target is not a type\ncast(C[str + str], None) # E: Cast target is not a type\ncast([int], None)   # E: Bracketed expression \"[...]\" is not valid as a type \\\n                    # N: Did you mean \"list[...]\"?\n[out]\n\n[case testInvalidCastTargetType]\n\nfrom typing import cast\nx = 0\ncast(x, None)        # E: Variable \"__main__.x\" is not valid as a type \\\n                     # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\ncast(t, None)        # E: Name \"t\" is not defined\ncast(__builtins__.x, None) # E: Name \"__builtins__.x\" is not defined\n[out]\n\n[case testInvalidCastTargetType2]\nfrom typing import cast\nx = 0\ncast(str[str], None) # E: \"str\" expects no type arguments, but 1 given\n[out]\n\n[case testInvalidNumberOfArgsToCast]\nfrom typing import cast\ncast(str) # E: \"cast\" expects 2 arguments\ncast(str, None, None) # E: \"cast\" expects 2 arguments\n[out]\n\n[case testInvalidKindsOfArgsToCast]\nfrom typing import cast\ncast(str, *None) # E: \"cast\" must be called with 2 positional arguments\ncast(str, target=None) # E: \"cast\" must be called with 2 positional arguments\n[out]\n\n[case testInvalidAssertType]\nfrom typing import assert_type\nassert_type(1, type=int) # E: \"assert_type\" must be called with 2 positional arguments\nassert_type(1, *int) # E: \"assert_type\" must be called with 2 positional arguments\nassert_type() # E: \"assert_type\" expects 2 arguments\nassert_type(1, int, \"hello\") # E: \"assert_type\" expects 2 arguments\nassert_type(int, 1)  # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?\nassert_type(1, int[int])  # E: \"int\" expects no type arguments, but 1 given\n\n[case testInvalidAnyCall]\nfrom typing import Any\nAny(str, None)  # E: Any(...) is no longer supported. Use cast(Any, ...) instead\nAny(arg=str)  # E: Any(...) is no longer supported. Use cast(Any, ...) instead\n[out]\n\n[case testTypeListAsType]\n\ndef f(x: [int]) -> None: # E: Bracketed expression \"[...]\" is not valid as a type \\\n                         # N: Did you mean \"list[...]\"?\n    pass\n[out]\n\n[case testInvalidFunctionType]\nfrom typing import Callable\nx = None # type: Callable[int, str]\ny = None # type: Callable[int]\nz = None # type: Callable[int, int, int]\n[out]\nmain:2: error: The first argument to Callable must be a list of types, parameter specification, or \"...\"\nmain:2: note: See https://kotlinisland.github.io/basedmypy/kinds_of_types.html#callable-types-and-lambdas\nmain:3: error: Please use \"Callable[[<parameters>], <return type>]\" or \"Callable\"\nmain:4: error: Please use \"Callable[[<parameters>], <return type>]\" or \"Callable\"\n\n[case testAbstractGlobalFunction]\nimport typing\nfrom abc import abstractmethod\n@abstractmethod\ndef foo(): pass\n[out]\nmain:3: error: \"abstractmethod\" used with a non-method\n\n[case testAbstractNestedFunction]\nimport typing\nfrom abc import abstractmethod\ndef g() -> None:\n  @abstractmethod\n  def foo(): pass\n[out]\nmain:4: error: \"abstractmethod\" used with a non-method\n\n[case testInvalidTypeDeclaration]\nimport typing\ndef f(): pass\nf() = 1 # type: int\n[out]\nmain:3: error: cannot assign to function call\n[out version>=3.10]\nmain:3: error: cannot assign to function call here. Maybe you meant '==' instead of '='?\n\n[case testIndexedAssignmentWithTypeDeclaration]\nimport typing\nNone[1] = 1 # type: int\n[out]\nmain:2: error: Unexpected type declaration\n\n[case testNonSelfMemberAssignmentWithTypeDeclaration]\nimport typing\nNone.x = 1 # type: int\n[out]\nmain:2: error: Type cannot be declared in assignment to non-self attribute\n\n[case testNonSelfMemberAssignmentWithTypeDeclarationInMethod]\nimport typing\nclass A:\n  def f(self, x) -> None:\n    x.y = 1 # type: int\n[out]\nmain:4: error: Type cannot be declared in assignment to non-self attribute\n\n[case testInvalidTypeInTypeApplication]\n\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\nA[TypeVar] # E: Variable \"typing.TypeVar\" is not valid as a type \\\n           # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n[out]\n\n[case testInvalidTypeInTypeApplication2]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\nA[1] # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?\n[out]\n\n[case testVariableDeclWithInvalidNumberOfTypes]\nx, y = 1, 2 # type: int, str, int # E: Incompatible number of tuple items\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testVariableDeclWithInvalidNumberOfTypesNested]\nx, (y, z) = 1, (2, 3) # type: int, (str, int, int) # E: Incompatible number of tuple items\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testVariableDeclWithInvalidNumberOfTypesNested2]\nx, (y, z) = 1, (2, 3) # type: int, (str, ) # E: Incompatible number of tuple items\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testVariableDeclWithInvalidNumberOfTypesNested3]\nx, (y, z) = 1, (2, 3) # type: int, str # E: Tuple type expected for multiple variables\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testVariableDeclWithInvalidNumberOfTypesNested4]\nx, (y, z) = 1, (2, 3) # type: int, str, int # E: Incompatible number of tuple items\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testVariableDeclWithInvalidNumberOfTypesNested5]\nx, (y, ) = 1, (2, ) # type: int, str # E: Tuple type expected for multiple variables\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testVariableDeclWithInvalidType]\nx, y = 1, 2 # type: int # E: Tuple type expected for multiple variables\n[out]\n\n[case testInvalidLvalueWithExplicitType]\na = 1\na() = None # type: int\n[out]\nmain:2: error: cannot assign to function call\n[out version>=3.10]\nmain:2: error: cannot assign to function call here. Maybe you meant '==' instead of '='?\n\n[case testInvalidLvalueWithExplicitType2]\na = 1\na[1] = None # type: int # E: Unexpected type declaration\na.x = None # type: int \\\n    # E: Type cannot be declared in assignment to non-self attribute\n[out]\n\n[case testInvalidLvalueWithExplicitType3]\na = 1\na.y, a.x = None, None # type: int, int \\\n    # E: Type cannot be declared in assignment to non-self attribute \\\n    # E: Type cannot be declared in assignment to non-self attribute\na[1], a[2] = None, None # type: int, int \\\n    # E: Unexpected type declaration \\\n    # E: Unexpected type declaration\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testMissingGenericImport]\nfrom typing import TypeVar\nT = TypeVar('T')\nclass A(Generic[T]): pass\n[out]\nmain:3: error: Name \"Generic\" is not defined\n\n[case testInvalidTypeWithinGeneric]\nfrom typing import Generic\nclass A(Generic[int]): pass # E: Free type variable expected in Generic[...]\n[out]\n\n[case testInvalidTypeWithinNestedGenericClass]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass A(Generic[T]):\n    class B(Generic[T]): pass \\\n          # E: Free type variable expected in Generic[...]\n[out]\n\n[case testIncludingGenericTwiceInBaseClassList]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T], Generic[S]): pass \\\n      # E: Only single Generic[...] or Protocol[...] can be in bases\n[out]\n\n[case testInvalidMetaclass]\nclass A(metaclass=x): pass # E: Name \"x\" is not defined\n[out]\n\n[case testInvalidQualifiedMetaclass]\nimport abc\nclass A(metaclass=abc.Foo): pass # E: Name \"abc.Foo\" is not defined\n[out]\n\n[case testNonClassMetaclass]\ndef f(): pass\nclass A(metaclass=f): pass # E: Invalid metaclass \"f\"\n[out]\n\n[case testInvalidTypevarArguments]\nfrom typing import TypeVar\na = TypeVar()       # E: Too few arguments for TypeVar()\nb = TypeVar(x='b')  # E: TypeVar() expects a string literal as first argument\nc = TypeVar(1)      # E: TypeVar() expects a string literal as first argument\nT = TypeVar(b'T')      # E: TypeVar() expects a string literal as first argument\nd = TypeVar('D')    # E: String argument 1 \"D\" to TypeVar(...) does not match variable name \"d\"\ne = TypeVar('e', int, str, x=1)   # E: Unexpected argument to \"TypeVar()\": \"x\"\nf = TypeVar('f', (int, str), int) # E: Type expected\ng = TypeVar('g', int)             # E: Type variable must have at least two constrained types\nh = TypeVar('h', x=(int, str))    # E: Unexpected argument to \"TypeVar()\": \"x\"\ni = TypeVar('i', bound=1)         # E: \"1\" is a bare literal and cannot be used here, try Literal[1] instead?\nj = TypeVar('j', covariant=None)  # E: TypeVar \"covariant\" may only be a literal bool\nk = TypeVar('k', contravariant=1) # E: TypeVar \"contravariant\" may only be a literal bool\n[out]\n\n[case testMoreInvalidTypevarArguments]\nfrom typing import TypeVar\nT = TypeVar('T', int, str, bound=bool) # E: TypeVar cannot have both constraints and an upper bound\nS = TypeVar('S', covariant=True, contravariant=True) \\\n    # E: TypeVar cannot be both covariant and contravariant\n[builtins fixtures/bool.pyi]\n\n[case testInvalidTypevarArgumentsGenericConstraint]\nfrom typing import Generic, List, TypeVar\nfrom typing_extensions import Self\n\nT = TypeVar(\"T\")\n\ndef f(x: T) -> None:\n    Bad = TypeVar(\"Bad\", int, List[T])    # E: TypeVar constraint type cannot be parametrized by type variables\nclass C(Generic[T]):\n    Bad = TypeVar(\"Bad\", int, List[T])    # E: TypeVar constraint type cannot be parametrized by type variables\nclass D:\n    Bad = TypeVar(\"Bad\", int, List[Self]) # E: TypeVar constraint type cannot be parametrized by type variables\nS = TypeVar(\"S\", int, List[T])            # 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)\n\n[case testInvalidTypevarValues]\nfrom typing import TypeVar\nb = TypeVar('b', *[int]) # E: Unexpected argument to \"TypeVar()\"\nc = TypeVar('c', int, 2) # E: \"2\" is a bare literal and cannot be used here, try Literal[2] instead?\n[out]\n\n[case testObsoleteTypevarValuesSyntax]\nfrom typing import TypeVar\na = TypeVar('a', values=(int, str))\n[out]\nmain:2: error: TypeVar \"values\" argument not supported\nmain:2: error: Use TypeVar('T', t, ...) instead of TypeVar('T', values=(t, ...))\n\n[case testLocalTypevarScope]\nfrom typing import TypeVar\ndef f() -> None:\n    T = TypeVar('T')\ndef g(x: T) -> None: pass # E: Name \"T\" is not defined\n[out]\n\n[case testClassTypevarScope]\nfrom typing import TypeVar\nclass A:\n    T = TypeVar('T')\ndef g(x: T) -> None: pass # E: Name \"T\" is not defined\n[out]\n\n[case testRedefineVariableAsTypevar]\nfrom typing import TypeVar\nx = 0\nx = TypeVar('x') # E: Cannot redefine \"x\" as a type variable\n[out]\n\n[case testTypevarWithType]\nfrom typing import TypeVar\nx = TypeVar('x') # type: int # E: Cannot declare the type of a TypeVar or similar construct\n[out]\n\n[case testRedefineTypevar]\nfrom typing import TypeVar\nt = TypeVar('t')\nt = 1 # E: Invalid assignment target\n[out]\n\n[case testRedefineTypevar2]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef t(): pass # E: Name \"t\" already defined on line 2\n[out]\n\n[case testRedefineTypevar3]\nfrom typing import TypeVar\nt = TypeVar('t')\nclass t: pass # E: Name \"t\" already defined on line 2\n[out]\n\n[case testRedefineTypevar4]\nfrom typing import TypeVar\nt = TypeVar('t')\nfrom typing import Generic as t # E: Name \"t\" already defined on line 2\n[out]\n\n[case testInvalidStrLiteralType]\ndef f(x: 'foo'): pass # E: Name \"foo\" is not defined\n[out]\n\n[case testInvalidStrLiteralStrayBrace]\ndef f(x: 'int['): pass # E: Invalid type comment or annotation\n[out]\n\n[case testInvalidStrLiteralSpaces]\ndef f(x: 'A B'): pass # E: Invalid type comment or annotation\n[out]\n\n[case testInvalidMultilineLiteralType]\ndef f() -> \"A\\nB\": pass  # E: Invalid type comment or annotation\n[out]\n\n[case testInconsistentOverload]\nfrom typing import overload\ndef dec(x): pass\n@dec  # E: The implementation for an overloaded function must come last\ndef f(): pass\n@overload\ndef f(): pass\n[out]\n\n[case testInconsistentOverload2]\nfrom typing import overload\ndef dec(x): pass\n@dec  # E: The implementation for an overloaded function must come last\ndef f(): pass\n@overload\ndef f(): pass\n[out]\n\n[case testMissingOverloadDecorator]\nfrom typing import overload\ndef dec(x): pass\n@dec\ndef f(): pass\n@dec  # E: Name \"f\" already defined on line 3\ndef f(): pass\n[out]\n\n[case testIncompatibleSignatureInComment]\nimport typing\ndef f(): # type: (int) -> int\n  pass\ndef g(x): # type: () -> int\n  pass\n[out]\nmain:2: error: Type signature has too many arguments\nmain:4: error: Type signature has too few arguments\n\n[case testStaticmethodAndNonMethod]\nimport typing\n@staticmethod\ndef f(): pass\nclass A:\n  def g(self) -> None:\n    @staticmethod\n    def h(): pass\n[builtins fixtures/staticmethod.pyi]\n[out]\nmain:2: error: \"staticmethod\" used with a non-method\nmain:6: error: \"staticmethod\" used with a non-method\n\n[case testClassmethodAndNonMethod]\nimport typing\n@classmethod\ndef f(): pass\nclass A:\n  def g(self) -> None:\n    @classmethod\n    def h(): pass\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:2: error: \"classmethod\" used with a non-method\nmain:6: error: \"classmethod\" used with a non-method\n\n[case testNonMethodProperty]\nimport typing\n@property  # E: \"property\" used with a non-method\ndef f() -> int: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testOverloadedProperty]\nfrom typing import overload\nclass A:\n    @overload  # E: Decorators on top of @property are not supported\n    @property\n    def f(self) -> int: pass\n    @property  # E: Only supported top decorator is @f.setter\n    @overload\n    def f(self) -> int: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testOverloadedProperty2]\nfrom typing import overload\nclass A:\n    @overload  # E: An overloaded function outside a stub file must have an implementation\n    def f(self) -> int: pass\n    @property  # E: An overload can not be a property\n    @overload\n    def f(self) -> int: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testDecoratedProperty]\nimport typing\ndef dec(f): pass\nclass A:\n    @dec  # E: Decorators on top of @property are not supported\n    @property\n    def f(self) -> int: pass\n    @property  # OK\n    @dec\n    def g(self) -> int: pass\n    @dec  # type: ignore[misc]\n    @property\n    def h(self) -> int: pass\n    @dec  # type: ignore[prop-decorator]\n    @property\n    def i(self) -> int: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testImportTwoModulesWithSameNameInFunction]\nimport typing\ndef f() -> None:\n    import x\n    import y as x # E: Name \"x\" already defined (by an import)\n    x.y\n[file x.py]\ny = 1\n[file y.py]\n[out]\n\n[case testImportTwoModulesWithSameNameInGlobalContext]\nimport typing\nimport x\nimport y as x # E: Name \"x\" already defined (by an import)\nx.y\n[file x.py]\ny = 1\n[file y.py]\n[out]\n\n[case testListTypeAliasWithoutImport]\nimport typing\ndef f() -> List[int]: pass\n[builtins fixtures/list.pyi]\n[out]\nmain:2: error: Name \"List\" is not defined\nmain:2: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import List\")\n\n[case testInvalidWithTarget]\ndef f(): pass\nwith f() as 1: pass\n[out]\nmain:2: error: cannot assign to literal\n\n[case testInvalidTypeAnnotation]\nimport typing\ndef f() -> None:\n    1[2] = 1  # type: int\n[out]\nmain:3: error: Unexpected type declaration\n\n[case testInvalidTypeAnnotation2]\nimport typing\ndef f() -> None:\n    f() = 1  # type: int\n[out]\nmain:3: error: cannot assign to function call\n[out version>=3.10]\nmain:3: error: cannot assign to function call here. Maybe you meant '==' instead of '='?\n\n[case testInvalidReferenceToAttributeOfOuterClass]\nclass A:\n    class X: pass\n    class B:\n        y = X  # E: Name \"X\" is not defined\n[out]\n\n[case testStubPackage]\nfrom m import x\nfrom m import y # E: Module \"m\" has no attribute \"y\"\n[file m/__init__.pyi]\nx = 1\n[out]\n\n[case testStubPackageSubModule]\nfrom m import x\nfrom m import y # E: Module \"m\" has no attribute \"y\"\nfrom m.m2 import y\nfrom m.m2 import z # E: Module \"m.m2\" has no attribute \"z\"\n[file m/__init__.pyi]\nx = 1\n[file m/m2.pyi]\ny = 1\n[out]\n\n[case testListComprehensionSpecialScoping]\nclass A:\n    x = 1\n    y = 1\n    z = 1\n    [x for i in z if y]\n[out]\nmain:5: error: Name \"x\" is not defined\nmain:5: error: Name \"y\" is not defined\n\n[case testTypeRedeclarationNoSpuriousWarnings]\nfrom typing import Tuple\na = 1  # type: int\na = 's'  # type: str\na = ('spam', 'spam', 'eggs', 'spam')  # type: Tuple[str]\n[builtins fixtures/tuple.pyi]\n\n[out]\nmain:3: error: Name \"a\" already defined on line 2\nmain:4: error: Name \"a\" already defined on line 2\n\n[case testDuplicateDefFromImport]\nfrom m import A\nclass A:  # E: Name \"A\" already defined (possibly by an import)\n    pass\n[file m.py]\nclass A:\n    pass\n[out]\n\n[case testDuplicateDefDec]\nfrom typing import Any\ndef dec(x: Any) -> Any:\n    return x\n@dec\ndef f() -> None:\n    pass\n@dec  # E: Name \"f\" already defined on line 4\ndef f() -> None:\n    pass\n[out]\n\n[case testDuplicateDefOverload]\nfrom typing import overload, Any\nif 1:\n    @overload\n    def f(x: int) -> None:\n        pass\n    @overload\n    def f(x: str) -> None:\n        pass\n    def f(x: Any) -> None:\n        pass\nelse:\n    def f(x: str) -> None:  # E: Name \"f\" already defined on line 3\n        pass\n[out]\n\n[case testDuplicateDefNT]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('a', int),\n                     ('b', str)])\n\nclass N:  # E: Name \"N\" already defined on line 2\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testDuplicateDefTypedDict]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\n\nclass Point:  # E: Name \"Point\" already defined on line 2\n    pass\n[builtins fixtures/dict.pyi]\n\n[out]\n\n[case testTypeVarClassDup]\nfrom typing import TypeVar\nT = TypeVar('T')\nclass T: ...  # E: Name \"T\" already defined on line 2\n\n[out]\n\n[case testAliasDup]\nfrom typing import List\nA = List[int]\nclass A: ... # E: Name \"A\" already defined on line 2\n\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNoInvalidTypeInDynamicFunctions]\n\nfrom typing import Dict, TypeVar\nT = TypeVar('T')\n\ndef f():  # Note no annotation\n    x: Dict[str, T] = {}\n    y: T\n    z: x\n    def nested(): pass\n    t: nested\n\ndef g() -> None:\n    x: Dict[str, T] = {}  # 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)\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testParamSpec]\nfrom typing_extensions import ParamSpec\n\nTParams = ParamSpec('TParams')\nTP = ParamSpec('?')  # E: String argument 1 \"?\" to ParamSpec(...) does not match variable name \"TP\"\nTP2: int = ParamSpec('TP2')  # E: Cannot declare the type of a TypeVar or similar construct\n\n[out]\n\n\n[case testBaseClassAnnotatedWithoutArgs]\n# https://github.com/python/mypy/issues/11808\nfrom typing_extensions import Annotated\n# Next line should not crash:\nclass A(Annotated): pass  # E: Annotated[...] must have exactly one type argument and at least one annotation\n\n[case testInvalidUnpackTypes]\nfrom typing_extensions import Unpack\nfrom typing import Tuple\n\nheterogenous_tuple: Tuple[Unpack[Tuple[int, str]]]\nhomogeneous_tuple: Tuple[Unpack[Tuple[int, ...]]]\nbad: Tuple[Unpack[int]]  # E: \"int\" cannot be unpacked (must be tuple or TypeVarTuple)\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleErrors]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTVariadic = TypeVarTuple('TVariadic')\nTVariadic2 = TypeVarTuple('TVariadic2')\nTP = TypeVarTuple('?')  # E: String argument 1 \"?\" to TypeVarTuple(...) does not match variable name \"TP\"\nTP2: int = TypeVarTuple('TP2')  # E: Cannot declare the type of a TypeVar or similar construct\nTP3 = TypeVarTuple()  # E: Too few arguments for TypeVarTuple()\nTP4 = TypeVarTuple('TP4', 'TP4')  # E: Too many positional arguments for \"TypeVarTuple\"\nTP5 = TypeVarTuple(t='TP5')  # E: TypeVarTuple() expects a string literal as first argument\nTP6 = TypeVarTuple('TP6', bound=int)  # E: Unexpected keyword argument \"bound\" for \"TypeVarTuple\"\n\nx: TVariadic  # E: TypeVarTuple \"TVariadic\" is unbound\ny: Unpack[TVariadic]  # E: Unpack is only valid in a variadic position\n\n\nclass Variadic(Generic[Unpack[TVariadic], Unpack[TVariadic2]]):  # E: Can only use one type var tuple in a class def\n    pass\n\ndef bad_args(*args: TVariadic):  # E: TypeVarTuple \"TVariadic\" is only valid with an unpack\n    pass\n\ndef bad_kwargs(**kwargs: Unpack[TVariadic]):  # E: Unpack item in ** argument must be a TypedDict\n    pass\n\n[builtins fixtures/dict.pyi]\n"
  },
  {
    "path": "test-data/unit/semanal-expressions.test",
    "content": "[case testLiterals]\n(1, 'x', 1.1, 1.1j)\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    TupleExpr:1(\n      IntExpr(1)\n      StrExpr(x)\n      FloatExpr(1.1)\n      ComplexExpr(1.1j))))\n\n[case testMemberExpr]\nx = 1\nx.y\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(x [__main__.x])\n      y)))\n\n[case testIndexExpr]\nx = y = 1\nx[y]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  ExpressionStmt:2(\n    IndexExpr:2(\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y]))))\n\n[case testBinaryOperations]\nx = y = 1\nx + y\nx | y\nx is not y\nx == y\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  ExpressionStmt:2(\n    OpExpr:2(\n      +\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y])))\n  ExpressionStmt:3(\n    OpExpr:3(\n      |\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y])))\n  ExpressionStmt:4(\n    ComparisonExpr:4(\n      is not\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y])))\n  ExpressionStmt:5(\n    ComparisonExpr:5(\n      ==\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y]))))\n\n[case testUnaryOperations]\nx = 1\n-x\n~x\n+x\nnot x\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  ExpressionStmt:2(\n    UnaryExpr:2(\n      -\n      NameExpr(x [__main__.x])))\n  ExpressionStmt:3(\n    UnaryExpr:3(\n      ~\n      NameExpr(x [__main__.x])))\n  ExpressionStmt:4(\n    UnaryExpr:4(\n      +\n      NameExpr(x [__main__.x])))\n  ExpressionStmt:5(\n    UnaryExpr:5(\n      not\n      NameExpr(x [__main__.x]))))\n\n[case testSlices]\nx = y = z = 1\nx[y:z:x]\nx[:]\nx[:y]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y])\n      NameExpr(z* [__main__.z]))\n    IntExpr(1))\n  ExpressionStmt:2(\n    IndexExpr:2(\n      NameExpr(x [__main__.x])\n      SliceExpr:2(\n        NameExpr(y [__main__.y])\n        NameExpr(z [__main__.z])\n        NameExpr(x [__main__.x]))))\n  ExpressionStmt:3(\n    IndexExpr:3(\n      NameExpr(x [__main__.x])\n      SliceExpr:3(\n        <empty>\n        <empty>)))\n  ExpressionStmt:4(\n    IndexExpr:4(\n      NameExpr(x [__main__.x])\n      SliceExpr:4(\n        <empty>\n        NameExpr(y [__main__.y])))))\n\n[case testTupleLiteral]\nx = y = 1\nx, y\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  ExpressionStmt:2(\n    TupleExpr:2(\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y]))))\n\n[case testListLiteral]\nx = y = 1\n([], [x, y])\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  ExpressionStmt:2(\n    TupleExpr:2(\n      ListExpr:2()\n      ListExpr:2(\n        NameExpr(x [__main__.x])\n        NameExpr(y [__main__.y])))))\n\n[case testDictLiterals]\nx = y = 1\n{ x : y, y : x }\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  ExpressionStmt:2(\n    DictExpr:2(\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y])\n      NameExpr(y [__main__.y])\n      NameExpr(x [__main__.x]))))\n\n[case testListComprehension]\na = 0\n([x + 1 for x in a])\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:2(\n    ListComprehension:2(\n      GeneratorExpr:2(\n        OpExpr:2(\n          +\n          NameExpr(x [l])\n          IntExpr(1))\n        NameExpr(x* [l])\n        NameExpr(a [__main__.a])))))\n\n[case testListComprehensionInFunction]\ndef f(a) -> None:\n    [x for x in a]\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(a))\n    def (a: Any)\n    Block:2(\n      ExpressionStmt:2(\n        ListComprehension:2(\n          GeneratorExpr:2(\n            NameExpr(x [l])\n            NameExpr(x* [l])\n            NameExpr(a [l])))))))\n\n[case testListComprehensionWithCondition]\na = 0\nb = [x for x in a if x]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  AssignmentStmt:2(\n    NameExpr(b* [__main__.b])\n    ListComprehension:2(\n      GeneratorExpr:2(\n        NameExpr(x [l])\n        NameExpr(x* [l])\n        NameExpr(a [__main__.a])\n        NameExpr(x [l])))))\n\n[case testSetComprehension]\na = 0\n({x + 1 for x in a})\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:2(\n    SetComprehension:2(\n      GeneratorExpr:2(\n        OpExpr:2(\n          +\n          NameExpr(x [l])\n          IntExpr(1))\n        NameExpr(x* [l])\n        NameExpr(a [__main__.a])))))\n\n[case testSetComprehensionWithCondition]\na = 0\nb = {x for x in a if x}\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  AssignmentStmt:2(\n    NameExpr(b* [__main__.b])\n    SetComprehension:2(\n      GeneratorExpr:2(\n        NameExpr(x [l])\n        NameExpr(x* [l])\n        NameExpr(a [__main__.a])\n        NameExpr(x [l])))))\n\n[case testDictionaryComprehension]\na = 0\n({x: x + 1 for x in a})\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:2(\n    DictionaryComprehension:2(\n      NameExpr(x [l])\n      OpExpr:2(\n        +\n        NameExpr(x [l])\n        IntExpr(1))\n      NameExpr(x* [l])\n      NameExpr(a [__main__.a]))))\n\n[case testDictionaryComprehensionWithCondition]\na = 0\nb = {x: x + 1 for x in a if x}\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  AssignmentStmt:2(\n    NameExpr(b* [__main__.b])\n    DictionaryComprehension:2(\n      NameExpr(x [l])\n      OpExpr:2(\n        +\n        NameExpr(x [l])\n        IntExpr(1))\n      NameExpr(x* [l])\n      NameExpr(a [__main__.a])\n      NameExpr(x [l]))))\n\n[case testGeneratorExpression]\na = 0\n(x for x in a)\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:2(\n    GeneratorExpr:2(\n      NameExpr(x [l])\n      NameExpr(x* [l])\n      NameExpr(a [__main__.a]))))\n\n[case testGeneratorExpressionNestedIndex]\na = 0\n(x for x, (y, z) in a)\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(a [__main__.a])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:2(\n    GeneratorExpr:2(\n      NameExpr(x [l])\n      TupleExpr:2(\n        NameExpr(x* [l])\n        TupleExpr:2(\n          NameExpr(y* [l])\n          NameExpr(z* [l])))\n      NameExpr(a [__main__.a]))))\n\n[case testLambda]\nx = 0\nlambda: x\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:2(\n    LambdaExpr:2(\n      Block:2(\n        ReturnStmt:2(\n          NameExpr(x [__main__.x]))))))\n\n[case testLambdaWithArguments]\nlambda x, y: x + y\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    LambdaExpr:1(\n      Args(\n        Var(x)\n        Var(y))\n      Block:1(\n        ReturnStmt:1(\n          OpExpr:1(\n            +\n            NameExpr(x [l])\n            NameExpr(y [l])))))))\n\n[case testConditionalExpression]\nint if None else str\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    ConditionalExpr:1(\n      Condition(\n        NameExpr(None [builtins.None]))\n      NameExpr(int [builtins.int])\n      NameExpr(str [builtins.str]))))\n\n[case testDictWithKeywordArgs]\ndict(a=1, b=str())\n[builtins fixtures/dict.pyi]\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    DictExpr:1(\n      StrExpr(a)\n      IntExpr(1)\n      StrExpr(b)\n      CallExpr:1(\n        NameExpr(str [builtins.str])\n        Args()))))\n"
  },
  {
    "path": "test-data/unit/semanal-lambda.test",
    "content": "[case testLambdaInheritsCheckedContextFromFunc]\ndef g():\n    return lambda x: UNDEFINED in x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    g\n    Block:2(\n      ReturnStmt:2(\n        LambdaExpr:2(\n          Args(\n            Var(x))\n          Block:2(\n            ReturnStmt:2(\n              ComparisonExpr:2(\n                in\n                NameExpr(UNDEFINED)\n                NameExpr(x [l])))))))))\n\n[case testLambdaInheritsCheckedContextFromFuncForced]\n# flags: --check-untyped-defs\ndef g():\n    return lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromTypedFunc]\ndef g() -> None:\n    return lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromTypedFuncForced]\n# flags: --check-untyped-defs\ndef g() -> None:\n    return lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromModule]\ng = lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromModuleForce]\n# flags: --check-untyped-defs\ng = lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromModuleLambdaStack]\ng = lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromModuleLambdaStackForce]\n# flags: --check-untyped-defs\ng = lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromFuncLambdaStack]\ndef g():\n    return lambda: lambda: lambda x: UNDEFINED in x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    g\n    Block:2(\n      ReturnStmt:2(\n        LambdaExpr:2(\n          Block:2(\n            ReturnStmt:2(\n              LambdaExpr:2(\n                Block:2(\n                  ReturnStmt:2(\n                    LambdaExpr:2(\n                      Args(\n                        Var(x))\n                      Block:2(\n                        ReturnStmt:2(\n                          ComparisonExpr:2(\n                            in\n                            NameExpr(UNDEFINED)\n                            NameExpr(x [l])))))))))))))))\n\n[case testLambdaInheritsCheckedContextFromFuncLambdaStackForce]\n# flags: --check-untyped-defs\ndef g():\n    return lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromTypedFuncLambdaStack]\ndef g() -> None:\n    return lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromTypedFuncLambdaStackForce]\n# flags: --check-untyped-defs\ndef g() -> None:\n    return lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromClassLambdaStack]\nclass A:\n    g = lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n\n[case testLambdaInheritsCheckedContextFromClassLambdaStackForce]\n# flags: --check-untyped-defs\nclass A:\n    g = lambda: lambda: lambda x: UNDEFINED in x  # E: Name \"UNDEFINED\" is not defined\n"
  },
  {
    "path": "test-data/unit/semanal-literal.test",
    "content": "[case testLiteralSemanalBasicAssignment]\nfrom typing_extensions import Literal\nfoo: Literal[3]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing_extensions, [Literal])\n  AssignmentStmt:2(\n    NameExpr(foo [__main__.foo])\n    TempNode:2(\n      Any)\n    Literal[3]))\n\n[case testLiteralSemanalInFunction]\nfrom typing_extensions import Literal\ndef foo(a: Literal[1], b: Literal[\"  foo  \"]) -> Literal[True]: pass\n[builtins fixtures/bool.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing_extensions, [Literal])\n  FuncDef:2(\n    foo\n    Args(\n      Var(a)\n      Var(b))\n    def (a: Literal[1], b: Literal['  foo  ']) -> Literal[True]\n    Block:2(\n      PassStmt:2())))\n"
  },
  {
    "path": "test-data/unit/semanal-modules.test",
    "content": "-- NOTE: If a module has a name starting or ending with _, it is skipped in\n--       output.\n\n[case testImport]\nimport x\nx.y\n[file x.py]\ny = 1\n[out]\nMypyFile:1(\n  Import:1(x)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(x)\n      y [x.y])))\nMypyFile:1(\n  tmp/x.py\n  AssignmentStmt:1(\n    NameExpr(y [x.y])\n    IntExpr(1)\n    builtins.int))\n\n[case testImportedNameInType]\nimport m\nx = None # type: m.c\n[file m.py]\nclass c: pass\n[out]\nMypyFile:1(\n  Import:1(m)\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    m.c))\nMypyFile:1(\n  tmp/m.py\n  ClassDef:1(\n    c\n    PassStmt:1()))\n\n[case testImportFrom]\nfrom m import y\nx = y\n[file m.py]\ny = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [y])\n  AssignmentStmt:2(\n    NameExpr(x* [__main__.x])\n    NameExpr(y [m.y])))\nMypyFile:1(\n  tmp/m.py\n  AssignmentStmt:1(\n    NameExpr(y [m.y])\n    IntExpr(1)\n    builtins.int))\n\n[case testImportFromType]\nfrom m import c\nx = None # type: c\n[file m.py]\nclass c: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [c])\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    m.c))\nMypyFile:1(\n  tmp/m.py\n  ClassDef:1(\n    c\n    PassStmt:1()))\n\n[case testImportMultiple]\nimport _m, _n\n_m.x, _n.y\n[fixture _m.py]\nx = 1\n[fixture _n.py]\ny = 2\n[out]\nMypyFile:1(\n  Import:1(_m, _n)\n  ExpressionStmt:2(\n    TupleExpr:2(\n      MemberExpr:2(\n        NameExpr(_m)\n        x [_m.x])\n      MemberExpr:2(\n        NameExpr(_n)\n        y [_n.y]))))\n\n[case testImportAs]\nimport _m as n\nn.x\n[fixture _m.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(_m : n)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(n [_m])\n      x [_m.x])))\n\n[case testImportFromMultiple]\nfrom _m import x, y\nx, y\n[fixture _m.py]\nx = y = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(_m, [x, y])\n  ExpressionStmt:2(\n    TupleExpr:2(\n      NameExpr(x [_m.x])\n      NameExpr(y [_m.y]))))\n\n[case testImportFromAs]\nfrom _m import y as z\nz\n[fixture _m.py]\ny = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(_m, [y : z])\n  ExpressionStmt:2(\n    NameExpr(z [_m.y])))\n\n[case testAccessImportedName]\nfrom m import x\ny = x\n[file m.py]\nfrom _n import x\n[fixture _n.py]\nx = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [x])\n  AssignmentStmt:2(\n    NameExpr(y* [__main__.y])\n    NameExpr(x [_n.x])))\nMypyFile:1(\n  tmp/m.py\n  ImportFrom:1(_n, [x]))\n\n[case testAccessImportedName2]\nimport _m\ny = _m.x\n[fixture _m.py]\nfrom _n import x\n[fixture _n.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(_m)\n  AssignmentStmt:2(\n    NameExpr(y* [__main__.y])\n    MemberExpr:2(\n      NameExpr(_m)\n      x [_n.x])))\n\n[case testAccessingImportedNameInType]\nfrom _m import c\nx = None # type: c\n[fixture _m.py]\nfrom _n import c\n[fixture _n.py]\nclass c: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(_m, [c])\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    _n.c))\n\n[case testAccessingImportedNameInType2]\nimport _m\nx = None # type: _m.c\n[fixture _m.py]\nfrom _n import c\n[fixture _n.py]\nclass c: pass\n[out]\nMypyFile:1(\n  Import:1(_m)\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    _n.c))\n\n[case testAccessingImportedModule]\nfrom _m import _n\n_n.x\n[fixture _m.py]\nimport _n\n[fixture _n.py]\nx = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(_m, [_n])\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(_n)\n      x [_n.x])))\n\n[case testAccessingImportedModule2]\nimport _m\n_m._n.x\n[fixture _m.py]\nimport _n\n[fixture _n.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(_m)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      MemberExpr:2(\n        NameExpr(_m)\n        _n)\n      x [_n.x])))\n\n[case testAccessTypeViaDoubleIndirection]\nfrom _m import c\na = None # type: c\n[fixture _m.py]\nfrom _n import c\n[fixture _n.py]\nclass c: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(_m, [c])\n  AssignmentStmt:2(\n    NameExpr(a [__main__.a])\n    NameExpr(None [builtins.None])\n    _n.c))\n\n[case testAccessTypeViaDoubleIndirection2]\nimport _m\na = None # type: _m.c\n[fixture _m.py]\nfrom _n import c\n[fixture _n.py]\nclass c: pass\n[out]\nMypyFile:1(\n  Import:1(_m)\n  AssignmentStmt:2(\n    NameExpr(a [__main__.a])\n    NameExpr(None [builtins.None])\n    _n.c))\n\n[case testImportAsterisk]\nfrom _m import *\nx, y\n[fixture _m.py]\nx = y = 1\n[out]\nMypyFile:1(\n  ImportAll:1(_m)\n  ExpressionStmt:2(\n    TupleExpr:2(\n      NameExpr(x [_m.x])\n      NameExpr(y [_m.y]))))\n\n[case testImportAsteriskAndImportedNames]\nfrom _m import *\nn_.x, y\n[fixture _m.py]\nimport n_\nfrom n_ import y\n[fixture n_.py]\nx = y = 1\n[out]\nMypyFile:1(\n  ImportAll:1(_m)\n  ExpressionStmt:2(\n    TupleExpr:2(\n      MemberExpr:2(\n        NameExpr(n_)\n        x [n_.x])\n      NameExpr(y [n_.y]))))\n\n[case testImportAsteriskAndImportedNamesInTypes]\nfrom _m import *\nx = None # type: n_.c\ny = None # type: d\n[fixture _m.py]\nimport n_\nfrom n_ import d\n[fixture n_.py]\nclass c: pass\nclass d: pass\n[out]\nMypyFile:1(\n  ImportAll:1(_m)\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    n_.c)\n  AssignmentStmt:3(\n    NameExpr(y [__main__.y])\n    NameExpr(None [builtins.None])\n    n_.d))\n\n[case testModuleInSubdir]\nimport _m\n_m.x\n[fixture _m/__init__.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(_m)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(_m)\n      x [_m.x])))\n\n[case testNestedModules]\nimport m.n\nm.n.x, m.y\n[fixture m/__init__.py]\ny = 1\n[file m/n.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(m.n)\n  ExpressionStmt:2(\n    TupleExpr:2(\n      MemberExpr:2(\n        MemberExpr:2(\n          NameExpr(m)\n          n [m.n])\n        x [m.n.x])\n      MemberExpr:2(\n        NameExpr(m)\n        y [m.y]))))\nMypyFile:1(\n  tmp/m/n.py\n  AssignmentStmt:1(\n    NameExpr(x [m.n.x])\n    IntExpr(1)\n    builtins.int))\n\n[case testImportFromSubmodule]\nfrom m._n import x\nx\n[fixture m/__init__.py]\n[fixture m/_n.py]\nx = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(m._n, [x])\n  ExpressionStmt:2(\n    NameExpr(x [m._n.x])))\n\n[case testImportAllFromSubmodule]\nfrom m._n import *\nx, y\n[fixture m/__init__.py]\n[fixture m/_n.py]\nx = y = 1\n[out]\nMypyFile:1(\n  ImportAll:1(m._n)\n  ExpressionStmt:2(\n    TupleExpr:2(\n      NameExpr(x [m._n.x])\n      NameExpr(y [m._n.y]))))\n\n[case testSubmodulesAndTypes]\nimport m._n\nx = None # type: m._n.c\n[fixture m/__init__.py]\n[fixture m/_n.py]\nclass c: pass\n[out]\nMypyFile:1(\n  Import:1(m._n)\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    m._n.c))\n\n[case testSubmodulesAndTypes2]\nfrom m._n import c\nx = None # type: c\n[fixture m/__init__.py]\n[fixture m/_n.py]\nclass c: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(m._n, [c])\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    m._n.c))\n\n[case testFromPackageImportModule]\nfrom m import _n\n_n.x\n[fixture m/__init__.py]\n[fixture m/_n.py]\nx = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(m, [_n])\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(_n [m._n])\n      x [m._n.x])))\n\n[case testDeeplyNestedModule]\nimport m.n.k\nm.n.k.x\nm.n.b\nm.a\n[fixture m/__init__.py]\na = 1\n[fixture m/n/__init__.py]\nb = 1\n[file m/n/k.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(m.n.k)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      MemberExpr:2(\n        MemberExpr:2(\n          NameExpr(m)\n          n [m.n])\n        k [m.n.k])\n      x [m.n.k.x]))\n  ExpressionStmt:3(\n    MemberExpr:3(\n      MemberExpr:3(\n        NameExpr(m)\n        n [m.n])\n      b [m.n.b]))\n  ExpressionStmt:4(\n    MemberExpr:4(\n      NameExpr(m)\n      a [m.a])))\nMypyFile:1(\n  tmp/m/n/k.py\n  AssignmentStmt:1(\n    NameExpr(x [m.n.k.x])\n    IntExpr(1)\n    builtins.int))\n\n[case testImportInSubmodule]\nimport m._n\ny = m._n.x\n[fixture m/__init__.py]\n[fixture m/_n.py]\nfrom m._k import x\n[fixture m/_k.py]\nx = 1\n[out]\nMypyFile:1(\n  Import:1(m._n)\n  AssignmentStmt:2(\n    NameExpr(y* [__main__.y])\n    MemberExpr:2(\n      MemberExpr:2(\n        NameExpr(m)\n        _n [m._n])\n      x [m._k.x])))\n\n[case testBuiltinsUsingModule]\no = None # type: __builtins__.object\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(o [__main__.o])\n    NameExpr(None [builtins.None])\n    builtins.object))\n\n[case testImplicitAccessToBuiltins]\nobject\n[out]\nMypyFile:1(\n  ExpressionStmt:1(\n    NameExpr(object [builtins.object])))\n\n[case testAssignmentToModuleAttribute]\nimport _m\n_m.x = (\n  _m.x)\n[fixture _m.py]\nx = None\n[out]\nMypyFile:1(\n  Import:1(_m)\n  AssignmentStmt:2(\n    MemberExpr:2(\n      NameExpr(_m)\n      x [_m.x])\n    MemberExpr:3(\n      NameExpr(_m)\n      x [_m.x])))\n\n[case testAssignmentThatRefersToModule]\nimport _m\n_m.x[None] = None\n[fixture _m.py]\nx = None\n[out]\nMypyFile:1(\n  Import:1(_m)\n  AssignmentStmt:2(\n    IndexExpr:2(\n      MemberExpr:2(\n        NameExpr(_m)\n        x [_m.x])\n      NameExpr(None [builtins.None]))\n    NameExpr(None [builtins.None])))\n\n[case testImportInBlock]\nif 1:\n    import _x\n    _x.y\n[fixture _x.py]\ny = 1\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      IntExpr(1))\n    Then(\n      Import:2(_x)\n      ExpressionStmt:3(\n        MemberExpr:3(\n          NameExpr(_x)\n          y [_x.y])))))\n\n[case testImportInFunction]\ndef f() -> None:\n    import _x\n    _x.y\n[fixture _x.py]\ny = 1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def ()\n    Block:2(\n      Import:2(_x)\n      ExpressionStmt:3(\n        MemberExpr:3(\n          NameExpr(_x)\n          y [_x.y])))))\n\n[case testImportInClassBody]\nclass A:\n    from _x import y\n    z = y\n[fixture _x.py]\ny = 1\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    ImportFrom:2(_x, [y])\n    AssignmentStmt:3(\n      NameExpr(z* [m])\n      NameExpr(y [__main__.A.y]))))\n\n[case testImportInClassBody2]\nclass A:\n    import _x\n    z = _x.y\n[fixture _x.py]\ny = 1\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    Import:2(_x)\n    AssignmentStmt:3(\n      NameExpr(z* [m])\n      MemberExpr:3(\n        NameExpr(_x)\n        y [_x.y]))))\n\n[case testImportModuleTwice]\ndef f() -> None:\n    import x\n    import x\n    x.y\n[file x.py]\ny = 1\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def ()\n    Block:2(\n      Import:2(x)\n      Import:3(x)\n      ExpressionStmt:4(\n        MemberExpr:4(\n          NameExpr(x)\n          y [x.y])))))\nMypyFile:1(\n  tmp/x.py\n  AssignmentStmt:1(\n    NameExpr(y [x.y])\n    IntExpr(1)\n    builtins.int))\n\n[case testRelativeImport0]\nimport m.x\nm.x.z.y\n[fixture m/__init__.py]\n[file m/x.py]\nfrom . import z\n[file m/z.py]\ny = 1\n[out]\nMypyFile:1(\n  Import:1(m.x)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      MemberExpr:2(\n        MemberExpr:2(\n          NameExpr(m)\n          x [m.x])\n        z [m.z])\n      y [m.z.y])))\nMypyFile:1(\n  tmp/m/x.py\n  ImportFrom:1(., [z]))\nMypyFile:1(\n  tmp/m/z.py\n  AssignmentStmt:1(\n    NameExpr(y [m.z.y])\n    IntExpr(1)\n    builtins.int))\n\n[case testRelativeImport1]\nimport m.t.b as b\nb.x.y\nb.z.y\n[fixture m/__init__.py]\n[file m/x.py]\ny = 1\n[file m/z.py]\ny = 3\n[fixture m/t/__init__.py]\n[file m/t/b.py]\nfrom .. import x, z\n[out]\nMypyFile:1(\n  Import:1(m.t.b : b)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      MemberExpr:2(\n        NameExpr(b [m.t.b])\n        x [m.x])\n      y [m.x.y]))\n  ExpressionStmt:3(\n    MemberExpr:3(\n      MemberExpr:3(\n        NameExpr(b [m.t.b])\n        z [m.z])\n      y [m.z.y])))\nMypyFile:1(\n  tmp/m/t/b.py\n  ImportFrom:1(.., [x, z]))\nMypyFile:1(\n  tmp/m/x.py\n  AssignmentStmt:1(\n    NameExpr(y [m.x.y])\n    IntExpr(1)\n    builtins.int))\nMypyFile:1(\n  tmp/m/z.py\n  AssignmentStmt:1(\n    NameExpr(y [m.z.y])\n    IntExpr(3)\n    builtins.int))\n\n[case testRelativeImport2]\nimport m.t.b as b\nb.xy\nb.zy\n[fixture m/__init__.py]\n[file m/x.py]\ny = 1\n[file m/z.py]\ny = 3\n[fixture m/t/__init__.py]\n[file m/t/b.py]\nfrom ..x import y as xy\nfrom ..z import y as zy\n[out]\nMypyFile:1(\n  Import:1(m.t.b : b)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(b [m.t.b])\n      xy [m.x.y]))\n  ExpressionStmt:3(\n    MemberExpr:3(\n      NameExpr(b [m.t.b])\n      zy [m.z.y])))\nMypyFile:1(\n  tmp/m/t/b.py\n  ImportFrom:1(..x, [y : xy])\n  ImportFrom:2(..z, [y : zy]))\nMypyFile:1(\n  tmp/m/x.py\n  AssignmentStmt:1(\n    NameExpr(y [m.x.y])\n    IntExpr(1)\n    builtins.int))\nMypyFile:1(\n  tmp/m/z.py\n  AssignmentStmt:1(\n    NameExpr(y [m.z.y])\n    IntExpr(3)\n    builtins.int))\n\n[case testRelativeImport3]\nimport m.t\nm.zy\nm.xy\nm.t.y\n[fixture m/__init__.py]\nfrom .x import *\nfrom .z import *\n[file m/x.py]\nfrom .z import zy as xy\n[file m/z.py]\nzy = 3\n[fixture m/t/__init__.py]\nfrom .b import *\n[file m/t/b.py]\nfrom .. import xy as y\n[out]\nMypyFile:1(\n  Import:1(m.t)\n  ExpressionStmt:2(\n    MemberExpr:2(\n      NameExpr(m)\n      zy [m.z.zy]))\n  ExpressionStmt:3(\n    MemberExpr:3(\n      NameExpr(m)\n      xy [m.z.zy]))\n  ExpressionStmt:4(\n    MemberExpr:4(\n      MemberExpr:4(\n        NameExpr(m)\n        t [m.t])\n      y [m.z.zy])))\nMypyFile:1(\n  tmp/m/t/b.py\n  ImportFrom:1(.., [xy : y]))\nMypyFile:1(\n  tmp/m/x.py\n  ImportFrom:1(.z, [zy : xy]))\nMypyFile:1(\n  tmp/m/z.py\n  AssignmentStmt:1(\n    NameExpr(zy [m.z.zy])\n    IntExpr(3)\n    builtins.int))\n\n[case testRelativeImportFromSameModule]\nimport m.x\n[fixture m/__init__.py]\n[file m/x.py]\nfrom .x import nonexistent\n[out]\ntmp/m/x.py:1: error: Module \"m.x\" has no attribute \"nonexistent\"\n\n[case testImportFromSameModule]\nimport m.x\n[fixture m/__init__.py]\n[file m/x.py]\nfrom m.x import nonexistent\n[out]\ntmp/m/x.py:1: error: Module \"m.x\" has no attribute \"nonexistent\"\n\n[case testImportMisspellingSingleCandidate]\nimport f\n[fixture m/__init__.py]\n[file m/x.py]\ndef some_function():\n    pass\n[file f.py]\nfrom m.x import somefunction\n[out]\ntmp/f.py:1: error: Module \"m.x\" has no attribute \"somefunction\"; maybe \"some_function\"?\n\n[case testImportMisspellingMultipleCandidates]\nimport f\n[fixture m/__init__.py]\n[file m/x.py]\ndef some_function():\n    pass\ndef somef_unction():\n    pass\n[file f.py]\nfrom m.x import somefunction\n[out]\ntmp/f.py:1: error: Module \"m.x\" has no attribute \"somefunction\"; maybe \"some_function\" or \"somef_unction\"?\n\n[case testImportMisspellingMultipleCandidatesTruncated]\nimport f\n[fixture m/__init__.py]\n[file m/x.py]\ndef some_function():\n    pass\ndef somef_unction():\n    pass\ndef somefu_nction():\n    pass\ndef somefun_ction():\n    pass\n[file f.py]\nfrom m.x import somefunction\n[out]\ntmp/f.py:1: error: Module \"m.x\" has no attribute \"somefunction\"; maybe \"some_function\", \"somef_unction\", or \"somefu_nction\"?\n\n[case testFromImportAsInStub]\nfrom m import *\nx\ny  # E: Name \"y\" is not defined\n[file m.pyi]\nfrom m2 import x as x\nfrom m2 import y\n[file m2.py]\nx = 1\ny = 2\n[out]\n\n[case testFromImportAsInNonStub]\nfrom m_ import *\nx\ny\n[fixture m_.py]\nfrom m2_ import x as x\nfrom m2_ import y\n[fixture m2_.py]\nx = 1\ny = 2\n[out]\nMypyFile:1(\n  ImportAll:1(m_)\n  ExpressionStmt:2(\n    NameExpr(x [m2_.x]))\n  ExpressionStmt:3(\n    NameExpr(y [m2_.y])))\n\n[case testImportAsInStub]\nfrom m import *\nm2\nm3  # E: Name \"m3\" is not defined\n[file m.pyi]\nimport m2 as m2\nimport m3\n[file m2.py]\n[file m3.py]\n[out]\n\n[case testImportAsInNonStub]\nfrom m_ import *\nm2_\nm3_\n[fixture m_.py]\nimport m2_ as m2_\nimport m3_\n[fixture m2_.py]\n[fixture m3_.py]\n[out]\nMypyFile:1(\n  ImportAll:1(m_)\n  ExpressionStmt:2(\n    NameExpr(m2_))\n  ExpressionStmt:3(\n    NameExpr(m3_)))\n\n[case testErrorsInMultipleModules]\nimport m\nx\n[file m.py]\ny\n[out]\ntmp/m.py:1: error: Name \"y\" is not defined\nmain:2: error: Name \"x\" is not defined\n\n[case testImportTwice]\nimport typing\nfrom x import a, a # ok (we could give a warning, but this is valid)\ndef f() -> None:\n    from x import a\n    from x import a # ok\nimport x\nimport x # ok, since we may import multiple submodules of a package\n[file x.py]\na = 1\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ImportFrom:2(x, [a, a])\n  FuncDef:3(\n    f\n    def ()\n    Block:4(\n      ImportFrom:4(x, [a])\n      ImportFrom:5(x, [a])))\n  Import:6(x)\n  Import:7(x))\nMypyFile:1(\n  tmp/x.py\n  AssignmentStmt:1(\n    NameExpr(a [x.a])\n    IntExpr(1)\n    builtins.int))\n"
  },
  {
    "path": "test-data/unit/semanal-namedtuple.test",
    "content": "-- Semantic analysis of named tuples\n\n[case testSimpleNamedtuple]\nfrom collections import namedtuple\nN = namedtuple('N', ['a'])\ndef f() -> N: pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(collections, [namedtuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[Any]))\n  FuncDef:3(\n    f\n    def () -> Tuple[Any, fallback=__main__.N]\n    Block:3(\n      PassStmt:3())))\n\n[case testTwoItemNamedtuple]\nfrom collections import namedtuple\nN = namedtuple('N', ['a', 'xyz'])\ndef f() -> N: pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(collections, [namedtuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[Any, Any]))\n  FuncDef:3(\n    f\n    def () -> Tuple[Any, Any, fallback=__main__.N]\n    Block:3(\n      PassStmt:3())))\n\n[case testTwoItemNamedtupleWithTupleFieldNames]\nfrom collections import namedtuple\nN = namedtuple('N', ('a', 'xyz'))\ndef f() -> N: pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(collections, [namedtuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[Any, Any]))\n  FuncDef:3(\n    f\n    def () -> Tuple[Any, Any, fallback=__main__.N]\n    Block:3(\n      PassStmt:3())))\n\n[case testTwoItemNamedtupleWithShorthandSyntax]\nfrom collections import namedtuple\nN = namedtuple('N', ' a  xyz ')\ndef f() -> N: pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(collections, [namedtuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[Any, Any]))\n  FuncDef:3(\n    f\n    def () -> Tuple[Any, Any, fallback=__main__.N]\n    Block:3(\n      PassStmt:3())))\n\n[case testNamedTupleWithItemTypes]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('a', int),\n                     ('b', str)])\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [NamedTuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[builtins.int, builtins.str])))\n\n[case testNamedTupleWithTupleFieldNamesWithItemTypes]\nfrom typing import NamedTuple\nN = NamedTuple('N', (('a', int),\n                     ('b', str)))\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [NamedTuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[builtins.int, builtins.str])))\n\n[case testNamedTupleBaseClass]\nfrom collections import namedtuple\nN = namedtuple('N', ['x'])\nclass A(N): pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(collections, [namedtuple])\n  AssignmentStmt:2(\n    NameExpr(N* [__main__.N])\n    NamedTupleExpr:2(N, Tuple[Any]))\n  ClassDef:3(\n    A\n    TupleType(\n      Tuple[Any, fallback=__main__.N])\n    BaseType(\n      __main__.N)\n    PassStmt:3()))\n\n[case testNamedTupleBaseClass2]\nfrom collections import namedtuple\nclass A(namedtuple('N', ['x'])): pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(collections, [namedtuple])\n  ClassDef:2(\n    A\n    TupleType(\n      Tuple[Any, fallback=__main__.N@2])\n    BaseType(\n      __main__.N@2)\n    PassStmt:2()))\n\n[case testNamedTupleBaseClassWithItemTypes]\nfrom typing import NamedTuple\nclass A(NamedTuple('N', [('x', int)])): pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [NamedTuple])\n  ClassDef:2(\n    A\n    TupleType(\n      Tuple[builtins.int, fallback=__main__.N@2])\n    BaseType(\n      __main__.N@2)\n    PassStmt:2()))\n\n-- Errors\n\n[case testNamedTupleWithTooFewArguments]\nfrom collections import namedtuple\nN = namedtuple('N') # E: Too few arguments for \"namedtuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleWithInvalidName]\nfrom collections import namedtuple\nN = namedtuple(1, ['x']) # E: \"namedtuple()\" expects a string literal as the first argument\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleWithInvalidItems]\nfrom collections import namedtuple\nN = namedtuple('N', 1) # E: List or tuple literal expected as the second argument to \"namedtuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleWithInvalidItems2]\nfrom collections import namedtuple\nN = namedtuple('N', ['x', 1]) # E: String literal expected as \"namedtuple()\" item\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleWithUnderscoreItemName]\nfrom collections import namedtuple\nN = namedtuple('N', ['_fallback']) # E: \"namedtuple()\" field name \"_fallback\" starts with an underscore\n[builtins fixtures/tuple.pyi]\n\n-- NOTE: The following code works at runtime but is not yet supported by mypy.\n--       Keyword arguments may potentially be supported in the future.\n[case testNamedTupleWithNonpositionalArgs]\nfrom collections import namedtuple\nN = namedtuple(typename='N', field_names=['x']) # E: Unexpected arguments to \"namedtuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingNamedTupleWithTooFewArguments]\nfrom typing import NamedTuple\nN = NamedTuple('N') # E: Too few arguments for \"NamedTuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingNamedTupleWithManyArguments]\nfrom typing import NamedTuple\nN = NamedTuple('N', [], []) # E: Too many arguments for \"NamedTuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingNamedTupleWithInvalidName]\nfrom typing import NamedTuple\nN = NamedTuple(1, ['x']) # E: \"NamedTuple()\" expects a string literal as the first argument\n[builtins fixtures/tuple.pyi]\n\n[case testTypingNamedTupleWithInvalidItems]\nfrom typing import NamedTuple\nN = NamedTuple('N', 1) # E: List or tuple literal expected as the second argument to \"NamedTuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypingNamedTupleWithUnderscoreItemName]\nfrom typing import NamedTuple\nN = NamedTuple('N', [('_fallback', int)]) # E: \"NamedTuple()\" field name \"_fallback\" starts with an underscore\n[builtins fixtures/tuple.pyi]\n\n[case testTypingNamedTupleWithUnexpectedNames]\nfrom typing import NamedTuple\nN = NamedTuple(name='N', fields=[]) # E: Unexpected arguments to \"NamedTuple()\"\n[builtins fixtures/tuple.pyi]\n\n-- NOTE: The following code works at runtime but is not yet supported by mypy.\n--       Keyword arguments may potentially be supported in the future.\n[case testNamedTupleWithNonpositionalArgs2]\nfrom collections import namedtuple\nN = namedtuple(typename='N', field_names=['x']) # E: Unexpected arguments to \"namedtuple()\"\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidNamedTupleBaseClass]\nfrom typing import NamedTuple\nclass A(NamedTuple('N', [1])): pass # E: Tuple expected as \"NamedTuple()\" field\nclass B(A): pass\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidNamedTupleBaseClass2]\n\nclass A(NamedTuple('N', [1])): pass\nclass B(A): pass\n[out]\nmain:2: error: Unsupported dynamic base class \"NamedTuple\"\nmain:2: error: Name \"NamedTuple\" is not defined\n\n[case testNamedTupleWithDecorator]\nfrom typing import final, NamedTuple\n\n@final\nclass A(NamedTuple(\"N\", [(\"x\", int)])):\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [final, NamedTuple])\n  ClassDef:4(\n    A\n    TupleType(\n      Tuple[builtins.int, fallback=__main__.N@4])\n    Decorators(\n      NameExpr(final [typing.final]))\n    BaseType(\n      __main__.N@4)\n    PassStmt:5()))\n"
  },
  {
    "path": "test-data/unit/semanal-python310.test",
    "content": "-- Python 3.10 semantic analysis test cases.\n\n[case testCapturePattern]\nx = 1\nmatch x:\n  case a:\n    a\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      AsPattern:3(\n        NameExpr(a* [__main__.a])))\n    Body(\n      ExpressionStmt:4(\n        NameExpr(a [__main__.a])))))\n\n[case testCapturePatternOutliving]\nx = 1\nmatch x:\n    case a:\n      pass\na\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      AsPattern:3(\n        NameExpr(a* [__main__.a])))\n    Body(\n      PassStmt:4()))\n  ExpressionStmt:5(\n    NameExpr(a [__main__.a])))\n\n[case testNestedCapturePatterns]\nx = 1\nmatch x:\n    case ([a], {'k': b}):\n        a\n        b\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      SequencePattern:3(\n        SequencePattern:3(\n          AsPattern:3(\n            NameExpr(a* [__main__.a])))\n        MappingPattern:3(\n          Key(\n            StrExpr(k))\n          Value(\n            AsPattern:3(\n              NameExpr(b* [__main__.b]))))))\n    Body(\n      ExpressionStmt:4(\n        NameExpr(a [__main__.a]))\n      ExpressionStmt:5(\n        NameExpr(b [__main__.b])))))\n\n[case testMappingPatternRest]\nx = 1\nmatch x:\n    case {**r}:\n        r\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      MappingPattern:3(\n        Rest(\n          NameExpr(r* [__main__.r]))))\n    Body(\n      ExpressionStmt:4(\n        NameExpr(r [__main__.r])))))\n\n\n[case testAsPattern]\nx = 1\nmatch x:\n    case 1 as a:\n        a\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      AsPattern:3(\n        ValuePattern:3(\n          IntExpr(1))\n        NameExpr(a* [__main__.a])))\n    Body(\n      ExpressionStmt:4(\n        NameExpr(a [__main__.a])))))\n\n[case testGuard]\nx = 1\na = 1\nmatch x:\n    case 1 if a:\n        pass\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  AssignmentStmt:2(\n    NameExpr(a [__main__.a])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:3(\n    NameExpr(x [__main__.x])\n    Pattern(\n      ValuePattern:4(\n        IntExpr(1)))\n    Guard(\n      NameExpr(a [__main__.a]))\n    Body(\n      PassStmt:5())))\n\n[case testCapturePatternInGuard]\nx = 1\nmatch x:\n  case a if a:\n    pass\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      AsPattern:3(\n        NameExpr(a* [__main__.a])))\n    Guard(\n      NameExpr(a [__main__.a]))\n    Body(\n      PassStmt:4())))\n\n[case testAsPatternInGuard]\nx = 1\nmatch x:\n    case 1 as a if a:\n        pass\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:2(\n    NameExpr(x [__main__.x])\n    Pattern(\n      AsPattern:3(\n        ValuePattern:3(\n          IntExpr(1))\n        NameExpr(a* [__main__.a])))\n    Guard(\n      NameExpr(a [__main__.a]))\n    Body(\n      PassStmt:4())))\n\n[case testValuePattern]\nimport _a\n\nx = 1\nmatch x:\n    case _a.b:\n        pass\n[fixture _a.py]\nb = 1\n[out]\nMypyFile:1(\n  Import:1(_a)\n  AssignmentStmt:3(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  MatchStmt:4(\n    NameExpr(x [__main__.x])\n    Pattern(\n      ValuePattern:5(\n        MemberExpr:5(\n          NameExpr(_a)\n          b [_a.b])))\n    Body(\n      PassStmt:6())))\n"
  },
  {
    "path": "test-data/unit/semanal-statements.test",
    "content": "[case testReturn]\ndef f(x): return x\ndef g(): return\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    Block:1(\n      ReturnStmt:1(\n        NameExpr(x [l]))))\n  FuncDef:2(\n    g\n    Block:2(\n      ReturnStmt:2())))\n\n[case testRaise]\nraise object()\n[out]\nMypyFile:1(\n  RaiseStmt:1(\n    CallExpr:1(\n      NameExpr(object [builtins.object])\n      Args())))\n\n[case testYield]\ndef f(): yield f\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Generator\n    Block:1(\n      ExpressionStmt:1(\n        YieldExpr:1(\n          NameExpr(f [__main__.f]))))))\n\n[case testAssert]\nassert object\n[out]\nMypyFile:1(\n  AssertStmt:1(\n    NameExpr(object [builtins.object])))\n\n[case testOperatorAssignment]\nx = y = 1\nx += y\ny |= x\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  OperatorAssignmentStmt:2(\n    +\n    NameExpr(x [__main__.x])\n    NameExpr(y [__main__.y]))\n  OperatorAssignmentStmt:3(\n    |\n    NameExpr(y [__main__.y])\n    NameExpr(x [__main__.x])))\n\n[case testWhile]\nx = y = 1\nwhile x:\n  y\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  WhileStmt:2(\n    NameExpr(x [__main__.x])\n    Block:3(\n      ExpressionStmt:3(\n        NameExpr(y [__main__.y])))))\n\n[case testFor]\nfor x in object:\n  x\n[out]\nMypyFile:1(\n  ForStmt:1(\n    NameExpr(x* [__main__.x])\n    NameExpr(object [builtins.object])\n    Block:2(\n      ExpressionStmt:2(\n        NameExpr(x [__main__.x])))))\n\n[case testForInFunction]\ndef f():\n  for x in f:\n    x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ForStmt:2(\n        NameExpr(x* [l])\n        NameExpr(f [__main__.f])\n        Block:3(\n          ExpressionStmt:3(\n            NameExpr(x [l])))))))\n\n[case testMultipleForIndexVars]\nfor x, y in []:\n  x, y\n[out]\nMypyFile:1(\n  ForStmt:1(\n    TupleExpr:1(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    ListExpr:1()\n    Block:2(\n      ExpressionStmt:2(\n        TupleExpr:2(\n          NameExpr(x [__main__.x])\n          NameExpr(y [__main__.y]))))))\n\n[case testForIndexVarScope]\nfor x in []:\n  pass\nx\n[out]\nMypyFile:1(\n  ForStmt:1(\n    NameExpr(x* [__main__.x])\n    ListExpr:1()\n    Block:2(\n      PassStmt:2()))\n  ExpressionStmt:3(\n    NameExpr(x [__main__.x])))\n\n[case testForIndexVarScope2]\ndef f():\n  for x in []:\n    pass\n  x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      ForStmt:2(\n        NameExpr(x* [l])\n        ListExpr:2()\n        Block:3(\n          PassStmt:3()))\n      ExpressionStmt:4(\n        NameExpr(x [l])))))\n\n[case testReusingForLoopIndexVariable]\n# flags: --allow-redefinition\nfor x in None:\n    pass\nfor x in None:\n    pass\n[out]\nMypyFile:1(\n  ForStmt:2(\n    NameExpr(x'* [__main__.x'])\n    NameExpr(None [builtins.None])\n    Block:3(\n      PassStmt:3()))\n  ForStmt:4(\n    NameExpr(x* [__main__.x])\n    NameExpr(None [builtins.None])\n    Block:5(\n      PassStmt:5())))\n\n[case testReusingForLoopIndexVariable2]\n# flags: --allow-redefinition\ndef f():\n    for x in None:\n        pass\n    for x in None:\n        pass\n[out]\nMypyFile:1(\n  FuncDef:2(\n    f\n    Block:3(\n      ForStmt:3(\n        NameExpr(x* [l])\n        NameExpr(None [builtins.None])\n        Block:4(\n          PassStmt:4()))\n      ForStmt:5(\n        NameExpr(x'* [l])\n        NameExpr(None [builtins.None])\n        Block:6(\n          PassStmt:6())))))\n\n[case testLoopWithElse]\nfor x in []:\n  pass\nelse:\n  x\nwhile 1:\n  pass\nelse:\n  x\n[out]\nMypyFile:1(\n  ForStmt:1(\n    NameExpr(x* [__main__.x])\n    ListExpr:1()\n    Block:2(\n      PassStmt:2())\n    Else(\n      ExpressionStmt:4(\n        NameExpr(x [__main__.x]))))\n  WhileStmt:5(\n    IntExpr(1)\n    Block:6(\n      PassStmt:6())\n    Else(\n      ExpressionStmt:8(\n        NameExpr(x [__main__.x])))))\n\n[case testBreak]\nwhile 1:\n  break\nfor x in []:\n  break\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(1)\n    Block:2(\n      BreakStmt:2()))\n  ForStmt:3(\n    NameExpr(x* [__main__.x])\n    ListExpr:3()\n    Block:4(\n      BreakStmt:4())))\n\n[case testContinue]\nwhile 1:\n  continue\nfor x in []:\n  continue\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    IntExpr(1)\n    Block:2(\n      ContinueStmt:2()))\n  ForStmt:3(\n    NameExpr(x* [__main__.x])\n    ListExpr:3()\n    Block:4(\n      ContinueStmt:4())))\n\n[case testIf]\nx = 1\nif x:\n  x\nelif x:\n  x\nelif x:\n  x\nelse:\n  x\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  IfStmt:2(\n    If(\n      NameExpr(x [__main__.x]))\n    Then(\n      ExpressionStmt:3(\n        NameExpr(x [__main__.x])))\n    Else(\n      IfStmt:4(\n        If(\n          NameExpr(x [__main__.x]))\n        Then(\n          ExpressionStmt:5(\n            NameExpr(x [__main__.x])))\n        Else(\n          IfStmt:6(\n            If(\n              NameExpr(x [__main__.x]))\n            Then(\n              ExpressionStmt:7(\n                NameExpr(x [__main__.x])))\n            Else(\n              ExpressionStmt:9(\n                NameExpr(x [__main__.x])))))))))\n\n[case testSimpleIf]\nif object:\n  object\n[out]\nMypyFile:1(\n  IfStmt:1(\n    If(\n      NameExpr(object [builtins.object]))\n    Then(\n      ExpressionStmt:2(\n        NameExpr(object [builtins.object])))))\n\n[case testLvalues]\nx = y = 1\nxx = 1\nx.m = 1\nx[y] = 1\nx2, y2 = 1\n[x3, y3] = 1\n(x4, y4) = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  AssignmentStmt:2(\n    NameExpr(xx [__main__.xx])\n    IntExpr(1)\n    builtins.int)\n  AssignmentStmt:3(\n    MemberExpr:3(\n      NameExpr(x [__main__.x])\n      m)\n    IntExpr(1))\n  AssignmentStmt:4(\n    IndexExpr:4(\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y]))\n    IntExpr(1))\n  AssignmentStmt:5(\n    TupleExpr:5(\n      NameExpr(x2* [__main__.x2])\n      NameExpr(y2* [__main__.y2]))\n    IntExpr(1))\n  AssignmentStmt:6(\n    TupleExpr:6(\n      NameExpr(x3* [__main__.x3])\n      NameExpr(y3* [__main__.y3]))\n    IntExpr(1))\n  AssignmentStmt:7(\n    TupleExpr:7(\n      NameExpr(x4* [__main__.x4])\n      NameExpr(y4* [__main__.y4]))\n    IntExpr(1)))\n\n[case testStarLvalues]\n# flags: --allow-redefinition\n*x, y = 1\n*x, (y, *z) = 1\n*(x, q), r = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:2(\n    TupleExpr:2(\n      StarExpr:2(\n        NameExpr(x'* [__main__.x']))\n      NameExpr(y'* [__main__.y']))\n    IntExpr(1))\n  AssignmentStmt:3(\n    TupleExpr:3(\n      StarExpr:3(\n        NameExpr(x''* [__main__.x'']))\n      TupleExpr:3(\n        NameExpr(y* [__main__.y])\n        StarExpr:3(\n          NameExpr(z* [__main__.z]))))\n    IntExpr(1))\n  AssignmentStmt:4(\n    TupleExpr:4(\n      StarExpr:4(\n        TupleExpr:4(\n          NameExpr(x* [__main__.x])\n          NameExpr(q* [__main__.q])))\n      NameExpr(r* [__main__.r]))\n    IntExpr(1)))\n\n[case testMultipleDefinition]\n# flags: --allow-redefinition\nx, y = 1\nx, y = 2\n[out]\nMypyFile:1(\n  AssignmentStmt:2(\n    TupleExpr:2(\n      NameExpr(x'* [__main__.x'])\n      NameExpr(y'* [__main__.y']))\n    IntExpr(1))\n  AssignmentStmt:3(\n    TupleExpr:3(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(2)))\n\n[case testComplexDefinitions]\n(x) = 1\n([y]) = 2\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  AssignmentStmt:2(\n    TupleExpr:2(\n      NameExpr(y* [__main__.y]))\n    IntExpr(2)))\n\n[case testLocalComplexDefinition]\ndef f():\n  (x) = 1\n  x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(x* [l])\n        IntExpr(1))\n      ExpressionStmt:3(\n        NameExpr(x [l])))))\n\n[case testMultipleDefOnlySomeNew]\nx = 1\ny, x = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  AssignmentStmt:2(\n    TupleExpr:2(\n      NameExpr(y* [__main__.y])\n      NameExpr(x [__main__.x]))\n    IntExpr(1)))\n\n[case testMultipleDefOnlySomeNewNestedTuples]\nx = 1\ny, (x, z) = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  AssignmentStmt:2(\n    TupleExpr:2(\n      NameExpr(y* [__main__.y])\n      TupleExpr:2(\n        NameExpr(x [__main__.x])\n        NameExpr(z* [__main__.z])))\n    IntExpr(1)))\n\n[case testMultipleDefOnlySomeNewNestedLists]\nx = 1\nif x:\n    y, [x, z] = 1\n    [p, [x, r]] = 1\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  IfStmt:2(\n    If(\n      NameExpr(x [__main__.x]))\n    Then(\n      AssignmentStmt:3(\n        TupleExpr:3(\n          NameExpr(y* [__main__.y])\n          TupleExpr:3(\n            NameExpr(x [__main__.x])\n            NameExpr(z* [__main__.z])))\n        IntExpr(1))\n      AssignmentStmt:4(\n        TupleExpr:4(\n          NameExpr(p* [__main__.p])\n          TupleExpr:4(\n            NameExpr(x [__main__.x])\n            NameExpr(r* [__main__.r])))\n        IntExpr(1)))))\n\n[case testIndexedDel]\nx = y = 1\ndel x[y]\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    Lvalues(\n      NameExpr(x* [__main__.x])\n      NameExpr(y* [__main__.y]))\n    IntExpr(1))\n  DelStmt:2(\n    IndexExpr:2(\n      NameExpr(x [__main__.x])\n      NameExpr(y [__main__.y]))))\n\n[case testDelGlobalName]\nx = 1\ndel x\n[out]\nMypyFile:1(\n  AssignmentStmt:1(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    builtins.int)\n  DelStmt:2(\n    NameExpr(x [__main__.x])))\n\n[case testDelLocalName]\ndef f(x):\n    del x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x))\n    Block:2(\n      DelStmt:2(\n        NameExpr(x [l])))))\n\n[case testDelMultipleThings]\ndef f(x, y):\n    del x, y[0]\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(x)\n      Var(y))\n    Block:2(\n      DelStmt:2(\n        TupleExpr:2(\n          NameExpr(x [l])\n          IndexExpr:2(\n            NameExpr(y [l])\n            IntExpr(0)))))))\n\n[case testDelMultipleThingsInvalid]\ndef f(x, y) -> None:\n    del x, y + 1\n[out]\nmain:2: error: cannot delete operator\n[out version>=3.10]\nmain:2: error: cannot delete expression\n\n[case testTry]\nclass c: pass\ntry:\n  c\nexcept object:\n  c\nexcept c as e:\n  e\nexcept:\n  c\nfinally:\n  c\n[out]\nMypyFile:1(\n  ClassDef:1(\n    c\n    PassStmt:1())\n  TryStmt:2(\n    Block:3(\n      ExpressionStmt:3(\n        NameExpr(c [__main__.c])))\n    NameExpr(object [builtins.object])\n    Block:5(\n      ExpressionStmt:5(\n        NameExpr(c [__main__.c])))\n    NameExpr(c [__main__.c])\n    NameExpr(e* [__main__.e])\n    Block:7(\n      ExpressionStmt:7(\n        NameExpr(e [__main__.e])))\n    Block:9(\n      ExpressionStmt:9(\n        NameExpr(c [__main__.c])))\n    Finally(\n      ExpressionStmt:11(\n        NameExpr(c [__main__.c])))))\n\n[case testTryElse]\ntry:\n  pass\nexcept:\n  pass\nelse:\n  object\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    Block:4(\n      PassStmt:4())\n    Else(\n      ExpressionStmt:6(\n        NameExpr(object [builtins.object])))))\n\n[case testTryWithOnlyFinally]\ntry:\n  pass\nfinally:\n  pass\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    Finally(\n      PassStmt:4())))\n\n[case testExceptWithMultipleTypes]\nclass c: pass\ntry:\n  pass\nexcept (c, object) as e:\n  e\n[out]\nMypyFile:1(\n  ClassDef:1(\n    c\n    PassStmt:1())\n  TryStmt:2(\n    Block:3(\n      PassStmt:3())\n    TupleExpr:4(\n      NameExpr(c [__main__.c])\n      NameExpr(object [builtins.object]))\n    NameExpr(e* [__main__.e])\n    Block:5(\n      ExpressionStmt:5(\n        NameExpr(e [__main__.e])))))\n\n[case testRaiseWithoutExpr]\nraise\n[out]\nMypyFile:1(\n  RaiseStmt:1())\n\n[case testWith]\nwith object:\n  object\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      NameExpr(object [builtins.object]))\n    Block:2(\n      ExpressionStmt:2(\n        NameExpr(object [builtins.object])))))\n\n[case testWithAndVariable]\nwith object as x:\n  x\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      NameExpr(object [builtins.object]))\n    Target(\n      NameExpr(x* [__main__.x]))\n    Block:2(\n      ExpressionStmt:2(\n        NameExpr(x [__main__.x])))))\n\n[case testWithInFunction]\ndef f():\n  with f as x:\n    x\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Block:2(\n      WithStmt:2(\n        Expr(\n          NameExpr(f [__main__.f]))\n        Target(\n          NameExpr(x* [l]))\n        Block:3(\n          ExpressionStmt:3(\n            NameExpr(x [l])))))))\n\n[case testComplexWith]\nwith object, object:\n  pass\nwith object as a, object as b:\n  pass\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      NameExpr(object [builtins.object]))\n    Expr(\n      NameExpr(object [builtins.object]))\n    Block:2(\n      PassStmt:2()))\n  WithStmt:3(\n    Expr(\n      NameExpr(object [builtins.object]))\n    Target(\n      NameExpr(a* [__main__.a]))\n    Expr(\n      NameExpr(object [builtins.object]))\n    Target(\n      NameExpr(b* [__main__.b]))\n    Block:4(\n      PassStmt:4())))\n\n[case testVariableInBlock]\nwhile object:\n  x = None\n  if x:\n    x = x\n[out]\nMypyFile:1(\n  WhileStmt:1(\n    NameExpr(object [builtins.object])\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(x* [__main__.x])\n        NameExpr(None [builtins.None]))\n      IfStmt:3(\n        If(\n          NameExpr(x [__main__.x]))\n        Then(\n          AssignmentStmt:4(\n            NameExpr(x [__main__.x])\n            NameExpr(x [__main__.x])))))))\n\n[case testVariableInExceptHandler]\ntry:\n  pass\nexcept object as o:\n  x = None\n  o = x\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    NameExpr(object [builtins.object])\n    NameExpr(o* [__main__.o])\n    Block:4(\n      AssignmentStmt:4(\n        NameExpr(x* [__main__.x])\n        NameExpr(None [builtins.None]))\n      AssignmentStmt:5(\n        NameExpr(o [__main__.o])\n        NameExpr(x [__main__.x])))))\n\n[case testCallInExceptHandler]\ntry:\n  pass\nexcept object as o:\n  o = object()\n[out]\nMypyFile:1(\n  TryStmt:1(\n    Block:2(\n      PassStmt:2())\n    NameExpr(object [builtins.object])\n    NameExpr(o* [__main__.o])\n    Block:4(\n      AssignmentStmt:4(\n        NameExpr(o [__main__.o])\n        CallExpr:4(\n          NameExpr(object [builtins.object])\n          Args())))))\n\n[case testTryExceptWithMultipleHandlers]\nclass Err(BaseException): pass\ntry:\n    pass\nexcept BaseException as e:\n    pass\nexcept Err as f:\n    f = BaseException() # Fail\n    f = Err()\n[builtins fixtures/exception.pyi]\n[out]\nMypyFile:1(\n  ClassDef:1(\n    Err\n    BaseType(\n      builtins.BaseException)\n    PassStmt:1())\n  TryStmt:2(\n    Block:3(\n      PassStmt:3())\n    NameExpr(BaseException [builtins.BaseException])\n    NameExpr(e* [__main__.e])\n    Block:5(\n      PassStmt:5())\n    NameExpr(Err [__main__.Err])\n    NameExpr(f* [__main__.f])\n    Block:7(\n      AssignmentStmt:7(\n        NameExpr(f [__main__.f])\n        CallExpr:7(\n          NameExpr(BaseException [builtins.BaseException])\n          Args()))\n      AssignmentStmt:8(\n        NameExpr(f [__main__.f])\n        CallExpr:8(\n          NameExpr(Err [__main__.Err])\n          Args())))))\n[case testMultipleAssignmentWithPartialNewDef]\n# flags: --allow-redefinition\no = None\nx, o = o, o\n[out]\nMypyFile:1(\n  AssignmentStmt:2(\n    NameExpr(o'* [__main__.o'])\n    NameExpr(None [builtins.None]))\n  AssignmentStmt:3(\n    TupleExpr:3(\n      NameExpr(x* [__main__.x])\n      NameExpr(o* [__main__.o]))\n    TupleExpr:3(\n      NameExpr(o' [__main__.o'])\n      NameExpr(o' [__main__.o']))))\n\n[case testFunctionDecorator]\ndef decorate(f): pass\n@decorate\ndef g():\n    g()\n[out]\nMypyFile:1(\n  FuncDef:1(\n    decorate\n    Args(\n      Var(f))\n    Block:1(\n      PassStmt:1()))\n  Decorator:2(\n    Var(g)\n    NameExpr(decorate [__main__.decorate])\n    FuncDef:3(\n      g\n      Block:4(\n        ExpressionStmt:4(\n          CallExpr:4(\n            NameExpr(g [__main__.g])\n            Args()))))))\n\n[case testTryWithinFunction]\ndef f() -> None:\n    try:\n        pass\n    except object as o:\n        pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def ()\n    Block:2(\n      TryStmt:2(\n        Block:3(\n          PassStmt:3())\n        NameExpr(object [builtins.object])\n        NameExpr(o* [l])\n        Block:5(\n          PassStmt:5())))))\n\n[case testReuseExceptionVariable]\ndef f() -> None:\n    try:\n        pass\n    except object as o:\n        pass\n    except object as o:\n        pass\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    def ()\n    Block:2(\n      TryStmt:2(\n        Block:3(\n          PassStmt:3())\n        NameExpr(object [builtins.object])\n        NameExpr(o* [l])\n        Block:5(\n          PassStmt:5())\n        NameExpr(object [builtins.object])\n        NameExpr(o [l])\n        Block:7(\n          PassStmt:7())))))\n\n[case testWithMultiple]\ndef f(a):\n    pass\ndef main():\n    with f(0) as a, f(a) as b:\n        x = a, b\n[out]\nMypyFile:1(\n  FuncDef:1(\n    f\n    Args(\n      Var(a))\n    Block:2(\n      PassStmt:2()))\n  FuncDef:3(\n    main\n    Block:4(\n      WithStmt:4(\n        Expr(\n          CallExpr:4(\n            NameExpr(f [__main__.f])\n            Args(\n              IntExpr(0))))\n        Target(\n          NameExpr(a* [l]))\n        Expr(\n          CallExpr:4(\n            NameExpr(f [__main__.f])\n            Args(\n              NameExpr(a [l]))))\n        Target(\n          NameExpr(b* [l]))\n        Block:5(\n          AssignmentStmt:5(\n            NameExpr(x* [l])\n            TupleExpr:5(\n              NameExpr(a [l])\n              NameExpr(b [l]))))))))\n\n[case testRenameGlobalVariable]\n# flags: --allow-redefinition\ndef f(a): pass\nx = 0\nf(x)\nx = ''\nf(x)\n[out]\nMypyFile:1(\n  FuncDef:2(\n    f\n    Args(\n      Var(a))\n    Block:2(\n      PassStmt:2()))\n  AssignmentStmt:3(\n    NameExpr(x' [__main__.x'])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:4(\n    CallExpr:4(\n      NameExpr(f [__main__.f])\n      Args(\n        NameExpr(x' [__main__.x']))))\n  AssignmentStmt:5(\n    NameExpr(x [__main__.x])\n    StrExpr()\n    builtins.str)\n  ExpressionStmt:6(\n    CallExpr:6(\n      NameExpr(f [__main__.f])\n      Args(\n        NameExpr(x [__main__.x])))))\n\n[case testNoRenameGlobalVariable]\n# flags: --disallow-redefinition\ndef f(a): pass\nx = 0\nf(x)\nx = ''\nf(x)\n[out]\nMypyFile:1(\n  FuncDef:2(\n    f\n    Args(\n      Var(a))\n    Block:2(\n      PassStmt:2()))\n  AssignmentStmt:3(\n    NameExpr(x [__main__.x])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:4(\n    CallExpr:4(\n      NameExpr(f [__main__.f])\n      Args(\n        NameExpr(x [__main__.x]))))\n  AssignmentStmt:5(\n    NameExpr(x [__main__.x])\n    StrExpr())\n  ExpressionStmt:6(\n    CallExpr:6(\n      NameExpr(f [__main__.f])\n      Args(\n        NameExpr(x [__main__.x])))))\n\n[case testRenameLocalVariable]\n# flags: --allow-redefinition\ndef f(a):\n    f(a)\n    a = ''\n    f(a)\n[out]\nMypyFile:1(\n  FuncDef:2(\n    f\n    Args(\n      Var(a))\n    Block:3(\n      ExpressionStmt:3(\n        CallExpr:3(\n          NameExpr(f [__main__.f])\n          Args(\n            NameExpr(a [l]))))\n      AssignmentStmt:4(\n        NameExpr(a'* [l])\n        StrExpr())\n      ExpressionStmt:5(\n        CallExpr:5(\n          NameExpr(f [__main__.f])\n          Args(\n            NameExpr(a' [l])))))))\n\n[case testCannotRenameExternalVarWithinClass]\n# flags: --allow-redefinition\nx = 0\nx\nclass A:\n    x = 1\nx = ''\n[out]\nMypyFile:1(\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    IntExpr(0)\n    builtins.int)\n  ExpressionStmt:3(\n    NameExpr(x [__main__.x]))\n  ClassDef:4(\n    A\n    AssignmentStmt:5(\n      NameExpr(x [m])\n      IntExpr(1)\n      builtins.int))\n  AssignmentStmt:6(\n    NameExpr(x [__main__.x])\n    StrExpr()))\n\n[case testSimpleWithRenaming]\nwith 0 as y:\n    z = y\nwith 1 as y:\n    y = 1\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      IntExpr(0))\n    Target(\n      NameExpr(y'* [__main__.y']))\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(z* [__main__.z])\n        NameExpr(y' [__main__.y']))))\n  WithStmt:3(\n    Expr(\n      IntExpr(1))\n    Target(\n      NameExpr(y* [__main__.y]))\n    Block:4(\n      AssignmentStmt:4(\n        NameExpr(y [__main__.y])\n        IntExpr(1)))))\n\n[case testSimpleWithRenamingFailure]\nwith 0 as y:\n    z = y\nzz = y\nwith 1 as y:\n    y = 1\n[out]\nMypyFile:1(\n  WithStmt:1(\n    Expr(\n      IntExpr(0))\n    Target(\n      NameExpr(y* [__main__.y]))\n    Block:2(\n      AssignmentStmt:2(\n        NameExpr(z* [__main__.z])\n        NameExpr(y [__main__.y]))))\n  AssignmentStmt:3(\n    NameExpr(zz* [__main__.zz])\n    NameExpr(y [__main__.y]))\n  WithStmt:4(\n    Expr(\n      IntExpr(1))\n    Target(\n      NameExpr(y [__main__.y]))\n    Block:5(\n      AssignmentStmt:5(\n        NameExpr(y [__main__.y])\n        IntExpr(1)))))\n\n[case testConstantFold1]\nfrom typing_extensions import Final\nadd: Final = 15 + 47\nadd_mul: Final = (2 + 3) * 5\nsub: Final = 7 - 11\nbit_and: Final = 6 & 10\nbit_or: Final = 6 | 10\nbit_xor: Final = 6 ^ 10\nlshift: Final = 5 << 2\nrshift: Final = 13 >> 2\nlshift0: Final = 5 << 0\nrshift0: Final = 13 >> 0\n[out]\nMypyFile:1(\n  ImportFrom:1(typing_extensions, [Final])\n  AssignmentStmt:2(\n    NameExpr(add [__main__.add] = 62)\n    OpExpr:2(\n      +\n      IntExpr(15)\n      IntExpr(47))\n    Literal[62]?)\n  AssignmentStmt:3(\n    NameExpr(add_mul [__main__.add_mul] = 25)\n    OpExpr:3(\n      *\n      OpExpr:3(\n        +\n        IntExpr(2)\n        IntExpr(3))\n      IntExpr(5))\n    Literal[25]?)\n  AssignmentStmt:4(\n    NameExpr(sub [__main__.sub] = -4)\n    OpExpr:4(\n      -\n      IntExpr(7)\n      IntExpr(11))\n    Literal[-4]?)\n  AssignmentStmt:5(\n    NameExpr(bit_and [__main__.bit_and] = 2)\n    OpExpr:5(\n      &\n      IntExpr(6)\n      IntExpr(10))\n    Literal[2]?)\n  AssignmentStmt:6(\n    NameExpr(bit_or [__main__.bit_or] = 14)\n    OpExpr:6(\n      |\n      IntExpr(6)\n      IntExpr(10))\n    Literal[14]?)\n  AssignmentStmt:7(\n    NameExpr(bit_xor [__main__.bit_xor] = 12)\n    OpExpr:7(\n      ^\n      IntExpr(6)\n      IntExpr(10))\n    Literal[12]?)\n  AssignmentStmt:8(\n    NameExpr(lshift [__main__.lshift] = 20)\n    OpExpr:8(\n      <<\n      IntExpr(5)\n      IntExpr(2))\n    Literal[20]?)\n  AssignmentStmt:9(\n    NameExpr(rshift [__main__.rshift] = 3)\n    OpExpr:9(\n      >>\n      IntExpr(13)\n      IntExpr(2))\n    Literal[3]?)\n  AssignmentStmt:10(\n    NameExpr(lshift0 [__main__.lshift0] = 5)\n    OpExpr:10(\n      <<\n      IntExpr(5)\n      IntExpr(0))\n    Literal[5]?)\n  AssignmentStmt:11(\n    NameExpr(rshift0 [__main__.rshift0] = 13)\n    OpExpr:11(\n      >>\n      IntExpr(13)\n      IntExpr(0))\n    Literal[13]?))\n\n[case testConstantFold2]\nfrom typing_extensions import Final\nneg1: Final = -5\nneg2: Final = --1\nneg3: Final = -0\npos: Final = +5\ninverted1: Final = ~0\ninverted2: Final = ~5\ninverted3: Final = ~3\np0: Final = 3**0\np1: Final = 3**5\np2: Final = (-5)**3\np3: Final = 0**0\ns: Final = 'x' + 'y'\n[out]\nMypyFile:1(\n  ImportFrom:1(typing_extensions, [Final])\n  AssignmentStmt:2(\n    NameExpr(neg1 [__main__.neg1] = -5)\n    UnaryExpr:2(\n      -\n      IntExpr(5))\n    Literal[-5]?)\n  AssignmentStmt:3(\n    NameExpr(neg2 [__main__.neg2] = 1)\n    UnaryExpr:3(\n      -\n      UnaryExpr:3(\n        -\n        IntExpr(1)))\n    Literal[1]?)\n  AssignmentStmt:4(\n    NameExpr(neg3 [__main__.neg3] = 0)\n    UnaryExpr:4(\n      -\n      IntExpr(0))\n    Literal[0]?)\n  AssignmentStmt:5(\n    NameExpr(pos [__main__.pos] = 5)\n    UnaryExpr:5(\n      +\n      IntExpr(5))\n    Literal[5]?)\n  AssignmentStmt:6(\n    NameExpr(inverted1 [__main__.inverted1] = -1)\n    UnaryExpr:6(\n      ~\n      IntExpr(0))\n    Literal[-1]?)\n  AssignmentStmt:7(\n    NameExpr(inverted2 [__main__.inverted2] = -6)\n    UnaryExpr:7(\n      ~\n      IntExpr(5))\n    Literal[-6]?)\n  AssignmentStmt:8(\n    NameExpr(inverted3 [__main__.inverted3] = -4)\n    UnaryExpr:8(\n      ~\n      IntExpr(3))\n    Literal[-4]?)\n  AssignmentStmt:9(\n    NameExpr(p0 [__main__.p0] = 1)\n    OpExpr:9(\n      **\n      IntExpr(3)\n      IntExpr(0))\n    Literal[1]?)\n  AssignmentStmt:10(\n    NameExpr(p1 [__main__.p1] = 243)\n    OpExpr:10(\n      **\n      IntExpr(3)\n      IntExpr(5))\n    Literal[243]?)\n  AssignmentStmt:11(\n    NameExpr(p2 [__main__.p2] = -125)\n    OpExpr:11(\n      **\n      UnaryExpr:11(\n        -\n        IntExpr(5))\n      IntExpr(3))\n    Literal[-125]?)\n  AssignmentStmt:12(\n    NameExpr(p3 [__main__.p3] = 1)\n    OpExpr:12(\n      **\n      IntExpr(0)\n      IntExpr(0))\n    Literal[1]?)\n  AssignmentStmt:13(\n    NameExpr(s [__main__.s] = xy)\n    OpExpr:13(\n      +\n      StrExpr(x)\n      StrExpr(y))\n    Literal['xy']?))\n"
  },
  {
    "path": "test-data/unit/semanal-symtable.test",
    "content": "[case testEmptyFile]\n[out]\n-- Note that builtins are ignored to simplify output.\n__main__:\n  SymbolTable()\n\n[case testVarDef]\nx = 1\n[out]\n__main__:\n  SymbolTable(\n    x : Gdef/Var (__main__.x) : builtins.int)\n\n[case testFuncDef]\ndef f(): pass\n[out]\n__main__:\n  SymbolTable(\n    f : Gdef/FuncDef (__main__.f))\n\n[case testEmptyClassDef]\nclass c: pass\n[out]\n__main__:\n  SymbolTable(\n    c : Gdef/TypeInfo (__main__.c))\n\n[case testImport]\nimport m\n[file m.py]\nx = 1\n[out]\n__main__:\n  SymbolTable(\n    m : Gdef/MypyFile (m))\nm:\n  SymbolTable(\n    x : Gdef/Var (m.x) : builtins.int)\n\n[case testImportFromModule]\nfrom m import x\n[file m.py]\nclass x: pass\ny = 1\n[out]\n__main__:\n  SymbolTable(\n    x : Gdef/TypeInfo (m.x))\nm:\n  SymbolTable(\n    x : Gdef/TypeInfo (m.x)\n    y : Gdef/Var (m.y) : builtins.int)\n\n[case testImportAs]\nfrom m import x as xx\n[file m.py]\nclass x: pass\ny = 1\n[out]\n__main__:\n  SymbolTable(\n    xx : Gdef/TypeInfo (m.x))\nm:\n  SymbolTable(\n    x : Gdef/TypeInfo (m.x)\n    y : Gdef/Var (m.y) : builtins.int)\n\n[case testFailingImports]\nfrom sys import non_existing1  # type: ignore\nfrom xyz import non_existing2  # type: ignore\nif int():\n    from sys import non_existing3  # type: ignore\nimport non_existing4  # type: ignore\n[out]\n__main__:\n  SymbolTable(\n    non_existing1 : Gdef/Var (__main__.non_existing1) : Any\n    non_existing2 : Gdef/Var (__main__.non_existing2) : Any\n    non_existing3 : Gdef/Var (__main__.non_existing3) : Any\n    non_existing4 : Gdef/Var (__main__.non_existing4) : Any)\n\n[case testDecorator]\nfrom typing import Callable\n\ndef dec(f: Callable[[], None]) -> Callable[[], None]:\n    return f\n\n@dec\ndef g() -> None:\n    pass\n[out]\n__main__:\n  SymbolTable(\n    Callable : Gdef/TypeInfo (typing.Callable)\n    dec : Gdef/FuncDef (__main__.dec) : def (f: def ()) -> def ()\n    g : Gdef/Decorator (__main__.g) : def ())\n"
  },
  {
    "path": "test-data/unit/semanal-typealiases.test",
    "content": "[case testListTypeAlias]\nfrom typing import List\ndef f() -> List[int]: pass\n[builtins fixtures/list.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [List])\n  FuncDef:2(\n    f\n    def () -> builtins.list[builtins.int]\n    Block:2(\n      PassStmt:2())))\n\n[case testDictTypeAlias]\nfrom typing import Dict\ndef f() -> Dict[int, str]: pass\n[builtins fixtures/dict.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Dict])\n  FuncDef:2(\n    f\n    def () -> builtins.dict[builtins.int, builtins.str]\n    Block:2(\n      PassStmt:2())))\n\n[case testQualifiedTypeAlias]\nimport typing\ndef f() -> typing.List[int]: pass\n[builtins fixtures/list.pyi]\n[out]\nMypyFile:1(\n  Import:1(typing)\n  FuncDef:2(\n    f\n    def () -> builtins.list[builtins.int]\n    Block:2(\n      PassStmt:2())))\n\n[case testTypeApplicationWithTypeAlias]\nfrom typing import List\nList[List[int]]\n[builtins fixtures/list.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [List])\n  ExpressionStmt:2(\n    TypeApplication:2(\n      NameExpr(List [typing.List])\n      Types(\n        builtins.list[builtins.int]))))\n\n[case testTypeApplicationWithQualifiedTypeAlias]\nimport typing\ntyping.List[typing.List[int]]\n[builtins fixtures/list.pyi]\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ExpressionStmt:2(\n    TypeApplication:2(\n      MemberExpr:2(\n        NameExpr(typing)\n        List [typing.List])\n      Types(\n        builtins.list[builtins.int]))))\n\n[case testSimpleTypeAlias]\nimport typing\nclass A: pass\nA2 = A\ndef f(x: A2) -> A: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    PassStmt:2())\n  AssignmentStmt:3(\n    NameExpr(A2* [__main__.A2])\n    NameExpr(A [__main__.A]))\n  FuncDef:4(\n    f\n    Args(\n      Var(x))\n    def (x: __main__.A) -> __main__.A\n    Block:4(\n      PassStmt:4())))\n\n[case testQualifiedSimpleTypeAlias]\nimport typing\nimport _m\nA2 = _m.A\nx = 1 # type: A2\n[fixture _m.py]\nimport typing\nclass A: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  Import:2(_m)\n  AssignmentStmt:3(\n    NameExpr(A2* [__main__.A2])\n    MemberExpr:3(\n      NameExpr(_m)\n      A [_m.A]))\n  AssignmentStmt:4(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    _m.A))\n\n[case testUnionTypeAlias]\nfrom typing import Union\nU = Union[int, str]\ndef f(x: U) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  AssignmentStmt:2(\n    NameExpr(U* [__main__.U])\n    TypeAliasExpr(Union[builtins.int, builtins.str]))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, builtins.str])\n    Block:3(\n      PassStmt:3())))\n\n[case testUnionTypeAlias2]\nfrom typing import Union\nclass A: pass\nU = Union[int, A]\ndef f(x: U) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  ClassDef:2(\n    A\n    PassStmt:2())\n  AssignmentStmt:3(\n    NameExpr(U* [__main__.U])\n    TypeAliasExpr(Union[builtins.int, __main__.A]))\n  FuncDef:4(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, __main__.A])\n    Block:4(\n      PassStmt:4())))\n\n[case testUnionTypeAliasWithQualifiedUnion]\nimport typing\nU = typing.Union[int, str]\ndef f(x: U) -> None: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  AssignmentStmt:2(\n    NameExpr(U* [__main__.U])\n    TypeAliasExpr(Union[builtins.int, builtins.str]))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, builtins.str])\n    Block:3(\n      PassStmt:3())))\n\n[case testTupleTypeAlias]\nfrom typing import Tuple\nT = Tuple[int, str]\ndef f(x: T) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Tuple])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeAliasExpr(Tuple[builtins.int, builtins.str]))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: Tuple[builtins.int, builtins.str])\n    Block:3(\n      PassStmt:3())))\n\n[case testCallableTypeAlias]\nfrom typing import Callable\nC = Callable[[int], None]\ndef f(x: C) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Callable])\n  AssignmentStmt:2(\n    NameExpr(C* [__main__.C])\n    TypeAliasExpr(def (builtins.int)))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: def (builtins.int))\n    Block:3(\n      PassStmt:3())))\n\n[case testGenericTypeAlias]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass G(Generic[T]): pass\nA = G[int]\ndef f(x: A) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Generic, TypeVar])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2())\n  ClassDef:3(\n    G\n    TypeVars(\n      T`1)\n    PassStmt:3())\n  AssignmentStmt:4(\n    NameExpr(A* [__main__.A])\n    TypeAliasExpr(__main__.G[builtins.int]))\n  FuncDef:5(\n    f\n    Args(\n      Var(x))\n    def (x: __main__.G[builtins.int])\n    Block:5(\n      PassStmt:5())))\n\n[case testGenericTypeAlias2]\nfrom typing import List\nA = List[int]\ndef f(x: A) -> None: pass\n[builtins fixtures/list.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [List])\n  AssignmentStmt:2(\n    NameExpr(A* [__main__.A])\n    TypeAliasExpr(builtins.list[builtins.int]))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: builtins.list[builtins.int])\n    Block:3(\n      PassStmt:3())))\n\n[case testImportUnionTypeAlias]\nimport typing\nfrom _m import U\ndef f(x: U) -> None: pass\n[fixture _m.py]\nfrom typing import Union\nclass A: pass\nU = Union[int, A]\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ImportFrom:2(_m, [U])\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, _m.A])\n    Block:3(\n      PassStmt:3())))\n\n[case testImportUnionTypeAlias2]\nimport typing\nimport _m\ndef f(x: _m.U) -> None: pass\n[fixture _m.py]\nfrom typing import Union\nclass A: pass\nU = Union[int, A]\n[out]\nMypyFile:1(\n  Import:1(typing)\n  Import:2(_m)\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, _m.A])\n    Block:3(\n      PassStmt:3())))\n\n[case testImportSimpleTypeAlias]\nimport typing\nfrom _m import A\ndef f(x: A) -> None: pass\n[fixture _m.py]\nimport typing\nA = int\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ImportFrom:2(_m, [A])\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: builtins.int)\n    Block:3(\n      PassStmt:3())))\n\n[case testImportSimpleTypeAlias2]\nimport typing\nimport _m\ndef f(x: _m.A) -> None: pass\n[fixture _m.py]\nimport typing\nA = int\n[out]\nMypyFile:1(\n  Import:1(typing)\n  Import:2(_m)\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: builtins.int)\n    Block:3(\n      PassStmt:3())))\n\n[case testAnyTypeAlias]\nfrom typing import Any\nA = Any\na = 1 # type: A\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Any])\n  AssignmentStmt:2(\n    NameExpr(A* [__main__.A])\n    NameExpr(Any [typing.Any]))\n  AssignmentStmt:3(\n    NameExpr(a [__main__.a])\n    IntExpr(1)\n    Any))\n\n[case testAnyTypeAlias2]\nimport typing\nA = typing.Any\na = 1 # type: A\n[out]\nMypyFile:1(\n  Import:1(typing)\n  AssignmentStmt:2(\n    NameExpr(A* [__main__.A])\n    MemberExpr:2(\n      NameExpr(typing)\n      Any [typing.Any]))\n  AssignmentStmt:3(\n    NameExpr(a [__main__.a])\n    IntExpr(1)\n    Any))\n\n[case testTypeAliasAlias]\nfrom typing import Union\nU = Union[int, str]\nU2 = U\nx = 1 # type: U2\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  AssignmentStmt:2(\n    NameExpr(U* [__main__.U])\n    TypeAliasExpr(Union[builtins.int, builtins.str]))\n  AssignmentStmt:3(\n    NameExpr(U2* [__main__.U2])\n    NameExpr(U [__main__.U]))\n  AssignmentStmt:4(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    Union[builtins.int, builtins.str]))\n\n[case testTypeAliasOfImportedAlias]\nfrom typing import Union\nfrom _m import U\nU2 = U\nx = 1 # type: U2\n[fixture _m.py]\nfrom typing import Union\nU = Union[int, str]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  ImportFrom:2(_m, [U])\n  AssignmentStmt:3(\n    NameExpr(U2* [__main__.U2])\n    NameExpr(U [_m.U]))\n  AssignmentStmt:4(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    Union[builtins.int, builtins.str]))\n\n[case testListTypeDoesNotGenerateAlias]\n\nimport typing\nA = [int, str]\na = 1 # type: A  # E: Variable \"__main__.A\" is not valid as a type \\\n                 # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testCantUseStringLiteralAsTypeAlias]\n\nfrom typing import Union\nA = 'Union[int, str]'\na = 1 # type: A  # E: Variable \"__main__.A\" is not valid as a type \\\n                 # N: See https://kotlinisland.github.io/basedmypy/common_issues.html#variables-vs-type-aliases\n\n[case testStringLiteralTypeAsAliasComponent]\nfrom typing import Union\nA = Union['int', str]\na = 1 # type: A\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  AssignmentStmt:2(\n    NameExpr(A* [__main__.A])\n    TypeAliasExpr(Union[builtins.int, builtins.str]))\n  AssignmentStmt:3(\n    NameExpr(a [__main__.a])\n    IntExpr(1)\n    Union[builtins.int, builtins.str]))\n\n[case testComplexTypeAlias]\nfrom typing import Union, Tuple, Any\nA = Union['int', Tuple[int, Any]]\na = 1 # type: A\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union, Tuple, Any])\n  AssignmentStmt:2(\n    NameExpr(A* [__main__.A])\n    TypeAliasExpr(Union[builtins.int, Tuple[builtins.int, Any]]))\n  AssignmentStmt:3(\n    NameExpr(a [__main__.a])\n    IntExpr(1)\n    Union[builtins.int, Tuple[builtins.int, Any]]))\n"
  },
  {
    "path": "test-data/unit/semanal-typeddict.test",
    "content": "-- Create Type\n\n-- TODO: Implement support for this syntax.\n--[case testCanCreateTypedDictTypeWithDictCall]\n--from mypy_extensions import TypedDict\n--Point = TypedDict('Point', dict(x=int, y=int))\n--[builtins fixtures/dict.pyi]\n--[out]\n--MypyFile:1(\n--  ImportFrom:1(mypy_extensions, [TypedDict])\n--  AssignmentStmt:2(\n--    NameExpr(Point* [__main__.Point])\n--    TypedDictExpr:2(Point)))\n\n[case testCanCreateTypedDictTypeWithDictLiteral]\nfrom mypy_extensions import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\n[builtins fixtures/dict.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(mypy_extensions, [TypedDict])\n  AssignmentStmt:2(\n    NameExpr(Point* [__main__.Point])\n    TypedDictExpr:2(Point)))\n\n[case testTypedDictWithDocString]\nfrom mypy_extensions import TypedDict\nclass A(TypedDict):\n    \"\"\"foo\"\"\"\n    x: str\n[builtins fixtures/dict.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(mypy_extensions, [TypedDict])\n  ClassDef:2(\n    A\n    BaseType(\n      mypy_extensions._TypedDict)\n    ExpressionStmt:3(\n      StrExpr(foo))\n    AssignmentStmt:4(\n      NameExpr(x)\n      TempNode:4(\n        Any)\n      builtins.str)))\n"
  },
  {
    "path": "test-data/unit/semanal-typeinfo.test",
    "content": "[case testEmptyFile]\n[out]\nTypeInfoMap()\n\n[case testEmptyClass]\nclass c: pass\n[out]\nTypeInfoMap(\n  __main__.c : TypeInfo(\n    Name(__main__.c)\n    Bases(builtins.object)\n    Mro(__main__.c, builtins.object)\n    Names()))\n\n[case testClassWithMethod]\nclass c:\n  def f(self): pass\n[out]\nTypeInfoMap(\n  __main__.c : TypeInfo(\n    Name(__main__.c)\n    Bases(builtins.object)\n    Mro(__main__.c, builtins.object)\n    Names(\n      f)))\n\n[case testClassWithAttributes]\nclass c:\n  def __init__(self, x):\n    self.y = x\n    self.z = 1\n[out]\nTypeInfoMap(\n  __main__.c : TypeInfo(\n    Name(__main__.c)\n    Bases(builtins.object)\n    Mro(__main__.c, builtins.object)\n    Names(\n      __init__\n      y\n      z)))\n\n[case testBaseClass]\nclass base: pass\nclass c(base): pass\n[out]\nTypeInfoMap(\n  __main__.base : TypeInfo(\n    Name(__main__.base)\n    Bases(builtins.object)\n    Mro(__main__.base, builtins.object)\n    Names())\n  __main__.c : TypeInfo(\n    Name(__main__.c)\n    Bases(__main__.base)\n    Mro(__main__.c, __main__.base, builtins.object)\n    Names()))\n\n[case testClassAndAbstractClass]\nfrom abc import abstractmethod, ABCMeta\nimport typing\n\nclass i(metaclass=ABCMeta): pass\nclass c(i): pass\n[out]\nTypeInfoMap(\n  __main__.c : TypeInfo(\n    Name(__main__.c)\n    Bases(__main__.i)\n    Mro(__main__.c, __main__.i, builtins.object)\n    Names()\n    MetaclassType(abc.ABCMeta))\n  __main__.i : TypeInfo(\n    Name(__main__.i)\n    Bases(builtins.object)\n    Mro(__main__.i, builtins.object)\n    Names()\n    DeclaredMetaclass(abc.ABCMeta)\n    MetaclassType(abc.ABCMeta)))\n\n[case testAttributeWithoutType]\nclass A:\n    a = A\n[out]\nTypeInfoMap(\n  __main__.A : TypeInfo(\n    Name(__main__.A)\n    Bases(builtins.object)\n    Mro(__main__.A, builtins.object)\n    Names(\n      a)))\n"
  },
  {
    "path": "test-data/unit/semanal-types.test",
    "content": "[case testVarWithType]\nimport typing\nclass A: pass\nx = A() # type: A\ny = x\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    PassStmt:2())\n  AssignmentStmt:3(\n    NameExpr(x [__main__.x])\n    CallExpr:3(\n      NameExpr(A [__main__.A])\n      Args())\n    __main__.A)\n  AssignmentStmt:4(\n    NameExpr(y* [__main__.y])\n    NameExpr(x [__main__.x])))\n\n[case testLocalVarWithType]\nclass A: pass\ndef f():\n  x = None # type: A\n  y = x\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    PassStmt:1())\n  FuncDef:2(\n    f\n    Block:3(\n      AssignmentStmt:3(\n        NameExpr(x [l])\n        NameExpr(None [builtins.None])\n        __main__.A)\n      AssignmentStmt:4(\n        NameExpr(y* [l])\n        NameExpr(x [l])))))\n\n[case testAnyType]\nfrom typing import Any\nx = None # type: Any\ny = x\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Any])\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    Any)\n  AssignmentStmt:3(\n    NameExpr(y* [__main__.y])\n    NameExpr(x [__main__.x])))\n\n[case testMemberVarWithType]\nimport typing\nclass A:\n  def __init__(self):\n    self.x = None # type: int\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    FuncDef:3(\n      __init__\n      Args(\n        Var(self))\n      Block:4(\n        AssignmentStmt:4(\n          MemberExpr:4(\n            NameExpr(self [l])\n            x)\n          NameExpr(None [builtins.None])\n          builtins.int)))))\n\n[case testClassVarWithType]\nimport typing\nclass A:\n  x = None # type: int\n  x = 1\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    AssignmentStmt:3(\n      NameExpr(x [m])\n      NameExpr(None [builtins.None])\n      builtins.int)\n    AssignmentStmt:4(\n      NameExpr(x [__main__.A.x])\n      IntExpr(1))))\n\n[case testFunctionSig]\nfrom typing import Any\nclass A: pass\ndef f(x: A) -> A: pass\ndef g(x: Any, y: A) -> None:\n  z = x, y\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Any])\n  ClassDef:2(\n    A\n    PassStmt:2())\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def (x: __main__.A) -> __main__.A\n    Block:3(\n      PassStmt:3()))\n  FuncDef:4(\n    g\n    Args(\n      Var(x)\n      Var(y))\n    def (x: Any, y: __main__.A)\n    Block:5(\n      AssignmentStmt:5(\n        NameExpr(z* [l])\n        TupleExpr:5(\n          NameExpr(x [l])\n          NameExpr(y [l]))))))\n\n[case testBaseclass]\nclass A: pass\nclass B(A): pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    PassStmt:1())\n  ClassDef:2(\n    B\n    BaseType(\n      __main__.A)\n    PassStmt:2()))\n\n[case testMultipleVarDef]\n\nclass A: pass\nclass B: pass\na, b = None, None # type: (A, B)\nx = a, b\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ClassDef:2(\n    A\n    PassStmt:2())\n  ClassDef:3(\n    B\n    PassStmt:3())\n  AssignmentStmt:4(\n    TupleExpr:4(\n      NameExpr(a [__main__.a])\n      NameExpr(b [__main__.b]))\n    TupleExpr:4(\n      NameExpr(None [builtins.None])\n      NameExpr(None [builtins.None]))\n    Tuple[__main__.A, __main__.B])\n  AssignmentStmt:5(\n    NameExpr(x* [__main__.x])\n    TupleExpr:5(\n      NameExpr(a [__main__.a])\n      NameExpr(b [__main__.b]))))\n\n[case testGenericType]\nfrom typing import TypeVar, Generic, Any\n\nt = TypeVar('t')\n\nclass A(Generic[t]): pass\nclass B: pass\nx = None # type: A[B]\ny = None # type: A[Any]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic, Any])\n  AssignmentStmt:3(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:3())\n  ClassDef:5(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:5())\n  ClassDef:6(\n    B\n    PassStmt:6())\n  AssignmentStmt:7(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    __main__.A[__main__.B])\n  AssignmentStmt:8(\n    NameExpr(y [__main__.y])\n    NameExpr(None [builtins.None])\n    __main__.A[Any]))\n\n[case testGenericType2]\nfrom typing import TypeVar, Generic, Any\nt = TypeVar('t')\ns = TypeVar('s')\nclass A(Generic[t, s]): pass\nclass B: pass\nx = None # type: A[B, Any]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic, Any])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(s* [__main__.s])\n    TypeVarExpr:3())\n  ClassDef:4(\n    A\n    TypeVars(\n      t`1\n      s`2)\n    PassStmt:4())\n  ClassDef:5(\n    B\n    PassStmt:5())\n  AssignmentStmt:6(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    __main__.A[__main__.B, Any]))\n\n[case testAssignmentAfterDef]\n\n\nclass A: pass\na = None # type: A\na = 1\ndef f():\n  b = None # type: A\n  b = 1\n[out]\nMypyFile:1(\n  ClassDef:3(\n    A\n    PassStmt:3())\n  AssignmentStmt:4(\n    NameExpr(a [__main__.a])\n    NameExpr(None [builtins.None])\n    __main__.A)\n  AssignmentStmt:5(\n    NameExpr(a [__main__.a])\n    IntExpr(1))\n  FuncDef:6(\n    f\n    Block:7(\n      AssignmentStmt:7(\n        NameExpr(b [l])\n        NameExpr(None [builtins.None])\n        __main__.A)\n      AssignmentStmt:8(\n        NameExpr(b [l])\n        IntExpr(1)))))\n\n[case testCast]\nfrom typing import TypeVar, Generic, Any, cast\nt = TypeVar('t')\nclass c: pass\nclass d(Generic[t]): pass\ncast(Any, 1)\ncast(c, 1)\ncast(d[c], c)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic, Any, cast])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    c\n    PassStmt:3())\n  ClassDef:4(\n    d\n    TypeVars(\n      t`1)\n    PassStmt:4())\n  ExpressionStmt:5(\n    CastExpr:5(\n      IntExpr(1)\n      Any))\n  ExpressionStmt:6(\n    CastExpr:6(\n      IntExpr(1)\n      __main__.c))\n  ExpressionStmt:7(\n    CastExpr:7(\n      NameExpr(c [__main__.c])\n      __main__.d[__main__.c])))\n\n[case testCastToQualifiedTypeAndCast]\nimport typing\nimport _m\ntyping.cast(_m.C, object)\n[fixture _m.py]\nclass C: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  Import:2(_m)\n  ExpressionStmt:3(\n    CastExpr:3(\n      NameExpr(object [builtins.object])\n      _m.C)))\n\n[case testLongQualifiedCast]\nimport typing\nimport _m._n\ntyping.cast(_m._n.C, object)\n[fixture _m/__init__.py]\n[fixture _m/_n.py]\nclass C: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  Import:2(_m._n)\n  ExpressionStmt:3(\n    CastExpr:3(\n      NameExpr(object [builtins.object])\n      _m._n.C)))\n\n[case testCastTargetWithTwoTypeArgs]\nfrom typing import TypeVar, Generic, cast\nt = TypeVar('t')\ns = TypeVar('s')\nclass C(Generic[t, s]): pass\ncast(C[str, int], C)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic, cast])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(s* [__main__.s])\n    TypeVarExpr:3())\n  ClassDef:4(\n    C\n    TypeVars(\n      t`1\n      s`2)\n    PassStmt:4())\n  ExpressionStmt:5(\n    CastExpr:5(\n      NameExpr(C [__main__.C])\n      __main__.C[builtins.str, builtins.int])))\n\n[case testCastToTupleType]\nfrom typing import Tuple, cast\ncast(Tuple[int, str], None)\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Tuple, cast])\n  ExpressionStmt:2(\n    CastExpr:2(\n      NameExpr(None [builtins.None])\n      Tuple[builtins.int, builtins.str])))\n\n[case testCastToFunctionType]\nfrom typing import Callable, cast\ncast(Callable[[int], str], None)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Callable, cast])\n  ExpressionStmt:2(\n    CastExpr:2(\n      NameExpr(None [builtins.None])\n      def (builtins.int) -> builtins.str)))\n\n[case testCastToStringLiteralType]\nfrom typing import cast\ncast('int', 1)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [cast])\n  ExpressionStmt:2(\n    CastExpr:2(\n      IntExpr(1)\n      builtins.int)))\n\n[case testAssertType]\nfrom typing import assert_type\nassert_type(1, int)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [assert_type])\n  ExpressionStmt:2(\n    AssertTypeExpr:2(\n      IntExpr(1)\n      builtins.int)))\n\n[case testFunctionTypeVariable]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef f(x: t) -> None:\n  y = None # type: t\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def [t] (x: t`-1)\n    Block:4(\n      AssignmentStmt:4(\n        NameExpr(y [l])\n        NameExpr(None [builtins.None])\n        t`-1))))\n\n[case testTwoFunctionTypeVariables]\nfrom typing import TypeVar\nt = TypeVar('t')\nu = TypeVar('u')\ndef f(x: t, y: u, z: t) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(u* [__main__.u])\n    TypeVarExpr:3())\n  FuncDef:4(\n    f\n    Args(\n      Var(x)\n      Var(y)\n      Var(z))\n    def [t, u] (x: t`-1, y: u`-2, z: t`-1)\n    Block:4(\n      PassStmt:4())))\n\n[case testNestedGenericFunctionTypeVariable]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\ndef f(x: A[t], y) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  FuncDef:4(\n    f\n    Args(\n      Var(x)\n      Var(y))\n    def [t] (x: __main__.A[t`-1], y: Any)\n    Block:4(\n      PassStmt:4())))\n\n[case testNestedGenericFunctionTypeVariable2]\nfrom typing import TypeVar, Tuple, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\ndef f(x: Tuple[int, t]) -> None: pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Tuple, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  FuncDef:4(\n    f\n    Args(\n      Var(x))\n    def [t] (x: Tuple[builtins.int, t`-1])\n    Block:4(\n      PassStmt:4())))\n\n[case testNestedGenericFunctionTypeVariable3]\nfrom typing import TypeVar, Callable, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\ndef f(x: Callable[[int, t], int]) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Callable, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  FuncDef:4(\n    f\n    Args(\n      Var(x))\n    def [t] (x: def (builtins.int, t`-1) -> builtins.int)\n    Block:4(\n      PassStmt:4())))\n\n[case testNestedGenericFunctionTypeVariable4]\nfrom typing import TypeVar, Callable, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\ndef f(x: Callable[[], t]) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Callable, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  FuncDef:4(\n    f\n    Args(\n      Var(x))\n    def [t] (x: def () -> t`-1)\n    Block:4(\n      PassStmt:4())))\n\n[case testGenericFunctionTypeVariableInReturnType]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef f() -> t: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  FuncDef:3(\n    f\n    def [t] () -> t`-1\n    Block:3(\n      PassStmt:3())))\n\n[case testSelfType]\nclass A:\n  def f(self, o: object) -> None: pass\n[out]\nMypyFile:1(\n  ClassDef:1(\n    A\n    FuncDef:2(\n      f\n      Args(\n        Var(self)\n        Var(o))\n      def (self: __main__.A, o: builtins.object)\n      Block:2(\n        PassStmt:2()))))\n\n[case testNestedGenericFunction]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef f() -> None:\n    def g() -> t: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  FuncDef:3(\n    f\n    def ()\n    Block:4(\n      FuncDef:4(\n        g\n        def [t] () -> t`-1\n        Block:4(\n          PassStmt:4())))))\n\n[case testClassTvar]\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t')\n\nclass c(Generic[t]):\n  def f(self) -> t: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:3(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:3())\n  ClassDef:5(\n    c\n    TypeVars(\n      t`1)\n    FuncDef:6(\n      f\n      Args(\n        Var(self))\n      def (self: __main__.c[t`1]) -> t`1\n      Block:6(\n        PassStmt:6()))))\n\n[case testClassTvar2]\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t')\ns = TypeVar('s')\n\nclass c(Generic[t, s]):\n  def f(self, x: s) -> t: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:3(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:3())\n  AssignmentStmt:4(\n    NameExpr(s* [__main__.s])\n    TypeVarExpr:4())\n  ClassDef:6(\n    c\n    TypeVars(\n      t`1\n      s`2)\n    FuncDef:7(\n      f\n      Args(\n        Var(self)\n        Var(x))\n      def (self: __main__.c[t`1, s`2], x: s`2) -> t`1\n      Block:7(\n        PassStmt:7()))))\n\n[case testGenericBaseClass]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass d(Generic[t]): pass\nclass c(d[t], Generic[t]): pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    d\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  ClassDef:4(\n    c\n    TypeVars(\n      t`1)\n    BaseType(\n      __main__.d[t`1])\n    PassStmt:4()))\n\n[case testTupleType]\nfrom typing import Tuple\nt = None # type: tuple\nt1 = None # type: Tuple[object]\nt2 = None # type: Tuple[int, object]\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Tuple])\n  AssignmentStmt:2(\n    NameExpr(t [__main__.t])\n    NameExpr(None [builtins.None])\n    builtins.tuple[Any, ...])\n  AssignmentStmt:3(\n    NameExpr(t1 [__main__.t1])\n    NameExpr(None [builtins.None])\n    Tuple[builtins.object])\n  AssignmentStmt:4(\n    NameExpr(t2 [__main__.t2])\n    NameExpr(None [builtins.None])\n    Tuple[builtins.int, builtins.object]))\n\n[case testVariableLengthTuple]\nfrom typing import Tuple\nt = None # type: Tuple[int, ...]\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Tuple])\n  AssignmentStmt:2(\n    NameExpr(t [__main__.t])\n    NameExpr(None [builtins.None])\n    builtins.tuple[builtins.int, ...]))\n\n[case testInvalidTupleType]\nfrom typing import Tuple\nt = None # type: Tuple[int, str, ...] # E: Unexpected \"...\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFunctionTypes]\nfrom typing import Callable\nf = None # type: Callable[[object, int], str]\ng = None # type: Callable[[], None]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Callable])\n  AssignmentStmt:2(\n    NameExpr(f [__main__.f])\n    NameExpr(None [builtins.None])\n    def (builtins.object, builtins.int) -> builtins.str)\n  AssignmentStmt:3(\n    NameExpr(g [__main__.g])\n    NameExpr(None [builtins.None])\n    def ()))\n\n[case testOverloadedFunction]\nfrom typing import overload, Any\n@overload\ndef f(a: object) -> int: a\n@overload\ndef f(a: str) -> object: a\n\ndef f(a: Any) -> Any: return a\n\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [overload, Any])\n  OverloadedFuncDef:2(\n    FuncDef:7(\n      f\n      Args(\n        Var(a))\n      def (a: Any) -> Any\n      Block:7(\n        ReturnStmt:7(\n          NameExpr(a [l]))))\n    Overload(def (a: builtins.object) -> builtins.int, \\\n             def (a: builtins.str) -> builtins.object)\n    Decorator:2(\n      Var(f)\n      NameExpr(overload [typing.overload])\n      FuncDef:3(\n        f\n        Args(\n          Var(a))\n        def (a: builtins.object) -> builtins.int\n        Block:3(\n          ExpressionStmt:3(\n            NameExpr(a [l])))))\n    Decorator:4(\n      Var(f)\n      NameExpr(overload [typing.overload])\n      FuncDef:5(\n        f\n        Args(\n          Var(a))\n        def (a: builtins.str) -> builtins.object\n        Block:5(\n          ExpressionStmt:5(\n            NameExpr(a [l])))))))\n\n[case testReferenceToOverloadedFunction]\nfrom typing import overload\n@overload\ndef f() -> None: pass\n@overload\ndef f(x: int) -> None: pass\n\ndef f(*args) -> None: pass\n\nx = f\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [overload])\n  OverloadedFuncDef:2(\n    FuncDef:7(\n      f\n      def (*args: Any)\n      VarArg(\n        Var(args))\n      Block:7(\n        PassStmt:7()))\n    Overload(def (), def (x: builtins.int))\n    Decorator:2(\n      Var(f)\n      NameExpr(overload [typing.overload])\n      FuncDef:3(\n        f\n        def ()\n        Block:3(\n          PassStmt:3())))\n    Decorator:4(\n      Var(f)\n      NameExpr(overload [typing.overload])\n      FuncDef:5(\n        f\n        Args(\n          Var(x))\n        def (x: builtins.int)\n        Block:5(\n          PassStmt:5()))))\n  AssignmentStmt:9(\n    NameExpr(x* [__main__.x])\n    NameExpr(f [__main__.f])))\n\n[case testNestedOverloadedFunction]\nfrom typing import overload\ndef f():\n    @overload\n    def g(): pass\n    @overload\n    def g(x): pass\n\n    def g(*args): pass\n\n    y = g\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [overload])\n  FuncDef:2(\n    f\n    Block:3(\n      OverloadedFuncDef:3(\n        FuncDef:8(\n          g\n          VarArg(\n            Var(args))\n          Block:8(\n            PassStmt:8()))\n        Overload(def () -> Any, def (x: Any) -> Any)\n        Decorator:3(\n          Var(g)\n          NameExpr(overload [typing.overload])\n          FuncDef:4(\n            g\n            Block:4(\n              PassStmt:4())))\n        Decorator:5(\n          Var(g)\n          NameExpr(overload [typing.overload])\n          FuncDef:6(\n            g\n            Args(\n              Var(x))\n            Block:6(\n              PassStmt:6()))))\n      AssignmentStmt:10(\n        NameExpr(y* [l])\n        NameExpr(g [l])))))\n\n[case testImplicitGenericTypeArgs]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\ns = TypeVar('s')\nclass A(Generic[t, s]): pass\nx = None # type: A\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(s* [__main__.s])\n    TypeVarExpr:3())\n  ClassDef:4(\n    A\n    TypeVars(\n      t`1\n      s`2)\n    PassStmt:4())\n  AssignmentStmt:5(\n    NameExpr(x [__main__.x])\n    NameExpr(None [builtins.None])\n    __main__.A[Any, Any]))\n\n[case testImplicitTypeArgsAndGenericBaseClass]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\ns = TypeVar('s')\nclass B(Generic[s]): pass\nclass A(B, Generic[t]): pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(s* [__main__.s])\n    TypeVarExpr:3())\n  ClassDef:4(\n    B\n    TypeVars(\n      s`1)\n    PassStmt:4())\n  ClassDef:5(\n    A\n    TypeVars(\n      t`1)\n    BaseType(\n      __main__.B[Any])\n    PassStmt:5()))\n\n[case testTypeApplication]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\nx = A[int]()\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  AssignmentStmt:4(\n    NameExpr(x* [__main__.x])\n    CallExpr:4(\n      TypeApplication:4(\n        NameExpr(A [__main__.A])\n        Types(\n          builtins.int))\n      Args())))\n\n[case testTypeApplicationWithTwoTypeArgs]\nfrom typing import TypeVar, Generic, Any\nt = TypeVar('t')\ns = TypeVar('s')\nclass A(Generic[t, s]): pass\nx = A[int, Any]()\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic, Any])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(s* [__main__.s])\n    TypeVarExpr:3())\n  ClassDef:4(\n    A\n    TypeVars(\n      t`1\n      s`2)\n    PassStmt:4())\n  AssignmentStmt:5(\n    NameExpr(x* [__main__.x])\n    CallExpr:5(\n      TypeApplication:5(\n        NameExpr(A [__main__.A])\n        Types(\n          builtins.int\n          Any))\n      Args())))\n\n[case testFunctionTypeApplication]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef f(x: t) -> None: pass\nf[int](1)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def [t] (x: t`-1)\n    Block:3(\n      PassStmt:3()))\n  ExpressionStmt:4(\n    CallExpr:4(\n      TypeApplication:4(\n        NameExpr(f [__main__.f])\n        Types(\n          builtins.int))\n      Args(\n        IntExpr(1)))))\n\n[case testTypeApplicationWithStringLiteralType]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\nA['int']()\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(t* [__main__.t])\n    TypeVarExpr:2())\n  ClassDef:3(\n    A\n    TypeVars(\n      t`1)\n    PassStmt:3())\n  ExpressionStmt:4(\n    CallExpr:4(\n      TypeApplication:4(\n        NameExpr(A [__main__.A])\n        Types(\n          builtins.int))\n      Args())))\n\n[case testVarArgsAndKeywordArgs]\ndef g(*x: int, y: str = ''): pass\n[builtins fixtures/tuple.pyi]\n[out]\nMypyFile:1(\n  FuncDef:1(\n    g\n    MaxPos(0)\n    Args(\n      default(\n        Var(y)\n        StrExpr()))\n    def (*x: builtins.int, y: builtins.str =) -> Any\n    VarArg(\n      Var(x))\n    Block:1(\n      PassStmt:1())))\n\n[case testQualifiedGeneric]\nfrom typing import TypeVar\nimport typing\nT = TypeVar('T')\nclass A(typing.Generic[T]): pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  Import:2(typing)\n  AssignmentStmt:3(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:3())\n  ClassDef:4(\n    A\n    TypeVars(\n      T`1)\n    PassStmt:4()))\n\n[case testQualifiedTypevar]\nimport typing\nT = typing.TypeVar('T')\ndef f(x: T) -> T: pass\n[out]\nMypyFile:1(\n  Import:1(typing)\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2())\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def [T] (x: T`-1) -> T`-1\n    Block:3(\n      PassStmt:3())))\n\n[case testAliasedTypevar]\nfrom typing import TypeVar as tv\nT = tv('T')\ndef f(x: T) -> T: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar : tv])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2())\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def [T] (x: T`-1) -> T`-1\n    Block:3(\n      PassStmt:3())))\n\n[case testLocalTypevar]\nfrom typing import TypeVar\ndef f():\n    T = TypeVar('T')\n    def g(x: T) -> T: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  FuncDef:2(\n    f\n    Block:3(\n      AssignmentStmt:3(\n        NameExpr(T* [l])\n        TypeVarExpr:3())\n      FuncDef:4(\n        g\n        Args(\n          Var(x))\n        def [T] (x: T`-1) -> T`-1\n        Block:4(\n          PassStmt:4())))))\n\n[case testClassLevelTypevar]\nfrom typing import TypeVar\nclass A:\n    T = TypeVar('T')\n    def g(self, x: T) -> T: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  ClassDef:2(\n    A\n    AssignmentStmt:3(\n      NameExpr(T* [m])\n      TypeVarExpr:3())\n    FuncDef:4(\n      g\n      Args(\n        Var(self)\n        Var(x))\n      def [T] (self: __main__.A, x: T`-1) -> T`-1\n      Block:4(\n        PassStmt:4()))))\n\n[case testImportTypevar]\nfrom typing import Generic\nfrom _m import T\nclass A(Generic[T]):\n    y = None # type: T\n[fixture _m.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Generic])\n  ImportFrom:2(_m, [T])\n  ClassDef:3(\n    A\n    TypeVars(\n      T`1)\n    AssignmentStmt:4(\n      NameExpr(y [m])\n      NameExpr(None [builtins.None])\n      T`1)))\n\n[case testQualifiedReferenceToTypevarInClass]\nfrom typing import Generic\nimport _m\nclass A(Generic[_m.T]):\n    a = None # type: _m.T\n    def f(self, x: _m.T):\n        b = None # type: _m.T\n[fixture _m.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Generic])\n  Import:2(_m)\n  ClassDef:3(\n    A\n    TypeVars(\n      _m.T`1)\n    AssignmentStmt:4(\n      NameExpr(a [m])\n      NameExpr(None [builtins.None])\n      _m.T`1)\n    FuncDef:5(\n      f\n      Args(\n        Var(self)\n        Var(x))\n      def (self: __main__.A[_m.T`1], x: _m.T`1) -> Any\n      Block:6(\n        AssignmentStmt:6(\n          NameExpr(b [l])\n          NameExpr(None [builtins.None])\n          _m.T`1)))))\n\n[case testQualifiedReferenceToTypevarInFunctionSignature]\nimport _m\ndef f(x: _m.T) -> None:\n    a = None # type: _m.T\n[fixture _m.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n[out]\nMypyFile:1(\n  Import:1(_m)\n  FuncDef:2(\n    f\n    Args(\n      Var(x))\n    def [_m.T] (x: _m.T`-1)\n    Block:3(\n      AssignmentStmt:3(\n        NameExpr(a [l])\n        NameExpr(None [builtins.None])\n        _m.T`-1))))\n\n[case testFunctionCommentAnnotation]\nfrom typing import Any\ndef f(x): # type: (int) -> Any\n  x = 1\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Any])\n  FuncDef:2(\n    f\n    Args(\n      Var(x))\n    def (x: builtins.int) -> Any\n    Block:3(\n      AssignmentStmt:3(\n        NameExpr(x [l])\n        IntExpr(1)))))\n\n[case testMethodCommentAnnotation]\nimport typing\nclass A:\n  def f(self, x): # type: (int) -> str\n    x = 1\n[out]\nMypyFile:1(\n  Import:1(typing)\n  ClassDef:2(\n    A\n    FuncDef:3(\n      f\n      Args(\n        Var(self)\n        Var(x))\n      def (self: __main__.A, x: builtins.int) -> builtins.str\n      Block:4(\n        AssignmentStmt:4(\n          NameExpr(x [l])\n          IntExpr(1))))))\n\n[case testTypevarWithValues]\nfrom typing import TypeVar, Any\nT = TypeVar('T', int, str)\nS = TypeVar('S', Any, int, str)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Any])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      Values(\n        builtins.int\n        builtins.str)))\n  AssignmentStmt:3(\n    NameExpr(S* [__main__.S])\n    TypeVarExpr:3(\n      Values(\n        Any\n        builtins.int\n        builtins.str))))\n\n-- why on earth is there a test for this\n--[case testTypevarWithValuesAndVariance]\n--from typing import TypeVar\n--T = TypeVar('T', int, str, covariant=True)\n--[builtins fixtures/bool.pyi]\n--[out]\n--MypyFile:1(\n--  ImportFrom:1(typing, [TypeVar])\n--  AssignmentStmt:2(\n--    NameExpr(T* [__main__.T])\n--    TypeVarExpr:2(\n--      Variance(COVARIANT)\n--      Values(\n--        builtins.int\n--        builtins.str))))\n\n[case testTypevarWithFalseVariance]\nfrom typing import TypeVar\nT1 = TypeVar('T1', covariant=False)\nT2 = TypeVar('T2', covariant=False, contravariant=False)\nT3 = TypeVar('T3', contravariant=False)\nT4 = TypeVar('T4', covariant=True, contravariant=False)\nT5 = TypeVar('T5', covariant=False, contravariant=True)\n[builtins fixtures/bool.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(T1* [__main__.T1])\n    TypeVarExpr:2())\n  AssignmentStmt:3(\n    NameExpr(T2* [__main__.T2])\n    TypeVarExpr:3())\n  AssignmentStmt:4(\n    NameExpr(T3* [__main__.T3])\n    TypeVarExpr:4())\n  AssignmentStmt:5(\n    NameExpr(T4* [__main__.T4])\n    TypeVarExpr:5(\n      Variance(COVARIANT)))\n  AssignmentStmt:6(\n    NameExpr(T5* [__main__.T5])\n    TypeVarExpr:6(\n      Variance(CONTRAVARIANT))))\n\n[case testTypevarWithBound]\nfrom typing import TypeVar\nT = TypeVar('T', bound=int)\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      UpperBound(builtins.int))))\n\n[case testGenericFunctionWithValueSet]\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      Values(\n        builtins.int\n        builtins.str)))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def [T in (builtins.int, builtins.str)] (x: T`-1) -> T`-1\n    Block:3(\n      PassStmt:3())))\n\n[case testGenericClassWithValueSet]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', int, str)\nclass C(Generic[T]): pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      Values(\n        builtins.int\n        builtins.str)))\n  ClassDef:3(\n    C\n    TypeVars(\n      T`1)\n    PassStmt:3()))\n\n[case testGenericFunctionWithBound]\nfrom typing import TypeVar\nT = TypeVar('T', bound=int)\ndef f(x: T) -> T: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      UpperBound(builtins.int)))\n  FuncDef:3(\n    f\n    Args(\n      Var(x))\n    def [T <: builtins.int] (x: T`-1) -> T`-1\n    Block:3(\n      PassStmt:3())))\n\n[case testGenericClassWithBound]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', bound=int)\nclass C(Generic[T]): pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar, Generic])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      UpperBound(builtins.int)))\n  ClassDef:3(\n    C\n    TypeVars(\n      T`1)\n    PassStmt:3()))\n\n[case testSimpleDucktypeDecorator]\nfrom typing import _promote\n@_promote(str)\nclass S: pass\n[typing fixtures/typing-medium.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [_promote])\n  ClassDef:3(\n    S\n    Promote([builtins.str])\n    Decorators(\n      PromoteExpr:2(builtins.str))\n    PassStmt:3()))\n\n[case testUnionType]\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  FuncDef:2(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, builtins.str])\n    Block:2(\n      PassStmt:2())))\n\n[case testUnionTypeWithNoneItem]\nfrom typing import Union\ndef f(x: Union[int, None]) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  FuncDef:2(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, None])\n    Block:2(\n      PassStmt:2())))\n\n[case testUnionTypeWithNoneItemAndTwoItems]\nfrom typing import Union\ndef f(x: Union[int, None, str]) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  FuncDef:2(\n    f\n    Args(\n      Var(x))\n    def (x: Union[builtins.int, None, builtins.str])\n    Block:2(\n      PassStmt:2())))\n\n[case testUnionTypeWithSingleItem]\nfrom typing import Union\ndef f(x: Union[int]) -> None: pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Union])\n  FuncDef:2(\n    f\n    Args(\n      Var(x))\n    def (x: builtins.int)\n    Block:2(\n      PassStmt:2())))\n\n[case testOptionalTypes]\nfrom typing import Optional\nx = 1  # type: Optional[int]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Optional])\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    IntExpr(1)\n    Union[builtins.int, None]))\n\n[case testInvalidOptionalType]\nfrom typing import Optional\nx = 1  # type: Optional[int, str]  # E: Optional[...] must have exactly one type argument\ny = 1  # type: Optional  # E: Optional[...] must have exactly one type argument\n[out]\n\n[case testCoAndContravariantTypeVar]\nfrom typing import TypeVar\nT = TypeVar('T', covariant=True)\nS = TypeVar('S', contravariant=True)\n[builtins fixtures/bool.pyi]\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [TypeVar])\n  AssignmentStmt:2(\n    NameExpr(T* [__main__.T])\n    TypeVarExpr:2(\n      Variance(COVARIANT)))\n  AssignmentStmt:3(\n    NameExpr(S* [__main__.S])\n    TypeVarExpr:3(\n      Variance(CONTRAVARIANT))))\n\n[case testTupleExpressionAsType]\ndef f(x: (int, int)) -> None: pass\n[out]\nmain:1: error: Syntax error in type annotation\nmain:1: note: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n\n[case testQualifiedTypeNameBasedOnAny]\nfrom typing import Any\nx = 0 # type: Any\nz = 0 # type: x.y\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [Any])\n  AssignmentStmt:2(\n    NameExpr(x [__main__.x])\n    IntExpr(0)\n    Any)\n  AssignmentStmt:3(\n    NameExpr(z [__main__.z])\n    IntExpr(0)\n    Any))\n\n\n[case testParamSpec]\nfrom typing import ParamSpec\nP = ParamSpec(\"P\")\n[out]\nMypyFile:1(\n  ImportFrom:1(typing, [ParamSpec])\n  AssignmentStmt:2(\n    NameExpr(P* [__main__.P])\n    ParamSpecExpr:2()))\n\n[case testTypeVarTuple]\nfrom typing_extensions import TypeVarTuple\nTV = TypeVarTuple(\"TV\")\n[out]\nMypyFile:1(\n  ImportFrom:1(typing_extensions, [TypeVarTuple])\n  AssignmentStmt:2(\n    NameExpr(TV* [__main__.TV])\n    TypeVarTupleExpr:2(\n      UpperBound(builtins.tuple[builtins.object, ...]))))\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleCallable]\nfrom typing_extensions import TypeVarTuple, Unpack\nfrom typing import Callable\nTs = TypeVarTuple(\"Ts\")\n\ndef foo(x: Callable[[Unpack[Ts]], None]) -> None:\n    pass\n[out]\nMypyFile:1(\n  ImportFrom:1(typing_extensions, [TypeVarTuple, Unpack])\n  ImportFrom:2(typing, [Callable])\n  AssignmentStmt:3(\n    NameExpr(Ts* [__main__.Ts])\n    TypeVarTupleExpr:3(\n      UpperBound(builtins.tuple[builtins.object, ...])))\n  FuncDef:5(\n    foo\n    Args(\n      Var(x))\n    def [Ts] (x: def (*Unpack[Ts`-1]))\n    Block:6(\n      PassStmt:6())))\n\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/stubgen-based.test",
    "content": "-- Test cases for stubgen that generate stubs from Python code\n\n[case testEmptyFile]\n[out]\n\n[case testSingleFunction]\ndef f():\n    x = 1\n[out]\ndef f(): ...\n\n[case testTwoFunctions]\ndef f(a, b):\n    x = 1\ndef g(arg):\n    pass\n[out]\ndef f(a, b): ...\ndef g(arg): ...\n\n[case testDefaultArgInt]\ndef f(a, b=2): ...\ndef g(b=-1, c=0): ...\n[out]\ndef f(a, b: int = 2): ...\ndef g(b: int = -1, c: int = 0): ...\n\n[case testDefaultArgNone]\ndef f(x=None): ...\n[out]\nfrom basedtyping import Untyped\n\ndef f(x: Untyped | None = None): ...\n\n[case testDefaultArgBool]\ndef f(x=True, y=False): ...\n[out]\ndef f(x: bool = True, y: bool = False): ...\n\n[case testDefaultArgStr]\ndef f(x='foo'): ...\n[out]\ndef f(x: str = 'foo'): ...\n\n[case testDefaultArgBytes]\ndef f(x=b'foo'): ...\n[out]\ndef f(x: bytes = b'foo'): ...\n\n[case testDefaultArgFloat]\ndef f(x=1.2): ...\n[out]\ndef f(x: float = 1.2): ...\n\n[case testDefaultArgOther]\ndef f(x=ord): ...\n[out]\ndef f(x=...): ...\n\n[case testPreserveFunctionAnnotation]\ndef f(x: Foo) -> Bar: ...\ndef g(x: Foo = Foo()) -> Bar: ...\n[out]\ndef f(x: Foo) -> Bar: ...\ndef g(x: Foo = ...) -> Bar: ...\n\n[case testPreserveFunctionAnnotationWithArgs]\ndef f(x: foo['x']) -> bar: ...\ndef g(x: foo[x]) -> bar: ...\ndef h(x: foo['x', 'y']) -> bar: ...\ndef i(x: foo[x, y]) -> bar: ...\ndef j(x: foo['x', y]) -> bar: ...\ndef k(x: foo[x, 'y']) -> bar: ...\ndef lit_str(x: Literal['str']) -> Literal['str']: ...\ndef lit_int(x: Literal[1]) -> Literal[1]: ...\n[out]\ndef f(x: foo['x']) -> bar: ...\ndef g(x: foo[x]) -> bar: ...\ndef h(x: foo['x', 'y']) -> bar: ...\ndef i(x: foo[x, y]) -> bar: ...\ndef j(x: foo['x', y]) -> bar: ...\ndef k(x: foo[x, 'y']) -> bar: ...\ndef lit_str(x: Literal['str']) -> Literal['str']: ...\ndef lit_int(x: Literal[1]) -> Literal[1]: ...\n\n[case testPreserveVarAnnotation]\nx: Foo\n[out]\nx: Foo\n\n[case testPreserveVarAnnotationWithoutQuotes]\nx: 'Foo'\n[out]\nx: Foo\n\n[case testVarArgs]\ndef f(x, *y): ...\n[out]\ndef f(x, *y): ...\n\n[case testKwVarArgs]\ndef f(x, **y): ...\n[out]\ndef f(x, **y): ...\n\n[case testVarArgsWithKwVarArgs]\ndef f(a, *b, **c): ...\ndef g(a, *b, c=1): ...\ndef h(a, *b, c=1, **d): ...\ndef i(a, *, b=1): ...\ndef j(a, *, b=1, **c): ...\n[out]\ndef f(a, *b, **c): ...\ndef g(a, *b, c: int = 1): ...\ndef h(a, *b, c: int = 1, **d): ...\ndef i(a, *, b: int = 1): ...\ndef j(a, *, b: int = 1, **c): ...\n\n[case testClass]\nclass A:\n    def f(self, x):\n        x = 1\ndef g(): ...\n[out]\nclass A:\n    def f(self, x): ...\n\ndef g(): ...\n\n[case testVariable]\nx = 1\n[out]\nx: int\n\n[case testAnnotatedVariable]\nx: int = 1\n[out]\nx: int\n\n[case testAnnotatedVariableGeneric]\nx: Foo[int, str] = ...\n[out]\nx: Foo[int, str]\n\n[case testAnnotatedVariableOldSyntax]\nx = 1  # type: int\n[out]\nx: int\n\n[case testAnnotatedVariableNone]\nx: None\n[out]\nx: None\n\n[case testAnnotatedVariableNoneOldSyntax]\nx = None  # type: None\n[out]\nx: None\n\n[case testMultipleVariable]\nx = y = 1\n[out]\nx: int\ny: int\n\n[case testClassVariable]\nclass C:\n    x = 1\n[out]\nclass C:\n    x: int\n\n[case testInitTypeAnnotationPreserved]\nclass C:\n    def __init__(self, x: str):\n        pass\n[out]\nclass C:\n    def __init__(self, x: str): ...\n\n[case testSelfAssignment]\nclass C:\n    def __init__(self):\n        self.x = 1\n        x.y = 2\n[out]\nclass C:\n    x: int\n    def __init__(self): ...\n\n[case testSelfAndClassBodyAssignment]\nx = 1\nclass C:\n    x = 1\n    def __init__(self):\n        self.x = 1\n        self.x = 1\n[out]\nx: int\n\nclass C:\n    x: int\n    def __init__(self): ...\n\n[case testEmptyClass]\nclass A: ...\n[out]\nclass A: ...\n\n[case testSkipPrivateFunction]\ndef _f(): ...\ndef g(): ...\n[out]\ndef g(): ...\n\n[case testIncludePrivateFunction]\n# flags:  --include-private\ndef _f(): ...\ndef g(): ...\n[out]\ndef _f(): ...\ndef g(): ...\n\n[case testSkipPrivateMethod]\nclass A:\n    def _f(self): ...\n[out]\nclass A: ...\n\n[case testIncludePrivateMethod]\n# flags:  --include-private\nclass A:\n    def _f(self): ...\n[out]\nclass A:\n    def _f(self): ...\n\n[case testSkipPrivateVar]\n_x = 1\nclass A:\n    _y = 1\n[out]\nclass A: ...\n\n[case testIncludePrivateVar]\n# flags:  --include-private\n_x = 1\nclass A:\n    _y = 1\n[out]\n_x: int\n\nclass A:\n    _y: int\n\n[case testSpecialInternalVar]\n__all__ = []\n__author__ = ''\n__version__ = ''\n[out]\n__version__: str\n\n[case testBaseClass]\nclass A: ...\nclass B(A): ...\n[out]\nclass A: ...\nclass B(A): ...\n\n[case testDecoratedFunction]\n@decorator\ndef foo(x): ...\n[out]\ndef foo(x): ...\n\n[case testMultipleAssignment]\nx, y = 1, 2\n[out]\nfrom basedtyping import Untyped\n\nx: Untyped\ny: Untyped\n\n[case testMultipleAssignmentAnnotated]\nx, y = 1, \"2\" # type: int, str\n[out]\nx: int\ny: str\n\n[case testMultipleAssignment2]\n[x, y] = 1, 2\n[out]\nfrom basedtyping import Untyped\n\nx: Untyped\ny: Untyped\n\n[case testKeywordOnlyArg]\ndef f(x, *, y=1): ...\ndef g(x, *, y=1, z=2): ...\n[out]\ndef f(x, *, y: int = 1): ...\ndef g(x, *, y: int = 1, z: int = 2): ...\n\n[case testProperty]\nclass A:\n    @property\n    def f(self):\n        return 1\n    @f.setter\n    def f(self, x): ...\n\n    def h(self):\n        self.f = 1\n[out]\nfrom basedtyping import Untyped\n\nclass A:\n    @property\n    def f(self) -> Untyped: ...\n    @f.setter\n    def f(self, x): ...\n    def h(self): ...\n\n[case testStaticMethod]\nclass A:\n    @staticmethod\n    def f(x): ...\n[out]\nclass A:\n    @staticmethod\n    def f(x): ...\n\n[case testClassMethod]\nclass A:\n    @classmethod\n    def f(cls): ...\n[out]\nclass A:\n    @classmethod\n    def f(cls): ...\n\n[case testIfMainCheck]\ndef a(): ...\nif __name__ == '__main__':\n    x = 1\n    def f(): ...\ndef b(): ...\n[out]\ndef a(): ...\ndef b(): ...\n\n[case testImportStar]\nfrom x import *\nfrom a.b import *\ndef f(): ...\n[out]\nfrom x import *\nfrom a.b import *\n\ndef f(): ...\n\n[case testNoSpacesBetweenEmptyClasses]\nclass X:\n    def g(self): ...\nclass A: ...\nclass B: ...\nclass C:\n    def f(self): ...\n[out]\nclass X:\n    def g(self): ...\n\nclass A: ...\nclass B: ...\n\nclass C:\n    def f(self): ...\n\n[case testExceptionBaseClasses]\nclass A(Exception): ...\nclass B(ValueError): ...\n[out]\nclass A(Exception): ...\nclass B(ValueError): ...\n\n[case testOmitSomeSpecialMethods]\nclass A:\n    def __str__(self): ...\n    def __repr__(self): ...\n    def __eq__(self): ...\n    def __getstate__(self): ...\n    def __setstate__(self, state): ...\n[out]\nfrom basedtyping import Untyped\n\nclass A:\n    def __eq__(self) -> Untyped: ...\n\n-- Tests that will perform runtime imports of modules.\n-- Don't use `_import` suffix if there are unquoted forward references.\n\n[case testOmitDefsNotInAll_import]\n__all__ = [] + ['f']\ndef f(): ...\ndef g(): ...\n[out]\n__all__ = ['f']\n\ndef f(): ...\n\n[case testOmitDefsNotInAll_semanal]\n__all__ = ['f']\ndef f(): ...\ndef g(): ...\n[out]\n__all__ = ['f']\n\ndef f(): ...\n\n[case testVarDefsNotInAll_import]\n__all__ = [] + ['f', 'g']\ndef f(): ...\nx = 1\ny = 1\ndef g(): ...\n[out]\n__all__ = ['f', 'g']\n\ndef f(): ...\ndef g(): ...\n\n[case testIncludeClassNotInAll_import]\n__all__ = [] + ['f']\ndef f(): ...\nclass A: ...\n[out]\n__all__ = ['f']\n\ndef f(): ...\n\nclass A: ...\n\n[case testAllAndClass_import]\n__all__ = ['A']\nclass A:\n    x = 1\n    def f(self): ...\n[out]\n__all__ = ['A']\n\nclass A:\n    x: int\n    def f(self): ...\n\n[case testSkipMultiplePrivateDefs]\nclass A: ...\n_x = 1\n_y = 1\n_z = 1\nclass C: ...\n[out]\nclass A: ...\nclass C: ...\n\n[case testIncludeMultiplePrivateDefs]\n# flags:  --include-private\nclass A: ...\n_x = 1\n_y = 1\n_z = 1\nclass C: ...\n[out]\nclass A: ...\n\n_x: int\n_y: int\n_z: int\n\nclass C: ...\n\n[case testIncludeFromImportIfInAll_import]\nfrom re import match, search, sub\n__all__ = ['match', 'sub', 'x']\nx = 1\n[out]\nfrom re import match as match, sub as sub\n\n__all__ = ['match', 'sub', 'x']\n\nx: int\n\n[case testExportModule_import]\nimport re\n__all__ = ['re', 'x']\nx = 1\ny = 2\n[out]\nimport re as re\n\n__all__ = ['re', 'x']\n\nx: int\n\n[case testExportModule2_import]\nimport re\n__all__ = ['re', 'x']\nx = 1\ny = 2\n[out]\nimport re as re\n\n__all__ = ['re', 'x']\n\nx: int\n\n[case testExportModuleAs_import]\nimport re as rex\n__all__ = ['rex', 'x']\nx = 1\ny = 2\n[out]\nimport re as rex\n\n__all__ = ['rex', 'x']\n\nx: int\n\n[case testExportModuleInPackage_import]\nimport urllib.parse as p\n__all__ = ['p']\n[out]\nimport urllib.parse as p\n\n__all__ = ['p']\n\n[case testExportPackageOfAModule_import]\nimport urllib.parse\n__all__ = ['urllib']\n\n[out]\nimport urllib as urllib\n\n__all__ = ['urllib']\n\n[case testRelativeImportAll]\nfrom .x import *\n[out]\nfrom .x import *\n\n[case testCommentForUndefinedName_import]\n__all__ = ['f', 'x', 'C', 'g']\ndef f(): ...\nx = 1\nclass C:\n    def g(self): ...\n[out]\n__all__ = ['f', 'x', 'C', 'g']\n\ndef f(): ...\n\nx: int\n\nclass C:\n    def g(self): ...\n\n# Names in __all__ with no definition:\n#   g\n\n[case testIgnoreSlots]\nclass A:\n    __slots__ = ()\n[out]\nclass A: ...\n\n[case testSkipPrivateProperty]\nclass A:\n    @property\n    def _foo(self): ...\n[out]\nclass A: ...\n\n[case testIncludePrivateProperty]\n# flags:  --include-private\nclass A:\n    @property\n    def _foo(self): ...\n[out]\nclass A:\n    @property\n    def _foo(self): ...\n\n[case testSkipPrivateStaticAndClassMethod]\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n[out]\nclass A: ...\n\n[case testIncludePrivateStaticAndClassMethod]\n# flags:  --include-private\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n[out]\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n\n[case testNamedtuple]\nimport collections, x\nX = collections.namedtuple('X', ['a', 'b'])\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Untyped\n    b: Untyped\n\n[case testEmptyNamedtuple]\nimport collections\nX = collections.namedtuple('X', [])\n[out]\nfrom typing import NamedTuple\n\nclass X(NamedTuple): ...\n\n[case testNamedtupleAltSyntax]\nfrom collections import namedtuple, xx\nX = namedtuple('X', 'a b')\nxx\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Untyped\n    b: Untyped\n\n[case testNamedtupleAltSyntaxUsingComma]\nfrom collections import namedtuple, xx\nX = namedtuple('X', 'a,    b')\nxx\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Untyped\n    b: Untyped\n\n[case testNamedtupleAltSyntaxUsingMultipleCommas]\nfrom collections import namedtuple, xx\nX = namedtuple('X', 'a,,   b')\nxx\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Untyped\n    b: Untyped\n\n[case testNamedtupleWithUnderscore]\nfrom collections import namedtuple as _namedtuple\ndef f(): ...\nX = _namedtuple('X', 'a b')\ndef g(): ...\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\ndef f(): ...\n\nclass X(NamedTuple):\n    a: Untyped\n    b: Untyped\n\ndef g(): ...\n\n[case testNamedtupleBaseClass]\nimport collections, x\n_X = collections.namedtuple('_X', ['a', 'b'])\nclass Y(_X): ...\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass _X(NamedTuple):\n    a: Untyped\n    b: Untyped\n\nclass Y(_X): ...\n\n[case testNamedtupleAltSyntaxFieldsTuples]\nfrom collections import namedtuple, xx\nX = namedtuple('X', ())\nY = namedtuple('Y', ('a',))\nZ = namedtuple('Z', ('a', 'b', 'c', 'd', 'e'))\nxx\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass X(NamedTuple): ...\n\nclass Y(NamedTuple):\n    a: Untyped\n\nclass Z(NamedTuple):\n    a: Untyped\n    b: Untyped\n    c: Untyped\n    d: Untyped\n    e: Untyped\n\n[case testDynamicNamedTuple]\nfrom collections import namedtuple\nN = namedtuple('N', ['x', 'y'] + ['z'])\n[out]\nfrom basedtyping import Untyped\n\nN: Untyped\n\n[case testArbitraryBaseClass]\nimport x\nclass D(x.C): ...\n[out]\nimport x\n\nclass D(x.C): ...\n\n[case testArbitraryBaseClass2]\nimport x.y\nclass D(x.y.C): ...\n[out]\nimport x.y\n\nclass D(x.y.C): ...\n\n[case testUnqualifiedArbitraryBaseClassWithNoDef]\nclass A(int): ...\n[out]\nclass A(int): ...\n\n[case testUnqualifiedArbitraryBaseClass]\nfrom x import X\nclass A(X): ...\n[out]\nfrom x import X\n\nclass A(X): ...\n\n[case testUnqualifiedArbitraryBaseClassWithImportAs]\nfrom x import X as _X\nclass A(_X): ...\n[out]\nfrom x import X as _X\n\nclass A(_X): ...\n\n[case testGenericClass]\nclass D(Generic[T]): ...\n[out]\nclass D(Generic[T]): ...\n\n[case testObjectBaseClass]\nclass A(object): ...\n[out]\nclass A: ...\n\n[case testEmptyLines]\ndef x(): ...\ndef f():\n    class A:\n        def f(self):\n            self.x = 1\ndef g(): ...\n[out]\ndef x(): ...\ndef f(): ...\ndef g(): ...\n\n[case testNestedClass]\nclass A:\n    class B:\n        x = 1\n        def f(self): ...\n    def g(self): ...\n[out]\nclass A:\n    class B:\n        x: int\n        def f(self): ...\n    def g(self): ...\n\n[case testExportViaRelativeImport]\nfrom .api import get\n[out]\nfrom .api import get as get\n\n[case testExportViaRelativePackageImport]\nfrom .packages.urllib3.contrib import parse\n[out]\nfrom .packages.urllib3.contrib import parse as parse\n\n[case testNoExportViaRelativeImport]\nfrom . import get\nget()\n[out]\n\n[case testRelativeImportAndBase]\nfrom .x import X\nclass A(X):\n     pass\n[out]\nfrom .x import X\n\nclass A(X): ...\n\n[case testDuplicateDef]\ndef syslog(a): pass\ndef syslog(a): pass\n[out]\ndef syslog(a): ...\n\n[case testAsyncAwait_fast_parser]\nasync def f(a):\n   x = await y\n[out]\nasync def f(a): ...\n\n[case testInferOptionalOnlyFunc]\nclass A:\n    x = None\n    def __init__(self, a=None):\n        self.x = []\n    def method(self, a=None):\n        self.x = []\n[out]\nfrom basedtyping import Untyped\n\nclass A:\n    x: Untyped\n    def __init__(self, a: Untyped | None = None): ...\n    def method(self, a: Untyped | None = None): ...\n\n[case testAnnotationImportsFrom]\nimport foo\nfrom collections import defaultdict\nx: defaultdict\n\n[out]\nfrom collections import defaultdict\n\nx: defaultdict\n\n[case testAnnotationImports]\nimport foo\nimport collections\nx: collections.defaultdict\n\n[out]\nimport collections\n\nx: collections.defaultdict\n\n\n[case testAnnotationImports2]\nfrom typing import List\nimport collections\nx: List[collections.defaultdict]\n\n[out]\nimport collections\n\nx: list[collections.defaultdict]\n\n\n[case testAnnotationFwRefs]\nx: C\n\nclass C:\n    attr: C\n\ny: C\n[out]\nx: C\n\nclass C:\n    attr: C\n\ny: C\n\n[case testTypeVarPreserved]\ntv = TypeVar('tv')\n\n[out]\nfrom typing import TypeVar\n\ntv = TypeVar('tv')\n\n[case testTypeVarArgsPreserved]\ntv = TypeVar('tv', int, str)\n\n[out]\nfrom typing import TypeVar\n\ntv = TypeVar('tv', int, str)\n\n[case testTypeVarNamedArgsPreserved]\ntv = TypeVar('tv', bound=bool, covariant=True)\n\n[out]\nfrom typing import TypeVar\n\ntv = TypeVar('tv', bound=bool, covariant=True)\n\n[case testTypeAliasPreserved]\nalias = str\n\n[out]\nalias = str\n\n[case testDeepTypeAliasPreserved]\n\nalias = Dict[str, List[str]]\n\n[out]\nalias = Dict[str, List[str]]\n\n[case testDeepGenericTypeAliasPreserved]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nalias = Union[T, List[T]]\n\n[out]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nalias = Union[T, List[T]]\n\n[case testEllipsisAliasPreserved]\n\nalias = Tuple[int, ...]\n\n[out]\nalias = Tuple[int, ...]\n\n[case testCallableAliasPreserved]\n\nalias1 = Callable[..., int]\nalias2 = Callable[[str, bool], None]\n\n[out]\nalias1 = Callable[..., int]\nalias2 = Callable[[str, bool], None]\n\n[case testAliasPullsImport]\nfrom module import Container\n\nalias = Container[Any]\n\n[out]\nfrom module import Container\nfrom typing import Any\n\nalias = Container[Any]\n\n[case testAliasExceptions]\nnoalias1 = None\nnoalias2 = ...\nnoalias3 = True\n\n[out]\nfrom basedtyping import Untyped\n\nnoalias1: Untyped\nnoalias2: Untyped\nnoalias3: bool\n\n-- More features/fixes:\n--   do not export deleted names\n\n[case testFunctionNoReturnInfersReturnNone]\ndef f():\n    x = 1\n[out]\ndef f(): ...\n\n[case testFunctionReturnNoReturnType]\ndef f():\n    return 1\ndef g():\n    return\n[out]\nfrom basedtyping import Untyped\n\ndef f() -> Untyped: ...\ndef g(): ...\n\n[case testFunctionEllipsisInfersReturnNone]\ndef f(): ...\n[out]\ndef f(): ...\n\n[case testFunctionYields]\ndef f():\n    yield 123\ndef g():\n    x = yield\ndef h1():\n    yield\n    return\ndef h2():\n    yield\n    return \"abc\"\ndef all():\n    x = yield 123\n    return \"abc\"\n[out]\nfrom basedtyping import Untyped\nfrom collections.abc import Generator\n\ndef f() -> Generator[Untyped]: ...\ndef g() -> Generator[None, Untyped]: ...\ndef h1() -> Generator[None]: ...\ndef h2() -> Generator[None, None, Untyped]: ...\ndef all() -> Generator[Untyped, Untyped, Untyped]: ...\n\n[case testFunctionYieldsNone]\ndef f():\n    yield\ndef g():\n    yield None\n\n[out]\nfrom collections.abc import Generator\n\ndef f() -> Generator[None]: ...\ndef g() -> Generator[None]: ...\n\n[case testGeneratorAlreadyDefined]\nclass Generator:\n    pass\n\ndef f():\n    yield 123\n[out]\nfrom basedtyping import Untyped\nfrom collections.abc import Generator as _Generator\n\nclass Generator: ...\n\ndef f() -> _Generator[Untyped]: ...\n\n[case testCallable]\nfrom typing import Callable\n\nx: Callable[[int, int], int]\n[out]\nfrom typing import Callable\n\nx: Callable[[int, int], int]\n\n[case testAwaitDef]\nclass F:\n    async def f(self):\n        return 1\n\nasync def g():\n    return 2\n[out]\nfrom basedtyping import Untyped\n\nclass F:\n    async def f(self) -> Untyped: ...\n\nasync def g() -> Untyped: ...\n\n[case testCoroutineImportAsyncio]\nimport asyncio\n\nclass F:\n    @asyncio.coroutine\n    def f(self):\n        return 1\n\n@asyncio.coroutine\ndef g():\n    return 2\n\n@asyncio.coroutine\ndef h():\n    return 3\n[out]\nimport asyncio\nfrom basedtyping import Untyped\n\nclass F:\n    @asyncio.coroutine\n    def f(self) -> Untyped: ...\n\n@asyncio.coroutine\ndef g() -> Untyped: ...\n@asyncio.coroutine\ndef h() -> Untyped: ...\n\n[case testCoroutineImportAsyncioCoroutines]\nimport asyncio.coroutines\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self):\n        return 1\n\n@asyncio.coroutines.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio.coroutines\nfrom basedtyping import Untyped\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self) -> Untyped: ...\n\n@asyncio.coroutines.coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineImportAsyncioCoroutinesSub]\nimport asyncio\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self):\n        return 1\n\n@asyncio.coroutines.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio\nfrom basedtyping import Untyped\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self) -> Untyped: ...\n\n@asyncio.coroutines.coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineImportTypes]\nimport types\n\nclass F:\n    @types.coroutine\n    def f(self):\n        return 1\n\n@types.coroutine\ndef g():\n    return 2\n[out]\nimport types\nfrom basedtyping import Untyped\n\nclass F:\n    @types.coroutine\n    def f(self) -> Untyped: ...\n\n@types.coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineFromAsyncioImportCoroutine]\nfrom asyncio import coroutine\n\nclass F:\n    @coroutine\n    def f(self):\n        return 1\n\n@coroutine\ndef g():\n    return 2\n[out]\nfrom asyncio import coroutine\nfrom basedtyping import Untyped\n\nclass F:\n    @coroutine\n    def f(self) -> Untyped: ...\n\n@coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineFromAsyncioCoroutinesImportCoroutine]\nfrom asyncio.coroutines import coroutine\n\nclass F:\n    @coroutine\n    def f(self):\n        return 1\n\n@coroutine\ndef g():\n    return 2\n[out]\nfrom asyncio.coroutines import coroutine\nfrom basedtyping import Untyped\n\nclass F:\n    @coroutine\n    def f(self) -> Untyped: ...\n\n@coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineFromTypesImportCoroutine]\nfrom types import coroutine\n\nclass F:\n    @coroutine\n    def f(self):\n        return 1\n\n@coroutine\ndef g():\n    return 2\n[out]\nfrom basedtyping import Untyped\nfrom types import coroutine\n\nclass F:\n    @coroutine\n    def f(self) -> Untyped: ...\n\n@coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineFromAsyncioImportCoroutineAsC]\nfrom asyncio import coroutine as c\n\nclass F:\n    @c\n    def f(self):\n        return 1\n\n@c\ndef g():\n    return 2\n[out]\nfrom asyncio import coroutine as c\nfrom basedtyping import Untyped\n\nclass F:\n    @c\n    def f(self) -> Untyped: ...\n\n@c\ndef g() -> Untyped: ...\n\n[case testCoroutineFromAsyncioCoroutinesImportCoroutineAsC]\nfrom asyncio.coroutines import coroutine as c\n\nclass F:\n    @c\n    def f(self):\n        return 1\n\n@c\ndef g():\n    return 2\n[out]\nfrom asyncio.coroutines import coroutine as c\nfrom basedtyping import Untyped\n\nclass F:\n    @c\n    def f(self) -> Untyped: ...\n\n@c\ndef g() -> Untyped: ...\n\n[case testCoroutineFromTypesImportCoroutineAsC]\nfrom types import coroutine as c\n\nclass F:\n    @c\n    def f(self):\n        return 1\n\n@c\ndef g():\n    return 2\n[out]\nfrom basedtyping import Untyped\nfrom types import coroutine as c\n\nclass F:\n    @c\n    def f(self) -> Untyped: ...\n\n@c\ndef g() -> Untyped: ...\n\n[case testCoroutineImportAsyncioAsA]\nimport asyncio as a\n\nclass F:\n    @a.coroutine\n    def f(self):\n        return 1\n\n@a.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio as a\nfrom basedtyping import Untyped\n\nclass F:\n    @a.coroutine\n    def f(self) -> Untyped: ...\n\n@a.coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineImportAsyncioCoroutinesAsC]\nimport asyncio.coroutines as c\n\nclass F:\n    @c.coroutine\n    def f(self):\n        return 1\n\n@c.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio.coroutines as c\nfrom basedtyping import Untyped\n\nclass F:\n    @c.coroutine\n    def f(self) -> Untyped: ...\n\n@c.coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineImportAsyncioCoroutinesSubAsA]\nimport asyncio as a\n\nclass F:\n    @a.coroutines.coroutine\n    def f(self):\n        return 1\n\n@a.coroutines.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio as a\nfrom basedtyping import Untyped\n\nclass F:\n    @a.coroutines.coroutine\n    def f(self) -> Untyped: ...\n\n@a.coroutines.coroutine\ndef g() -> Untyped: ...\n\n[case testCoroutineImportTypesAsT]\nimport types as t\n\nclass F:\n    @t.coroutine\n    def f(self):\n        return 1\n\n@t.coroutine\ndef g():\n    return 2\n[out]\nimport types as t\nfrom basedtyping import Untyped\n\nclass F:\n    @t.coroutine\n    def f(self) -> Untyped: ...\n\n@t.coroutine\ndef g() -> Untyped: ...\n\n-- Tests for stub generation from semantically analyzed trees.\n-- These tests are much slower, so use the `_semanal` suffix only when needed.\n\n[case testNestedClass_semanal]\nclass Outer:\n    class Inner:\n        pass\n\nA = Outer.Inner\n[out]\nclass Outer:\n    class Inner: ...\nA = Outer.Inner\n\n[case testFunctionAlias_semanal]\nfrom asyncio import coroutine\n\n@coroutine\ndef start_server():\n    ...\n\nstart = start_server\n[out]\nfrom asyncio import coroutine\n\n@coroutine\ndef start_server(): ...\nstart = start_server\n\n[case testModuleAlias_semanal]\nimport a\n\nb = a\n[file a.py]\nx = 1\n[out]\nimport a\n\nb = a\n\n[case testBadAliasNested_semanal]\nimport a\n\nx = registry[a.f]\n[file a.py]\ndef f(): ...\n[out]\nfrom basedtyping import Untyped\n\nx: Untyped\n\n[case testCrossModuleClass_semanal]\nimport a\n\nclass C:\n    x: A\n    def f(self) -> A: ...\nA = a.A\n[file a.py]\nclass A: ...\n[out]\nimport a\n\nclass C:\n    x: A\n    def f(self) -> A: ...\nA = a.A\n\n[case testCrossModuleFunction_semanal]\nimport a\ng = a.f\n[file a.py]\ndef f(): ...\n[out]\nimport a\n\ng = a.f\n\n[case testPrivateAliasesExcluded_semanal]\nimport a, _a\n\nclass C: ...\n\nA = a._A\nB = _a.f\n_C = C\n[file a.py]\nclass _A: ...\n[file _a.py]\ndef f(): ...\n[out]\nfrom basedtyping import Untyped\n\nclass C: ...\n\nA: Untyped\nB: Untyped\n\n[case testPrivateAliasesIncluded_semanal]\n# flags: --include-private\nimport a, _a\n\nclass C: ...\n\nA = a._A\nB = _a.f\n_C = C\n[file a.py]\nclass _A: ...\n[file _a.py]\ndef f(): ...\n[out]\nimport _a\nimport a\n\nclass C: ...\nA = a._A\nB = _a.f\n_C = C\n\n[case testFinalWrapped_semanal]\nfrom typing import Final\n\nx: Final = 1\ny: Final = x\nz: Final[object]\nt: Final\n[out]\nfrom basedtyping import Untyped\nfrom typing import Final\n\nx: Final[int]\ny: Final[Untyped]\nz: Final[object]\nt: Final[Untyped]\n\n[case testFinalInvalid_semanal]\nFinal = 'boom'\n\nx: Final = 1\n[out]\nFinal: str\nx: Final\n\n[case testNoFunctionNested_semanal]\nimport a\nfrom typing import Dict, Any\n\nfuncs: Dict[Any, Any]\nf = funcs[a.f]\n[out]\nfrom basedtyping import Untyped\nfrom typing import Any\n\nfuncs: dict[Any, Any]\nf: Untyped\n\n[case testAbstractMethodNameExpr]\nfrom abc import ABCMeta, abstractmethod\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def meth(self):\n        pass\n[out]\nfrom abc import ABCMeta, abstractmethod\nfrom basedtyping import Untyped\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def meth(self) -> Untyped: ...\n\n[case testAbstractMethodMemberExpr]\nimport abc\n\nclass A(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def meth(self):\n        pass\n[out]\nimport abc\nfrom basedtyping import Untyped\n\nclass A(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def meth(self) -> Untyped: ...\n\n[case testAbstractMethodMemberExpr2]\nimport abc as _abc\n\nclass A(metaclass=abc.ABCMeta):\n    @_abc.abstractmethod\n    def meth(self):\n        pass\n[out]\nimport abc as _abc\nfrom basedtyping import Untyped\n\nclass A(metaclass=abc.ABCMeta):\n    @_abc.abstractmethod\n    def meth(self) -> Untyped: ...\n\n[case testABCMeta_semanal]\nfrom base import Base\nfrom abc import abstractmethod\n\nclass C(Base):\n    @abstractmethod\n    def other(self):\n        pass\n\n[file base.py]\nfrom abc import abstractmethod, ABCMeta\n\nclass Base(metaclass=ABCMeta):\n    @abstractmethod\n    def meth(self):\n        pass\n[out]\nimport abc\nfrom abc import abstractmethod\nfrom base import Base\nfrom basedtyping import Untyped\n\nclass C(Base, metaclass=abc.ABCMeta):\n    @abstractmethod\n    def other(self) -> Untyped: ...\n\n[case testInvalidNumberOfArgsInAnnotation]\ndef f(x):\n    # type: () -> int\n    return ''\n\n[out]\nfrom basedtyping import Untyped\n\ndef f(x) -> Untyped: ...\n\n[case testFunctionPartiallyAnnotated]\ndef f(x):\n    pass\n\ndef g(x, y: str):\n    pass\n\nclass A:\n    def f(self, x):\n        pass\n\n[out]\ndef f(x): ...\ndef g(x, y: str): ...\n\nclass A:\n    def f(self, x): ...\n\n[case testExplicitAnyArg]\nfrom typing import Any\n\ndef f(x: Any):\n    pass\ndef g(x, y: Any) -> str:\n    pass\ndef h(x: Any) -> str:\n    pass\n\n[out]\nfrom typing import Any\n\ndef f(x: Any): ...\ndef g(x, y: Any) -> str: ...\ndef h(x: Any) -> str: ...\n\n[case testExplicitReturnedAny]\nfrom typing import Any\n\ndef f(x: str) -> Any:\n    pass\ndef g(x, y: str) -> Any:\n    pass\ndef h(x) -> Any:\n    pass\n\n[out]\nfrom typing import Any\n\ndef f(x: str) -> Any: ...\ndef g(x, y: str) -> Any: ...\ndef h(x) -> Any: ...\n\n[case testPlacementOfDecorators]\nclass A:\n    @property\n    def x(self):\n        self.y = 'y'\n        return 'x'\n\nclass B:\n    @property\n    def x(self):\n        return 'x'\n\n    @x.setter\n    def x(self, value):\n        self.y = 'y'\n\n[out]\nfrom basedtyping import Untyped\n\nclass A:\n    y: str\n    @property\n    def x(self) -> Untyped: ...\n\nclass B:\n    @property\n    def x(self) -> Untyped: ...\n    y: str\n    @x.setter\n    def x(self, value): ...\n\n[case testMisplacedTypeComment]\ndef f():\n    x = 0\n\n    # type: str\n    y = ''\n\n[out]\ndef f(): ...\n\n[case testConditionalImportAll_semanal]\n__all__ = ['cookielib']\n\nif object():\n    from http import cookiejar as cookielib\nelse:\n    import cookielib\n\n[out]\nimport cookielib as cookielib\n\n__all__ = ['cookielib']\n\n[case testCannotCalculateMRO_semanal]\nclass X: pass\n\nclass int(int, X):  # Cycle\n    pass\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nclass D(A, B): pass # No consistent method resolution order\nclass E(C, D): pass # Ditto\n\n[out]\nclass X: ...\nclass int(int, X): ...\nclass A: ...\nclass B(A): ...\nclass C(B): ...\nclass D(A, B): ...\nclass E(C, D): ...\n\n[case testUnreachableCode_semanal]\nMYPY = False\nclass A: pass\nif MYPY:\n    class C(A):\n        def f(self): pass\nelse:\n    def f(i):\n        return i\n\n    class C(A):\n        def g(self): pass\n[out]\nMYPY: bool\n\nclass A: ...\n\nclass C(A):\n    def f(self): ...\n\n[case testAbstractProperty1_semanal]\nimport other\nimport abc\n\nclass A:\n    @abc.abstractproperty\n    def x(self): pass\n\n[out]\nimport abc\nfrom basedtyping import Untyped\n\nclass A(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def x(self) -> Untyped: ...\n\n[case testAbstractProperty2_semanal]\nimport other\nfrom abc import abstractproperty\n\nclass A:\n    @abstractproperty\n    def x(self): pass\n\n[out]\nimport abc\nfrom basedtyping import Untyped\n\nclass A(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def x(self) -> Untyped: ...\n\n[case testAbstractProperty3_semanal]\nimport other\nfrom abc import abstractproperty as alias_name\n\nclass A:\n    @alias_name\n    def x(self): pass\n\n[out]\nimport abc\nfrom basedtyping import Untyped\n\nclass A(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def x(self) -> Untyped: ...\n\n[case testClassWithNameUntypedOrOptional]\nY = object()\n\ndef g(x=None): pass\n\nx = g()\n\nclass Untyped:\n    pass\n\ndef Optional():\n    return 0\n\n[out]\nfrom basedtyping import Untyped as _Untyped\n\nY: _Untyped\n\ndef g(x: _Untyped | None = None): ...\n\nx: _Untyped\n\nclass Untyped: ...\n\ndef Optional() -> _Untyped: ...\n\n[case testExportedNameImported]\n# modules: main a b\nfrom a import C\n\nclass D(C): pass\n\n[file a.py]\nfrom b import C\n\n[file b.py]\nclass C: pass\n\n[out]\n# main.pyi\nfrom a import C\n\nclass D(C): ...\n# a.pyi\nfrom b import C as C\n# b.pyi\nclass C: ...\n\n[case testVendoredSix]\nfrom p1.vendored import six\nfrom p1.vendor.six import foobar\nfrom p1.packages.six.moves import http_client\nfrom .packages.six.moves import queue\nfrom p1.vendored.six.moves.http_client import foo\nfrom p1.vendored.six.moves.urllib.parse import bar\n\nclass C(http_client.HTTPMessage): pass\nclass D(six.Iterator): pass\n\n[out]\nimport six\nfrom six import foobar as foobar\nfrom six.moves import http_client, queue as queue\nfrom six.moves.http_client import foo as foo\nfrom six.moves.urllib.parse import bar as bar\n\nclass C(http_client.HTTPMessage): ...\nclass D(six.Iterator): ...\n\n[case testVendoredPackage]\n# modules: main p.vendored.requests p.sub.requests\nfrom p.vendored.requests import Request\nfrom p.sub.requests import Request2\n\nx = Request()\ny = Request2()\n\n[file p/__init__.py]\n\n[file p/vendored/__init__.py]\n\n[file p/vendored/requests.py]\nclass Request:\n    pass\n\n[file p/sub/__init__.py]\n\n[file p/sub/requests.py]\nclass Request2:\n    pass\n\n[out]\n# main.pyi\nfrom basedtyping import Untyped\n\nx: Untyped\ny: Untyped\n<out/p/vendored/requests.pyi was not generated>\n# p/sub/requests.pyi\nclass Request2: ...\n\n[case testTestFiles]\n# modules: p p.x p.tests p.tests.test_foo\n\n[file p/__init__.py]\ndef f(): pass\n\n[file p/x.py]\ndef g(): pass\n\n[file p/tests/__init__.py]\n\n[file p/tests/test_foo.py]\ndef test_thing(): pass\n\n[out]\n# p/__init__.pyi\ndef f(): ...\n# p/x.pyi\ndef g(): ...\n<out/p/tests.pyi was not generated>\n<out/p/tests/test_foo.pyi was not generated>\n\n[case testTestFiles_import]\n# modules: p p.x p.tests p.tests.test_foo\n\n[file p/__init__.py]\ndef f(): pass\n\n[file p/x.py]\ndef g(): pass\n\n[file p/tests/__init__.py]\n\n[file p/tests/test_foo.py]\ndef test_thing(): pass\n\n[out]\n# p/__init__.pyi\ndef f(): ...\n# p/x.pyi\ndef g(): ...\n<out/p/tests.pyi was not generated>\n<out/p/tests/test_foo.pyi was not generated>\n\n[case testVerboseFlag]\n# Just test that --verbose does not break anything in a basic test case.\n# flags: --verbose\n\ndef f(x, y): pass\n[out]\ndef f(x, y): ...\n\n[case testImportedModuleExits_import]\n# modules: a b c\n\n[file a.py]\ndef g(): pass\n\n[file b.py]\nimport sys\ndef f(): pass\nsys.exit(1)\n\n[file c.py]\nx = 0\n\n[out]\n# a.pyi\ndef g(): ...\n# b.pyi\ndef f(): ...\n# c.pyi\nx: int\n\n[case testImportedModuleHardExits_import]\n# modules: a b c\n\n[file a.py]\ndef g(): pass\n\n[file b.py]\nimport os\ndef f(): pass\nos._exit(1)  # Kill process\n\n[file c.py]\nx = 0\n\n[out]\n# a.pyi\ndef g(): ...\n# b.pyi\ndef f(): ...\n# c.pyi\nx: int\n\n[case testImportedModuleHardExits2_import]\n# modules: p/a p/b p/c\n\n[file p/__init__.py]\n\n[file p/a.py]\ndef g(): pass\n\n[file p/b.py]\nimport os\ndef f(): pass\nos._exit(1)  # Kill process\n\n[file p/c.py]\nx = 0\n\n[out]\n# p/a.pyi\ndef g(): ...\n# p/b.pyi\ndef f(): ...\n# p/c.pyi\nx: int\n\n[case testImportedModuleHardExits3_import]\n# modules: p p/a\n\n[file p/__init__.py]\nimport os\ndef f(): pass\nos._exit(1)  # Kill process\n\n[file p/a.py]\ndef g(): pass\n\n[out]\n# p/__init__.pyi\ndef f(): ...\n# p/a.pyi\ndef g(): ...\n\n[case testImportedModuleHardExits4_import]\n# flags: -p p\n# modules: p p/a\n\n[file p/__init__.py]\ndef ff(): pass\n\n[file p/a.py]\nimport os\ndef gg(): pass\nos._exit(1)  # Kill process\n\n[out]\n# p/__init__.pyi\ndef ff(): ...\n# p/a.pyi\ndef gg(): ...\n\n[case testExportInternalImportsByDefault]\n# modules: p p/a\n\n[file p/__init__.py]\nfrom p.a import A, f\nfrom m import C\n\na: A\nc: C\nf()\n\n[file p/a.py]\nclass A: pass\ndef f(): pass\n\n[file m.py]\nclass C: pass\n\n[out]\n# p/__init__.pyi\nfrom m import C\nfrom p.a import A as A, f as f\n\na: A\nc: C\n# p/a.pyi\nclass A: ...\n\ndef f(): ...\n\n[case testNoExportOfInternalImportsIfAll_import]\n# modules: p p/a\n\n[file p/__init__.py]\nfrom p.a import A\n\n__all__ = ['a']\n\na = None  # type: A\nb = 0  # type: int\n\n[file p/a.py]\nclass A: pass\n\n[out]\n# p/__init__.pyi\nfrom p.a import A\n\n__all__ = ['a']\n\na: A\n# p/a.pyi\nclass A: ...\n\n[case testExportInternalImportsByDefaultFromUnderscorePackage]\n# modules: p\n\n[file p.py]\nfrom _p import A\nfrom _m import B\nfrom _pm import C\n\na: A\nb: B\nc: C\n\n[file _p.py]\nclass A: pass\n\n[file _m.py]\nclass B: pass\n\n[file _pm.py]\nclass C: pass\n\n[out]\nfrom _m import B\nfrom _p import A as A\nfrom _pm import C\n\na: A\nb: B\nc: C\n\n[case testDisableExportOfInternalImports]\n# flags: --export-less\n# modules: p p/a\n\n[file p/__init__.py]\nfrom p.a import A, B\nfrom m import C\n\na: A\nc: C\n\n[file p/a.py]\nclass A: pass\nclass B: pass\n\n[file m.py]\nclass C: pass\n\n[out]\n# p/__init__.pyi\nfrom m import C\nfrom p.a import A, B as B\n\na: A\nc: C\n# p/a.pyi\nclass A: ...\nclass B: ...\n\n[case testExportInternalImportsByDefaultUsingRelativeImport]\n# modules: p.a\n\n[file p/__init__.py]\n\n[file p/a.py]\nfrom .b import f\nf()\n\n[file p/b.py]\ndef f(): pass\n\n[out]\nfrom .b import f as f\n\n[case testExportInternalImportsByDefaultSkipPrivate]\n# modules: p.a\n\n[file p/__init__.py]\n\n[file p/a.py]\nfrom .b import _f, _g as _g, _i\nfrom p.b import _h\n_f()\n_h()\n\n[file p/b.py]\ndef _f(): pass\ndef _g(): pass\ndef _h(): pass\ndef _i(): pass\nx = 0\n\n[out]\n\n[case testExportInternalImportsByDefaultIncludePrivate]\n# flags: --include-private\n# modules: p.a\n\n[file p/__init__.py]\n\n[file p/a.py]\nfrom .b import _f\n_f()\n\n[file p/b.py]\ndef _f(): pass\n\n[out]\nfrom .b import _f as _f\n\n[case testHideDunderModuleAttributes]\nfrom m import (\n    __about__,\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__\n)\n\nclass A:\n    __uri__ = 0\n\n[file m.py]\n__about__ = ''\n__author__ = ''\n__copyright__ = ''\n__email__ = ''\n__license__ = ''\n__summary__ = ''\n__title__ = ''\n__uri__ = ''\n__version__ = ''\n\n[out]\nfrom m import __version__ as __version__\n\nclass A: ...\n\n\n[case testHideDunderModuleAttributesWithAll_import]\nfrom m import (\n    __about__,\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__\n)\n\n__all__ = ['__about__', '__author__', '__version__']\n\n[file m.py]\n__about__ = ''\n__author__ = ''\n__copyright__ = ''\n__email__ = ''\n__license__ = ''\n__summary__ = ''\n__title__ = ''\n__uri__ = ''\n__version__ = ''\n\n[out]\nfrom m import __about__ as __about__, __author__ as __author__, __version__ as __version__\n\n__all__ = ['__about__', '__author__', '__version__']\n\n[case testAttrsClass_semanal]\nimport attr\n\n@attr.s\nclass C:\n    x = attr.ib()\n\n[out]\nfrom basedtyping import Untyped\n\nclass C:\n    x: Untyped\n    def __init__(self, x): ...\n    def __lt__(self, other) -> Untyped: ...\n    def __le__(self, other) -> Untyped: ...\n    def __gt__(self, other) -> Untyped: ...\n    def __ge__(self, other) -> Untyped: ...\n\n[case testNamedTupleInClass]\nfrom collections import namedtuple\n\nclass C:\n    N = namedtuple('N', ['x', 'y'])\n[out]\nfrom basedtyping import Untyped\nfrom typing import NamedTuple\n\nclass C:\n    class N(NamedTuple):\n        x: Untyped\n        y: Untyped\n\n[case testImports_directImportsWithAlias]\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\n\n[out]\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\n\n[case testImports_directImportsMixed]\nimport p.a\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\nz: p.a.X\n\n[out]\nimport p.a\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\nz: p.a.X\n\n[case testImport_overwrites_directWithAlias_from]\nimport p.a as a\nfrom p import a\n\nx: a.X\n\n[out]\nfrom p import a\n\nx: a.X\n\n[case testImport_overwrites_directWithAlias_fromWithAlias]\nimport p.a as a\nfrom p import b as a\n\nx: a.X\n\n[out]\nfrom p import b as a\n\nx: a.X\n\n[case testImports_overwrites_direct_from]\nimport a\nfrom p import a\n\nx: a.X\n\n[out]\nfrom p import a\n\nx: a.X\n\n[case testImports_overwrites_direct_fromWithAlias]\nimport a\nfrom p import b as a\n\nx: a.X\n\n[out]\nfrom p import b as a\n\nx: a.X\n\n[case testImports_overwrites_from_directWithAlias]\nfrom p import a\nimport p.a as a\n\nx: a.X\n\n[out]\nimport p.a as a\n\nx: a.X\n\n[case testImports_overwrites_fromWithAlias_direct]\nimport a\nfrom p import b as a\n\nx: a.X\n\n[out]\nfrom p import b as a\n\nx: a.X\n\n[case testImports_direct]\nimport p.a\nimport pp\n\nx: a.X\ny: p.a.Y\n\n[out]\nimport p.a\n\nx: a.X\ny: p.a.Y\n\n[case testOverload_fromTypingImport]\nfrom typing import Tuple, Union, overload\n\nclass A:\n    @overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @overload\n    def f(self, x: Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: Union[int, Tuple[int, int]]) -> int:\n        pass\n\n@overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@overload\ndef f(x: Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: Union[int, Tuple[int, int]]) -> int:\n    pass\n\n\n[out]\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self, x: int, y: int) -> int: ...\n    @overload\n    def f(self, x: tuple[int, int]) -> int: ...\n\n@overload\ndef f(x: int, y: int) -> int: ...\n@overload\ndef f(x: tuple[int, int]) -> int: ...\n\n[case testOverload_importTyping]\nimport typing\n\nclass A:\n    @typing.overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @typing.overload\n    def f(self, x: typing.Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n        pass\n\n    @typing.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int:\n        ...\n\n    @typing.overload\n    @classmethod\n    def g(cls, x: typing.Tuple[int, int]) -> int:\n        ...\n\n    @classmethod\n    def g(self, *args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n        pass\n\n@typing.overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@typing.overload\ndef f(x: typing.Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n    pass\n\n\n[out]\nimport typing\n\nclass A:\n    @typing.overload\n    def f(self, x: int, y: int) -> int: ...\n    @typing.overload\n    def f(self, x: tuple[int, int]) -> int: ...\n    @typing.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int: ...\n    @typing.overload\n    @classmethod\n    def g(cls, x: tuple[int, int]) -> int: ...\n\n@typing.overload\ndef f(x: int, y: int) -> int: ...\n@typing.overload\ndef f(x: tuple[int, int]) -> int: ...\n\n\n[case testOverload_importTypingAs]\nimport typing as t\nimport typing_extensions as te\n\nclass A:\n    @t.overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @t.overload\n    def f(self, x: t.Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: typing.Union[int, t.Tuple[int, int]]) -> int:\n        pass\n\n    @t.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int:\n        ...\n\n    @t.overload\n    @classmethod\n    def g(cls, x: t.Tuple[int, int]) -> int:\n        ...\n\n    @classmethod\n    def g(self, *args: t.Union[int, t.Tuple[int, int]]) -> int:\n        pass\n\n@t.overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@t.overload\ndef f(x: t.Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: t.Union[int, t.Tuple[int, int]]) -> int:\n    pass\n\n\n\n@te.overload\ndef g(x: int, y: int) -> int:\n    ...\n\n@te.overload\ndef g(x: t.Tuple[int, int]) -> int:\n    ...\n\ndef g(*args: t.Union[int, t.Tuple[int, int]]) -> int:\n    pass\n\n[out]\nimport typing as t\nimport typing_extensions as te\n\nclass A:\n    @t.overload\n    def f(self, x: int, y: int) -> int: ...\n    @t.overload\n    def f(self, x: tuple[int, int]) -> int: ...\n    @t.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int: ...\n    @t.overload\n    @classmethod\n    def g(cls, x: tuple[int, int]) -> int: ...\n\n@t.overload\ndef f(x: int, y: int) -> int: ...\n@t.overload\ndef f(x: tuple[int, int]) -> int: ...\n@te.overload\ndef g(x: int, y: int) -> int: ...\n@te.overload\ndef g(x: tuple[int, int]) -> int: ...\n\n\n[case testProtocol_semanal]\nfrom typing import Protocol, TypeVar\n\nclass P(Protocol):\n    def f(self, x: int, y: int) -> str:\n        ...\n\nT = TypeVar('T')\nT2 = TypeVar('T2')\nclass PT(Protocol[T, T2]):\n    def f(self, x: T) -> T2:\n        ...\n\n[out]\nfrom typing import Protocol, TypeVar\n\nclass P(Protocol):\n    def f(self, x: int, y: int) -> str: ...\nT = TypeVar('T')\nT2 = TypeVar('T2')\n\nclass PT(Protocol[T, T2]):\n    def f(self, x: T) -> T2: ...\n\n[case testNonDefaultKeywordOnlyArgAfterAsterisk]\ndef func(*, non_default_kwarg: bool, default_kwarg: bool = True): ...\n[out]\ndef func(*, non_default_kwarg: bool, default_kwarg: bool = True): ...\n\n[case testNestedGenerator]\ndef f():\n    def g():\n        yield 0\n\n    return 0\n[out]\nfrom basedtyping import Untyped\n\ndef f() -> Untyped: ...\n\n\n[case testKnownMagicMethodsReturnTypes]\nclass Some:\n    def __len__(self): ...\n    def __length_hint__(self): ...\n    def __init__(self): ...\n    def __del__(self): ...\n    def __bool__(self): ...\n    def __bytes__(self): ...\n    def __format__(self, spec): ...\n    def __contains__(self, obj): ...\n    def __complex__(self): ...\n    def __int__(self): ...\n    def __float__(self): ...\n    def __index__(self): ...\n[out]\nclass Some:\n    def __len__(self) -> int: ...\n    def __length_hint__(self) -> int: ...\n    def __init__(self): ...\n    def __del__(self): ...\n    def __bool__(self) -> bool: ...\n    def __bytes__(self) -> bytes: ...\n    def __format__(self, spec) -> str: ...\n    def __contains__(self, obj) -> bool: ...\n    def __complex__(self) -> complex: ...\n    def __int__(self) -> int: ...\n    def __float__(self) -> float: ...\n    def __index__(self) -> int: ...\n"
  },
  {
    "path": "test-data/unit/stubgen.test",
    "content": "-- Test cases for stubgen that generate stubs from Python code\n\n[case testEmptyFile]\n[out]\n\n[case testSingleFunction]\ndef f():\n    x = 1\n[out]\ndef f() -> None: ...\n\n[case testTwoFunctions]\ndef f(a, b):\n    \"\"\"\n    this is a docstring\n\n    more.\n    \"\"\"\n    x = 1\ndef g(arg):\n    pass\n[out]\ndef f(a, b) -> None: ...\ndef g(arg) -> None: ...\n\n[case testDefaultArgInt]\ndef f(a, b=2): ...\ndef g(b=-1, c=0): ...\n[out]\ndef f(a, b: int = 2) -> None: ...\ndef g(b: int = -1, c: int = 0) -> None: ...\n\n[case testDefaultArgNone]\ndef f(x=None): ...\n[out]\nfrom _typeshed import Incomplete\n\ndef f(x: Incomplete | None = None) -> None: ...\n\n[case testDefaultArgBool]\ndef f(x=True, y=False): ...\n[out]\ndef f(x: bool = True, y: bool = False) -> None: ...\n\n[case testDefaultArgBool_inspect]\ndef f(x=True, y=False): ...\n[out]\ndef f(x: bool = ..., y: bool = ...): ...\n\n[case testDefaultArgStr]\ndef f(x='foo',y=\"how's quotes\"): ...\n[out]\ndef f(x: str = 'foo', y: str = \"how's quotes\") -> None: ...\n\n[case testDefaultArgStr_inspect]\ndef f(x='foo'): ...\n[out]\ndef f(x: str = ...): ...\n\n[case testDefaultArgBytes]\ndef f(x=b'foo',y=b\"what's up\",z=b'\\xc3\\xa0 la une'): ...\n[out]\ndef f(x: bytes = b'foo', y: bytes = b\"what's up\", z: bytes = b'\\xc3\\xa0 la une') -> None: ...\n\n[case testDefaultArgFloat]\ndef f(x=1.2,y=1e-6,z=0.0,w=-0.0,v=+1.0): ...\ndef g(x=float(\"nan\"), y=float(\"inf\"), z=float(\"-inf\")): ...\n[out]\ndef f(x: float = 1.2, y: float = 1e-06, z: float = 0.0, w: float = -0.0, v: float = +1.0) -> None: ...\ndef g(x=..., y=..., z=...) -> None: ...\n\n[case testDefaultArgOther]\ndef f(x=ord): ...\n[out]\ndef f(x=...) -> None: ...\n\n[case testPreserveFunctionAnnotation]\ndef f(x: Foo) -> Bar: ...\ndef g(x: Foo = Foo()) -> Bar: ...\n[out]\ndef f(x: Foo) -> Bar: ...\ndef g(x: Foo = ...) -> Bar: ...\n\n[case testPreserveFunctionAnnotationWithArgs]\ndef f(x: foo['x']) -> bar: ...\ndef g(x: foo[x]) -> bar: ...\ndef h(x: foo['x', 'y']) -> bar: ...\ndef i(x: foo[x, y]) -> bar: ...\ndef j(x: foo['x', y]) -> bar: ...\ndef k(x: foo[x, 'y']) -> bar: ...\ndef lit_str(x: Literal['str']) -> Literal['str']: ...\ndef lit_int(x: Literal[1]) -> Literal[1]: ...\n[out]\ndef f(x: foo['x']) -> bar: ...\ndef g(x: foo[x]) -> bar: ...\ndef h(x: foo['x', 'y']) -> bar: ...\ndef i(x: foo[x, y]) -> bar: ...\ndef j(x: foo['x', y]) -> bar: ...\ndef k(x: foo[x, 'y']) -> bar: ...\ndef lit_str(x: Literal['str']) -> Literal['str']: ...\ndef lit_int(x: Literal[1]) -> Literal[1]: ...\n\n[case testPreserveVarAnnotation]\nx: Foo\n[out]\nx: Foo\n\n[case testPreserveVarAnnotationWithoutQuotes]\nx: 'Foo'\n[out]\nx: Foo\n\n[case testVarArgs]\ndef f(x, *y): ...\n[out]\ndef f(x, *y) -> None: ...\n\n[case testKwVarArgs]\ndef f(x, **y): ...\n[out]\ndef f(x, **y) -> None: ...\n\n[case testVarArgsWithKwVarArgs]\ndef f(a, *b, **c): ...\ndef g(a, *b, c=1): ...\ndef h(a, *b, c=1, **d): ...\ndef i(a, *, b=1): ...\ndef j(a, *, b=1, **c): ...\n[out]\ndef f(a, *b, **c) -> None: ...\ndef g(a, *b, c: int = 1) -> None: ...\ndef h(a, *b, c: int = 1, **d) -> None: ...\ndef i(a, *, b: int = 1) -> None: ...\ndef j(a, *, b: int = 1, **c) -> None: ...\n\n[case testClass]\nclass A:\n    def f(self, x):\n        x = 1\ndef g(): ...\n[out]\nclass A:\n    def f(self, x) -> None: ...\n\ndef g() -> None: ...\n\n[case testVariables]\ni = 1\ns = 'a'\nf = 1.5\nc1 = 1j\nc2 = 0j + 1\nbl1 = True\nbl2 = False\nbts = b''\n[out]\ni: int\ns: str\nf: float\nc1: complex\nc2: complex\nbl1: bool\nbl2: bool\nbts: bytes\n\n[case testVariablesWithUnary]\ni = +-1\nf = -1.5\nc1 = -1j\nc2 = -1j + 1\nbl1 = not True\nbl2 = not not False\n[out]\ni: int\nf: float\nc1: complex\nc2: complex\nbl1: bool\nbl2: bool\n\n[case testVariablesWithUnaryWrong]\ni = not +1\nbl1 = -True\nbl2 = not -False\nbl3 = -(not False)\n[out]\nfrom _typeshed import Incomplete\n\ni: Incomplete\nbl1: Incomplete\nbl2: Incomplete\nbl3: Incomplete\n\n[case testAnnotatedVariable]\nx: int = 1\n[out]\nx: int\n\n[case testAnnotatedVariableGeneric]\nx: Foo[int, str] = ...\n[out]\nx: Foo[int, str]\n\n[case testAnnotatedVariableOldSyntax]\nx = 1  # type: int\n[out]\nx: int\n\n[case testAnnotatedVariableNone]\nx: None\n[out]\nx: None\n\n[case testAnnotatedVariableNoneOldSyntax]\nx = None  # type: None\n[out]\nx: None\n\n[case testMultipleVariable]\nx = y = 1\n[out]\nx: int\ny: int\n\n[case testClassVariable]\nclass C:\n    x = 1\n[out]\nclass C:\n    x: int\n\n[case testInitTypeAnnotationPreserved]\nclass C:\n    def __init__(self, x: str):\n        pass\n[out]\nclass C:\n    def __init__(self, x: str) -> None: ...\n\n[case testSelfAssignment]\nfrom mod import A\nfrom typing import Any, Dict, Union\nclass C:\n    def __init__(self):\n        self.a: A = A()\n        self.x = 1\n        x.y = 2\n        self.y: Dict[str, Any] = {}\n        self.z: Union[int, str, bool, None] = None\n[out]\nfrom mod import A\nfrom typing import Any\n\nclass C:\n    a: A\n    x: int\n    y: dict[str, Any]\n    z: int | str | bool | None\n    def __init__(self) -> None: ...\n\n[case testSelfAndClassBodyAssignment]\nx = 1\nclass C:\n    x = 1\n    def __init__(self):\n        self.x = 1\n        self.x = 1\n[out]\nx: int\n\nclass C:\n    x: int\n    def __init__(self) -> None: ...\n\n[case testEmptyClass]\nclass A: ...\n[out]\nclass A: ...\n\n[case testSkipPrivateFunction]\ndef _f(): ...\ndef g(): ...\n[out]\ndef g() -> None: ...\n\n[case testIncludePrivateFunction]\n# flags:  --include-private\ndef _f(): ...\ndef g(): ...\n[out]\ndef _f() -> None: ...\ndef g() -> None: ...\n\n[case testSkipPrivateMethod]\nclass A:\n    def _f(self): ...\n[out]\nclass A: ...\n\n[case testIncludePrivateMethod]\n# flags:  --include-private\nclass A:\n    def _f(self): ...\n[out]\nclass A:\n    def _f(self) -> None: ...\n\n[case testSkipPrivateVar]\n_x = 1\nclass A:\n    _y = 1\n[out]\nclass A: ...\n\n[case testIncludePrivateVar]\n# flags:  --include-private\n_x = 1\nclass A:\n    _y = 1\n[out]\n_x: int\n\nclass A:\n    _y: int\n\n[case testSpecialInternalVar]\n__all__ = []\n__author__ = ''\n__version__ = ''\n[out]\n__version__: str\n\n[case testBaseClass]\nclass A: ...\nclass B(A): ...\n[out]\nclass A: ...\nclass B(A): ...\n\n[case testDecoratedFunction]\n@decorator\ndef foo(x): ...\n[out]\ndef foo(x) -> None: ...\n\n[case testMultipleAssignment]\nx, y = 1, 2\n[out]\nfrom _typeshed import Incomplete\n\nx: Incomplete\ny: Incomplete\n\n[case testMultipleAssignmentAnnotated]\nx, y = 1, \"2\" # type: int, str\n[out]\nx: int\ny: str\n\n[case testMultipleAssignment2]\n[x, y] = 1, 2\n[out]\nfrom _typeshed import Incomplete\n\nx: Incomplete\ny: Incomplete\n\n[case testKeywordOnlyArg]\ndef f(x, *, y=1): ...\ndef g(x, *, y=1, z=2): ...\n[out]\ndef f(x, *, y: int = 1) -> None: ...\ndef g(x, *, y: int = 1, z: int = 2) -> None: ...\n\n[case testKeywordOnlyArg_inspect]\ndef f(x, *, y=1): ...\ndef g(x, *, y=1, z=2): ...\ndef h(x, *, y, z=2): ...\n[out]\ndef f(x, *, y: int = ...): ...\ndef g(x, *, y: int = ..., z: int = ...): ...\ndef h(x, *, y, z: int = ...): ...\n\n[case testProperty]\nclass A:\n    @property\n    def f(self):\n        return 1\n    @f.setter\n    def f(self, x): ...\n    @f.deleter\n    def f(self): ...\n\n    def h(self):\n        self.f = 1\n[out]\nclass A:\n    @property\n    def f(self): ...\n    @f.setter\n    def f(self, x) -> None: ...\n    @f.deleter\n    def f(self) -> None: ...\n    def h(self) -> None: ...\n\n[case testProperty_semanal]\nclass A:\n    @property\n    def f(self):\n        return 1\n    @f.setter\n    def f(self, x): ...\n    @f.deleter\n    def f(self): ...\n\n    def h(self):\n        self.f = 1\n[out]\nclass A:\n    @property\n    def f(self): ...\n    @f.setter\n    def f(self, x) -> None: ...\n    @f.deleter\n    def f(self) -> None: ...\n    def h(self) -> None: ...\n\n-- a read/write property is treated the same as an attribute\n[case testProperty_inspect]\nclass A:\n    @property\n    def f(self):\n        return 1\n    @f.setter\n    def f(self, x): ...\n\n    def h(self):\n        self.f = 1\n[out]\nfrom _typeshed import Incomplete\n\nclass A:\n    f: Incomplete\n    def h(self): ...\n\n[case testFunctoolsCachedProperty]\nimport functools\n\nclass A:\n    @functools.cached_property\n    def x(self):\n        return 'x'\n[out]\nimport functools\n\nclass A:\n    @functools.cached_property\n    def x(self): ...\n\n[case testFunctoolsCachedPropertyAlias]\nimport functools as ft\n\nclass A:\n    @ft.cached_property\n    def x(self):\n        return 'x'\n[out]\nimport functools as ft\n\nclass A:\n    @ft.cached_property\n    def x(self): ...\n\n[case testCachedProperty]\nfrom functools import cached_property\n\nclass A:\n    @cached_property\n    def x(self):\n        return 'x'\n[out]\nfrom functools import cached_property\n\nclass A:\n    @cached_property\n    def x(self): ...\n\n[case testCachedPropertyAlias]\nfrom functools import cached_property as cp\n\nclass A:\n    @cp\n    def x(self):\n        return 'x'\n[out]\nfrom functools import cached_property as cp\n\nclass A:\n    @cp\n    def x(self): ...\n\n[case testStaticMethod]\nclass A:\n    @staticmethod\n    def f(x): ...\n[out]\nclass A:\n    @staticmethod\n    def f(x) -> None: ...\n\n[case testClassMethod]\nclass A:\n    @classmethod\n    def f(cls): ...\n[out]\nclass A:\n    @classmethod\n    def f(cls) -> None: ...\n\n[case testClassMethod_inspect]\nclass A:\n    @classmethod\n    def f(cls): ...\n[out]\nclass A:\n    @classmethod\n    def f(cls): ...\n\n[case testIfMainCheck]\ndef a(): ...\nif __name__ == '__main__':\n    x = 1\n    def f(): ...\ndef b(): ...\n[out]\ndef a() -> None: ...\ndef b() -> None: ...\n\n[case testImportStar]\nfrom x import *\nfrom a.b import *\ndef f(): ...\n[out]\nfrom x import *\nfrom a.b import *\n\ndef f() -> None: ...\n\n[case testNoSpacesBetweenEmptyClasses]\nclass X:\n    def g(self): ...\nclass A: ...\nclass B: ...\nclass C:\n    def f(self): ...\n[out]\nclass X:\n    def g(self) -> None: ...\n\nclass A: ...\nclass B: ...\n\nclass C:\n    def f(self) -> None: ...\n\n[case testNoSpacesBetweenEmptyClasses_inspect]\nclass X:\n    def g(self): ...\nclass A: ...\nclass B: ...\nclass C:\n    def f(self): ...\n[out]\nclass X:\n    def g(self): ...\n\nclass A: ...\nclass B: ...\n\nclass C:\n    def f(self): ...\n\n[case testExceptionBaseClasses]\nclass A(Exception): ...\nclass B(ValueError): ...\n[out]\nclass A(Exception): ...\nclass B(ValueError): ...\n\n[case testOmitSomeSpecialMethods]\nclass A:\n    def __str__(self): ...\n    def __repr__(self): ...\n    def __eq__(self): ...\n    def __getstate__(self): ...\n    def __setstate__(self, state): ...\n[out]\nclass A:\n    def __eq__(self): ...\n\n[case testOmitSomeSpecialMethods_inspect]\nclass A:\n    def __str__(self): ...\n    def __repr__(self): ...\n    def __eq__(self): ...\n    def __getstate__(self): ...\n    def __setstate__(self, state): ...\n[out]\nclass A:\n    def __eq__(self) -> bool: ...\n\n-- Tests that will perform runtime imports of modules.\n-- Don't use `_import` suffix if there are unquoted forward references.\n\n[case testOmitDefsNotInAll_import]\n__all__ = [] + ['f']\ndef f(): ...\ndef g(): ...\n[out]\n__all__ = ['f']\n\ndef f() -> None: ...\n\n[case testOmitDefsNotInAll_semanal]\n__all__ = ['f']\ndef f(): ...\ndef g(): ...\n[out]\n__all__ = ['f']\n\ndef f() -> None: ...\n\n[case testOmitDefsNotInAll_inspect]\n__all__ = [] + ['f']\ndef f(): ...\ndef g(): ...\n[out]\n__all__ = ['f']\n\ndef f(): ...\n\n[case testVarDefsNotInAll_import]\n__all__ = [] + ['f', 'g']\ndef f(): ...\nx = 1\ny = 1\ndef g(): ...\n[out]\n__all__ = ['f', 'g']\n\ndef f() -> None: ...\ndef g() -> None: ...\n\n[case testVarDefsNotInAll_inspect]\n__all__ = [] + ['f', 'g']\ndef f(): ...\nx = 1\ny = 1\ndef g(): ...\n[out]\n__all__ = ['f', 'g']\n\ndef f(): ...\ndef g(): ...\n\n[case testIncludeClassNotInAll_import]\n__all__ = [] + ['f']\ndef f(): ...\nclass A: ...\n[out]\n__all__ = ['f']\n\ndef f() -> None: ...\n\nclass A: ...\n\n[case testIncludeClassNotInAll_inspect]\n__all__ = [] + ['f']\ndef f(): ...\nclass A: ...\n[out]\n__all__ = ['f']\n\ndef f(): ...\n\nclass A: ...\n\n[case testAllAndClass_import]\n__all__ = ['A']\nclass A:\n    x = 1\n    def f(self): ...\n[out]\n__all__ = ['A']\n\nclass A:\n    x: int\n    def f(self) -> None: ...\n\n[case testSkipMultiplePrivateDefs]\nclass A: ...\n_x = 1\n_y = 1\n_z = 1\nclass C: ...\n[out]\nclass A: ...\nclass C: ...\n\n[case testIncludeMultiplePrivateDefs]\n# flags:  --include-private\nclass A: ...\n_x = 1\n_y = 1\n_z = 1\nclass C: ...\n[out]\nclass A: ...\n\n_x: int\n_y: int\n_z: int\n\nclass C: ...\n\n[case testIncludeFromImportIfInAll_import]\nfrom re import match, search, sub\n__all__ = ['match', 'sub', 'x']\nx = 1\n[out]\nfrom re import match as match, sub as sub\n\n__all__ = ['match', 'sub', 'x']\n\nx: int\n\n[case testExportModule_import]\nimport re\n__all__ = ['re', 'x']\nx = 1\ny = 2\n[out]\nimport re as re\n\n__all__ = ['re', 'x']\n\nx: int\n\n[case testExportModule2_import]\nimport re\n__all__ = ['re', 'x']\nx = 1\ny = 2\n[out]\nimport re as re\n\n__all__ = ['re', 'x']\n\nx: int\n\n[case testExportModuleAs_import]\nimport re as rex\n__all__ = ['rex', 'x']\nx = 1\ny = 2\n[out]\nimport re as rex\n\n__all__ = ['rex', 'x']\n\nx: int\n\n[case testExportModuleInPackage_import]\nimport urllib.parse as p\n__all__ = ['p']\n[out]\nimport urllib.parse as p\n\n__all__ = ['p']\n\n[case testExportPackageOfAModule_import]\nimport urllib.parse\n__all__ = ['urllib']\n\n[out]\nimport urllib as urllib\n\n__all__ = ['urllib']\n\n[case testRelativeImportAll]\nfrom .x import *\n[out]\nfrom .x import *\n\n[case testCommentForUndefinedName_import]\n__all__ = ['f', 'x', 'C', 'g']\ndef f(): ...\nx = 1\nclass C:\n    def g(self): ...\n[out]\n__all__ = ['f', 'x', 'C', 'g']\n\ndef f() -> None: ...\n\nx: int\n\nclass C:\n    def g(self) -> None: ...\n\n# Names in __all__ with no definition:\n#   g\n\n[case testCommentForUndefinedName_inspect]\n__all__ = ['f', 'x', 'C', 'g']\ndef f(): ...\nx = 1\nclass C:\n    def g(self): ...\n[out]\n__all__ = ['f', 'x', 'C', 'g']\n\ndef f(): ...\n\nx: int\n\nclass C:\n    def g(self): ...\n\n# Names in __all__ with no definition:\n#   g\n\n[case testIgnoreSlots]\nclass A:\n    __slots__ = ()\n[out]\nclass A: ...\n\n[case testSkipPrivateProperty]\nclass A:\n    @property\n    def _foo(self): ...\n[out]\nclass A: ...\n\n[case testSkipPrivateProperty_inspect]\nclass A:\n    @property\n    def _foo(self): ...\n[out]\nclass A: ...\n\n[case testIncludePrivateProperty]\n# flags:  --include-private\nclass A:\n    @property\n    def _foo(self): ...\n[out]\nclass A:\n    @property\n    def _foo(self) -> None: ...\n\n[case testIncludePrivateProperty_inspect]\n# flags:  --include-private\nclass A:\n    @property\n    def _foo(self): ...\n[out]\nclass A:\n    @property\n    def _foo(self): ...\n\n[case testSkipPrivateStaticAndClassMethod]\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n[out]\nclass A: ...\n\n[case testSkipPrivateStaticAndClassMethod_inspect]\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n[out]\nclass A: ...\n\n[case testIncludePrivateStaticAndClassMethod]\n# flags:  --include-private\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n[out]\nclass A:\n    @staticmethod\n    def _foo() -> None: ...\n    @classmethod\n    def _bar(cls) -> None: ...\n\n[case testIncludePrivateStaticAndClassMethod_inspect]\n# flags:  --include-private\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n[out]\nclass A:\n    @staticmethod\n    def _foo(): ...\n    @classmethod\n    def _bar(cls): ...\n\n[case testNamedtuple]\nimport collections, typing, x\nX = collections.namedtuple('X', ['a', 'b'])\nY = typing.NamedTuple('Y', [('a', int), ('b', str)])\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\nclass Y(NamedTuple):\n    a: int\n    b: str\n\n[case testNamedTupleClassSyntax_semanal]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    x: int\n    y: str = 'a'\n\nclass B(A):\n    z1: str\n    z2 = 1\n    z3: str = 'b'\n\nclass RegularClass:\n    x: int\n    y: str = 'a'\n    class NestedNamedTuple(NamedTuple):\n        x: int\n        y: str = 'a'\n    z: str = 'b'\n[out]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    x: int\n    y: str = ...\n\nclass B(A):\n    z1: str\n    z2: int\n    z3: str\n\nclass RegularClass:\n    x: int\n    y: str\n    class NestedNamedTuple(NamedTuple):\n        x: int\n        y: str = ...\n    z: str\n\n\n[case testNestedClassInNamedTuple_semanal-xfail]\nfrom typing import NamedTuple\n\n# TODO: make sure that nested classes in `NamedTuple` are supported:\nclass NamedTupleWithNestedClass(NamedTuple):\n    class Nested:\n        x: int\n        y: str = 'a'\n[out]\nfrom typing import NamedTuple\n\nclass NamedTupleWithNestedClass(NamedTuple):\n    class Nested:\n        x: int\n        y: str\n\n[case testEmptyNamedtuple]\nimport collections, typing\nX = collections.namedtuple('X', [])\nY = typing.NamedTuple('Y', [])\n[out]\nfrom typing import NamedTuple\n\nclass X(NamedTuple): ...\nclass Y(NamedTuple): ...\n\n[case testNamedtupleAltSyntax]\nfrom collections import namedtuple, xx\nX = namedtuple('X', 'a b')\nxx\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\n[case testNamedtupleAltSyntaxUsingComma]\nfrom collections import namedtuple, xx\nX = namedtuple('X', 'a,    b')\nxx\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\n[case testNamedtupleAltSyntaxUsingMultipleCommas]\nfrom collections import namedtuple, xx\nX = namedtuple('X', 'a,,   b')\nxx\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\n[case testNamedtupleWithUnderscore]\nfrom collections import namedtuple as _namedtuple\nfrom typing import NamedTuple as _NamedTuple\ndef f(): ...\nX = _namedtuple('X', 'a b')\nY = _NamedTuple('Y', [('a', int), ('b', str)])\ndef g(): ...\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\ndef f() -> None: ...\n\nclass X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\nclass Y(NamedTuple):\n    a: int\n    b: str\n\ndef g() -> None: ...\n\n[case testNamedtupleBaseClass]\nimport collections, x\n_X = collections.namedtuple('_X', ['a', 'b'])\nclass Y(_X): ...\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass _X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\nclass Y(_X): ...\n\n[case testNamedtupleAltSyntaxFieldsTuples]\nfrom collections import namedtuple, xx\nfrom typing import NamedTuple\nX = namedtuple('X', ())\nY = namedtuple('Y', ('a',))\nZ = namedtuple('Z', ('a', 'b', 'c', 'd', 'e'))\nxx\nR = NamedTuple('R', ())\nS = NamedTuple('S', (('a', int),))\nT = NamedTuple('T', (('a', int), ('b', str)))\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple): ...\n\nclass Y(NamedTuple):\n    a: Incomplete\n\nclass Z(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n    c: Incomplete\n    d: Incomplete\n    e: Incomplete\n\nclass R(NamedTuple): ...\n\nclass S(NamedTuple):\n    a: int\n\nclass T(NamedTuple):\n    a: int\n    b: str\n\n[case testDynamicNamedTuple]\nfrom collections import namedtuple\nfrom typing import NamedTuple\nN = namedtuple('N', ['x', 'y'] + ['z'])\nM = NamedTuple('M', [('x', int), ('y', str)] + [('z', float)])\nclass X(namedtuple('X', ['a', 'b'] + ['c'])): ...\n[out]\nfrom _typeshed import Incomplete\n\nN: Incomplete\nM: Incomplete\n\nclass X(Incomplete): ...\n\n[case testNamedTupleInClassBases]\nimport collections, typing\nfrom collections import namedtuple\nfrom typing import NamedTuple\nclass X(namedtuple('X', ['a', 'b'])): ...\nclass Y(NamedTuple('Y', [('a', int), ('b', str)])): ...\nclass R(collections.namedtuple('R', ['a', 'b'])): ...\nclass S(typing.NamedTuple('S', [('a', int), ('b', str)])): ...\n[out]\nimport typing\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple('X', [('a', Incomplete), ('b', Incomplete)])): ...\nclass Y(NamedTuple('Y', [('a', int), ('b', str)])): ...\nclass R(NamedTuple('R', [('a', Incomplete), ('b', Incomplete)])): ...\nclass S(typing.NamedTuple('S', [('a', int), ('b', str)])): ...\n\n[case testNotNamedTuple]\nfrom not_collections import namedtuple\nfrom not_typing import NamedTuple\nfrom collections import notnamedtuple\nfrom typing import NotNamedTuple\nX = namedtuple('X', ['a', 'b'])\nY = notnamedtuple('Y', ['a', 'b'])\nZ = NamedTuple('Z', [('a', int), ('b', str)])\nW = NotNamedTuple('W', [('a', int), ('b', str)])\n[out]\nfrom _typeshed import Incomplete\n\nX: Incomplete\nY: Incomplete\nZ: Incomplete\nW: Incomplete\n\n[case testNamedTupleFromImportAlias]\nimport collections as c\nimport typing as t\nimport typing_extensions as te\nX = c.namedtuple('X', ['a', 'b'])\nY = t.NamedTuple('Y', [('a', int), ('b', str)])\nZ = te.NamedTuple('Z', [('a', int), ('b', str)])\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    a: Incomplete\n    b: Incomplete\n\nclass Y(NamedTuple):\n    a: int\n    b: str\n\nclass Z(NamedTuple):\n    a: int\n    b: str\n\n[case testArbitraryBaseClass]\nimport x\nclass D(x.C): ...\n[out]\nimport x\n\nclass D(x.C): ...\n\n[case testArbitraryBaseClass2]\nimport x.y\nclass D(x.y.C): ...\n[out]\nimport x.y\n\nclass D(x.y.C): ...\n\n[case testUnqualifiedArbitraryBaseClassWithNoDef]\nclass A(int): ...\n[out]\nclass A(int): ...\n\n[case testUnqualifiedArbitraryBaseClass]\nfrom x import X\nclass A(X): ...\n[out]\nfrom x import X\n\nclass A(X): ...\n\n[case testUnqualifiedArbitraryBaseClassWithImportAs]\nfrom x import X as _X\nclass A(_X): ...\n[out]\nfrom x import X as _X\n\nclass A(_X): ...\n\n[case testGenericClass]\nclass D(Generic[T]): ...\n[out]\nclass D(Generic[T]): ...\n\n[case testGenericClass_semanal]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass D(Generic[T]): ...\n[out]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass D(Generic[T]): ...\n\n[case testGenericClassTypeVarTuple]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\nTs = TypeVarTuple('Ts')\nclass D(Generic[Unpack[Ts]]): ...\ndef callback(func: Callable[[Unpack[Ts]], None], *args: Unpack[Ts]) -> None: ...\n[out]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple('Ts')\n\nclass D(Generic[Unpack[Ts]]): ...\n\ndef callback(func: Callable[[Unpack[Ts]], None], *args: Unpack[Ts]) -> None: ...\n\n[case testGenericClassTypeVarTuple_semanal]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\nTs = TypeVarTuple('Ts')\nclass D(Generic[Unpack[Ts]]): ...\ndef callback(func: Callable[[Unpack[Ts]], None], *args: Unpack[Ts]) -> None: ...\n[out]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple('Ts')\n\nclass D(Generic[Unpack[Ts]]): ...\n\ndef callback(func: Callable[[Unpack[Ts]], None], *args: Unpack[Ts]) -> None: ...\n\n[case testGenericClassTypeVarTuplePy311]\n# flags: --python-version=3.11\nfrom typing import Generic, TypeVarTuple\nTs = TypeVarTuple('Ts')\nclass D(Generic[*Ts]): ...\ndef callback(func: Callable[[*Ts], None], *args: *Ts) -> None: ...\n[out]\nfrom typing import Generic, TypeVarTuple\n\nTs = TypeVarTuple('Ts')\n\nclass D(Generic[*Ts]): ...\n\ndef callback(func: Callable[[*Ts], None], *args: *Ts) -> None: ...\n\n[case testGenericClassTypeVarTuplePy311_semanal]\n# flags: --python-version=3.11\nfrom typing import Generic, TypeVarTuple\nTs = TypeVarTuple('Ts')\nclass D(Generic[*Ts]): ...\ndef callback(func: Callable[[*Ts], None], *args: *Ts) -> None: ...\n[out]\nfrom typing import Generic, TypeVarTuple\n\nTs = TypeVarTuple('Ts')\n\nclass D(Generic[*Ts]): ...\n\ndef callback(func: Callable[[*Ts], None], *args: *Ts) -> None: ...\n\n[case testObjectBaseClass]\nclass A(object): ...\n[out]\nclass A: ...\n\n[case testObjectBaseClassWithImport]\nimport builtins as b\nclass A(b.object): ...\n[out]\nclass A: ...\n\n[case testEmptyLines]\ndef x(): ...\ndef f():\n    class A:\n        def f(self):\n            self.x = 1\ndef g(): ...\n[out]\ndef x() -> None: ...\ndef f() -> None: ...\ndef g() -> None: ...\n\n[case testNestedClass]\nclass A:\n    class B:\n        x = 1\n        def f(self): ...\n    def g(self): ...\n[out]\nclass A:\n    class B:\n        x: int\n        def f(self) -> None: ...\n    def g(self) -> None: ...\n\n[case testExportViaRelativeImport]\nfrom .api import get\n[out]\nfrom .api import get as get\n\n[case testExportViaRelativePackageImport]\nfrom .packages.urllib3.contrib import parse\n[out]\nfrom .packages.urllib3.contrib import parse as parse\n\n[case testNoExportViaRelativeImport]\nfrom . import get\nget()\n[out]\n\n[case testRelativeImportAndBase]\nfrom .x import X\nclass A(X):\n     pass\n[out]\nfrom .x import X\n\nclass A(X): ...\n\n[case testDuplicateDef]\ndef syslog(a): pass\ndef syslog(a): pass\n[out]\ndef syslog(a) -> None: ...\n\n[case testAsyncAwait_fast_parser]\nasync def f(a):\n   x = await y\n[out]\nasync def f(a) -> None: ...\n\n[case testInferOptionalOnlyFunc]\nclass A:\n    x = None\n    def __init__(self, a=None):\n        self.x = []\n    def method(self, a=None):\n        self.x = []\n[out]\nfrom _typeshed import Incomplete\n\nclass A:\n    x: Incomplete\n    def __init__(self, a: Incomplete | None = None) -> None: ...\n    def method(self, a: Incomplete | None = None) -> None: ...\n\n[case testAnnotationImportsFrom]\nimport foo\nfrom collections import defaultdict\nx: defaultdict\n\n[out]\nfrom collections import defaultdict\n\nx: defaultdict\n\n[case testAnnotationImports]\nimport foo\nimport collections\nx: collections.defaultdict\n\n[out]\nimport collections\n\nx: collections.defaultdict\n\n\n[case testAnnotationImports2]\nfrom typing import List\nimport collections\nx: List[collections.defaultdict]\n\n[out]\nimport collections\n\nx: list[collections.defaultdict]\n\n\n[case testAnnotationFwRefs]\nx: C\n\nclass C:\n    attr: C\n\ny: C\n[out]\nx: C\n\nclass C:\n    attr: C\n\ny: C\n\n[case testTypeVarPreserved]\ntv = TypeVar('tv')\nps = ParamSpec('ps')\ntvt = TypeVarTuple('tvt')\n\n[out]\nfrom typing import TypeVar\nfrom typing_extensions import ParamSpec, TypeVarTuple\n\ntv = TypeVar('tv')\nps = ParamSpec('ps')\ntvt = TypeVarTuple('tvt')\n\n[case testTypeVarArgsPreserved]\ntv = TypeVar('tv', int, str)\n\n[out]\nfrom typing import TypeVar\n\ntv = TypeVar('tv', int, str)\n\n[case testTypeVarNamedArgsPreserved]\ntv = TypeVar('tv', bound=bool, covariant=True)\nps = ParamSpec('ps', bound=bool, covariant=True)\n\n[out]\nfrom typing import TypeVar\nfrom typing_extensions import ParamSpec\n\ntv = TypeVar('tv', bound=bool, covariant=True)\nps = ParamSpec('ps', bound=bool, covariant=True)\n\n[case TypeVarImportAlias]\nfrom typing import TypeVar as t_TV, ParamSpec as t_PS\nfrom typing_extensions import TypeVar as te_TV, TypeVarTuple as te_TVT\nfrom x import TypeVar as x_TV\n\nT = t_TV('T')\nU = te_TV('U')\nV = x_TV('V')\n\nPS = t_PS('PS')\nTVT = te_TVT('TVT')\n\n[out]\nfrom _typeshed import Incomplete\nfrom typing import ParamSpec as t_PS, TypeVar as t_TV\nfrom typing_extensions import TypeVar as te_TV, TypeVarTuple as te_TVT\n\nT = t_TV('T')\nU = te_TV('U')\nV: Incomplete\nPS = t_PS('PS')\nTVT = te_TVT('TVT')\n\n[case testTypeVarFromImportAlias]\nimport typing as t\nimport typing_extensions as te\nimport x\n\nT = t.TypeVar('T')\nU = te.TypeVar('U')\nV = x.TypeVar('V')\n\nPS = t.ParamSpec('PS')\nTVT = te.TypeVarTuple('TVT')\n\n[out]\nimport typing as t\nimport typing_extensions as te\nfrom _typeshed import Incomplete\n\nT = t.TypeVar('T')\nU = te.TypeVar('U')\nV: Incomplete\nPS = t.ParamSpec('PS')\nTVT = te.TypeVarTuple('TVT')\n\n[case testTypeAliasPreserved]\nalias = str\n\n[out]\nalias = str\n\n[case testDeepTypeAliasPreserved]\n\nalias = Dict[str, List[str]]\n\n[out]\nalias = Dict[str, List[str]]\n\n[case testDeepGenericTypeAliasPreserved]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nalias = Union[T, List[T]]\n\n[out]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nalias = Union[T, List[T]]\n\n[case testEllipsisAliasPreserved]\n\nalias = Tuple[int, ...]\n\n[out]\nalias = Tuple[int, ...]\n\n[case testCallableAliasPreserved]\n\nalias1 = Callable[..., int]\nalias2 = Callable[[str, bool], None]\n\n[out]\nalias1 = Callable[..., int]\nalias2 = Callable[[str, bool], None]\n\n[case testAliasPullsImport]\nfrom module import Container\n\nalias = Container[Any]\n\n[out]\nfrom module import Container\nfrom typing import Any\n\nalias = Container[Any]\n\n[case testAliasExceptions]\nnoalias1 = None\nnoalias2 = ...\nnoalias3 = True\n\n[out]\nfrom _typeshed import Incomplete\n\nnoalias1: Incomplete\nnoalias2: Incomplete\nnoalias3: bool\n\n[case testComplexAlias]\n# modules: main a\n\nfrom a import valid\n\ndef func() -> int:\n    return 2\n\naliased_func = func\nint_value = 1\n\nclass A:\n    cls_var = valid\n\n    def __init__(self, arg: str) -> None:\n        self.self_var = arg\n\n    def meth(self) -> None:\n        func_value = int_value\n\n    alias_meth = meth\n    alias_func = func\n    alias_alias_func = aliased_func\n    int_value = int_value\n\n[file a.py]\nvalid : list[int] = [1, 2, 3]\n\n\n[out]\n# main.pyi\nfrom _typeshed import Incomplete\nfrom a import valid\n\ndef func() -> int: ...\naliased_func = func\nint_value: int\n\nclass A:\n    cls_var = valid\n    self_var: Incomplete\n    def __init__(self, arg: str) -> None: ...\n    def meth(self) -> None: ...\n    alias_meth = meth\n    alias_func = func\n    alias_alias_func = aliased_func\n    int_value = int_value\n# a.pyi\nvalid: list[int]\n\n-- More features/fixes:\n--   do not export deleted names\n\n[case testFunctionNoReturnInfersReturnNone]\ndef f():\n    x = 1\n[out]\ndef f() -> None: ...\n\n[case testFunctionReturnNoReturnType]\ndef f():\n    return 1\ndef g():\n    return\n[out]\ndef f(): ...\ndef g() -> None: ...\n\n[case testFunctionEllipsisInfersReturnNone]\ndef f(): ...\n[out]\ndef f() -> None: ...\n\n[case testFunctionYields]\ndef f():\n    yield 123\ndef g():\n    x = yield\ndef h1():\n    yield\n    return\ndef h2():\n    yield\n    return \"abc\"\ndef h3():\n    yield\n    return None\ndef all():\n    x = yield 123\n    return \"abc\"\n[out]\nfrom _typeshed import Incomplete\nfrom collections.abc import Generator\n\ndef f() -> Generator[Incomplete]: ...\ndef g() -> Generator[None, Incomplete]: ...\ndef h1() -> Generator[None]: ...\ndef h2() -> Generator[None, None, Incomplete]: ...\ndef h3() -> Generator[None]: ...\ndef all() -> Generator[Incomplete, Incomplete, Incomplete]: ...\n\n[case testFunctionYieldsNone]\ndef f():\n    yield\ndef g():\n    yield None\n\n[out]\nfrom collections.abc import Generator\n\ndef f() -> Generator[None]: ...\ndef g() -> Generator[None]: ...\n\n[case testGeneratorAlreadyDefined]\nclass Generator:\n    pass\n\ndef f():\n    yield 123\n[out]\nfrom _typeshed import Incomplete\nfrom collections.abc import Generator as _Generator\n\nclass Generator: ...\n\ndef f() -> _Generator[Incomplete]: ...\n\n[case testGeneratorYieldFrom]\ndef g1():\n    yield from x\ndef g2():\n    y = yield from x\ndef g3():\n    yield from x\n    return\ndef g4():\n    yield from x\n    return None\ndef g5():\n    yield from x\n    return z\n\n[out]\nfrom _typeshed import Incomplete\nfrom collections.abc import Generator\n\ndef g1() -> Generator[Incomplete, Incomplete]: ...\ndef g2() -> Generator[Incomplete, Incomplete]: ...\ndef g3() -> Generator[Incomplete, Incomplete]: ...\ndef g4() -> Generator[Incomplete, Incomplete]: ...\ndef g5() -> Generator[Incomplete, Incomplete, Incomplete]: ...\n\n[case testGeneratorYieldAndYieldFrom]\ndef g1():\n    yield x1\n    yield from x2\ndef g2():\n    yield x1\n    y = yield from x2\ndef g3():\n    y = yield x1\n    yield from x2\ndef g4():\n    yield x1\n    yield from x2\n    return\ndef g5():\n    yield x1\n    yield from x2\n    return None\ndef g6():\n    yield x1\n    yield from x2\n    return z\ndef g7():\n    yield None\n    yield from x2\n\n[out]\nfrom _typeshed import Incomplete\nfrom collections.abc import Generator\n\ndef g1() -> Generator[Incomplete, Incomplete]: ...\ndef g2() -> Generator[Incomplete, Incomplete]: ...\ndef g3() -> Generator[Incomplete, Incomplete]: ...\ndef g4() -> Generator[Incomplete, Incomplete]: ...\ndef g5() -> Generator[Incomplete, Incomplete]: ...\ndef g6() -> Generator[Incomplete, Incomplete, Incomplete]: ...\ndef g7() -> Generator[Incomplete, Incomplete]: ...\n\n[case testCallable]\nfrom typing import Callable\n\nx: Callable[[int, int], int]\n[out]\nfrom typing import Callable\n\nx: Callable[[int, int], int]\n\n[case testAwaitDef]\nclass F:\n    async def f(self):\n        return 1\n\nasync def g():\n    return 2\n[out]\nclass F:\n    async def f(self): ...\n\nasync def g(): ...\n\n[case testCoroutineImportAsyncio]\nimport asyncio\n\nclass F:\n    @asyncio.coroutine\n    def f(self):\n        return 1\n\n@asyncio.coroutine\ndef g():\n    return 2\n\n@asyncio.coroutine\ndef h():\n    return 3\n[out]\nimport asyncio\n\nclass F:\n    @asyncio.coroutine\n    def f(self): ...\n\n@asyncio.coroutine\ndef g(): ...\n@asyncio.coroutine\ndef h(): ...\n\n[case testCoroutineImportAsyncioCoroutines]\nimport asyncio.coroutines\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self):\n        return 1\n\n@asyncio.coroutines.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio.coroutines\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self): ...\n\n@asyncio.coroutines.coroutine\ndef g(): ...\n\n[case testCoroutineImportAsyncioCoroutinesSub]\nimport asyncio\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self):\n        return 1\n\n@asyncio.coroutines.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio\n\nclass F:\n    @asyncio.coroutines.coroutine\n    def f(self): ...\n\n@asyncio.coroutines.coroutine\ndef g(): ...\n\n[case testCoroutineImportTypes]\nimport types\n\nclass F:\n    @types.coroutine\n    def f(self):\n        return 1\n\n@types.coroutine\ndef g():\n    return 2\n[out]\nimport types\n\nclass F:\n    @types.coroutine\n    def f(self): ...\n\n@types.coroutine\ndef g(): ...\n\n[case testCoroutineFromAsyncioImportCoroutine]\nfrom asyncio import coroutine\n\nclass F:\n    @coroutine\n    def f(self):\n        return 1\n\n@coroutine\ndef g():\n    return 2\n[out]\nfrom asyncio import coroutine\n\nclass F:\n    @coroutine\n    def f(self): ...\n\n@coroutine\ndef g(): ...\n\n[case testCoroutineFromAsyncioCoroutinesImportCoroutine]\nfrom asyncio.coroutines import coroutine\n\nclass F:\n    @coroutine\n    def f(self):\n        return 1\n\n@coroutine\ndef g():\n    return 2\n[out]\nfrom asyncio.coroutines import coroutine\n\nclass F:\n    @coroutine\n    def f(self): ...\n\n@coroutine\ndef g(): ...\n\n[case testCoroutineFromTypesImportCoroutine]\nfrom types import coroutine\n\nclass F:\n    @coroutine\n    def f(self):\n        return 1\n\n@coroutine\ndef g():\n    return 2\n[out]\nfrom types import coroutine\n\nclass F:\n    @coroutine\n    def f(self): ...\n\n@coroutine\ndef g(): ...\n\n[case testCoroutineFromAsyncioImportCoroutineAsC]\nfrom asyncio import coroutine as c\n\nclass F:\n    @c\n    def f(self):\n        return 1\n\n@c\ndef g():\n    return 2\n[out]\nfrom asyncio import coroutine as c\n\nclass F:\n    @c\n    def f(self): ...\n\n@c\ndef g(): ...\n\n[case testCoroutineFromAsyncioCoroutinesImportCoroutineAsC]\nfrom asyncio.coroutines import coroutine as c\n\nclass F:\n    @c\n    def f(self):\n        return 1\n\n@c\ndef g():\n    return 2\n[out]\nfrom asyncio.coroutines import coroutine as c\n\nclass F:\n    @c\n    def f(self): ...\n\n@c\ndef g(): ...\n\n[case testCoroutineFromTypesImportCoroutineAsC]\nfrom types import coroutine as c\n\nclass F:\n    @c\n    def f(self):\n        return 1\n\n@c\ndef g():\n    return 2\n[out]\nfrom types import coroutine as c\n\nclass F:\n    @c\n    def f(self): ...\n\n@c\ndef g(): ...\n\n[case testCoroutineImportAsyncioAsA]\nimport asyncio as a\n\nclass F:\n    @a.coroutine\n    def f(self):\n        return 1\n\n@a.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio as a\n\nclass F:\n    @a.coroutine\n    def f(self): ...\n\n@a.coroutine\ndef g(): ...\n\n[case testCoroutineImportAsyncioCoroutinesAsC]\nimport asyncio.coroutines as c\n\nclass F:\n    @c.coroutine\n    def f(self):\n        return 1\n\n@c.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio.coroutines as c\n\nclass F:\n    @c.coroutine\n    def f(self): ...\n\n@c.coroutine\ndef g(): ...\n\n[case testCoroutineImportAsyncioCoroutinesSubAsA]\nimport asyncio as a\n\nclass F:\n    @a.coroutines.coroutine\n    def f(self):\n        return 1\n\n@a.coroutines.coroutine\ndef g():\n    return 2\n[out]\nimport asyncio as a\n\nclass F:\n    @a.coroutines.coroutine\n    def f(self): ...\n\n@a.coroutines.coroutine\ndef g(): ...\n\n[case testCoroutineImportTypesAsT]\nimport types as t\n\nclass F:\n    @t.coroutine\n    def f(self):\n        return 1\n\n@t.coroutine\ndef g():\n    return 2\n[out]\nimport types as t\n\nclass F:\n    @t.coroutine\n    def f(self): ...\n\n@t.coroutine\ndef g(): ...\n\n\n-- Tests for stub generation from semantically analyzed trees.\n-- These tests are much slower, so use the `_semanal` suffix only when needed.\n\n[case testNestedClass_semanal]\nclass Outer:\n    class Inner:\n        pass\n\nA = Outer.Inner\n[out]\nclass Outer:\n    class Inner: ...\nA = Outer.Inner\n\n-- needs improvement\n[case testNestedClass_inspect]\nclass Outer:\n    class Inner:\n        pass\n\nA = Outer.Inner\n[out]\nclass Outer:\n    class Inner: ...\n\nclass A: ...\n\n[case testFunctionAlias_semanal]\nfrom asyncio import coroutine\n\n@coroutine\ndef start_server():\n    ...\n\nstart = start_server\n[out]\nfrom asyncio import coroutine\n\n@coroutine\ndef start_server() -> None: ...\nstart = start_server\n\n[case testModuleAlias_semanal]\nimport a\n\nb = a\n[file a.py]\nx = 1\n[out]\nimport a\n\nb = a\n\n[case testBadAliasNested_semanal]\nimport a\n\nx = registry[a.f]\n[file a.py]\ndef f(): ...\n[out]\nfrom _typeshed import Incomplete\n\nx: Incomplete\n\n[case testCrossModuleClass_semanal]\nimport a\n\nclass C:\n    x: A\n    def f(self) -> A: ...\nA = a.A\n[file a.py]\nclass A: ...\n[out]\nimport a\n\nclass C:\n    x: A\n    def f(self) -> A: ...\nA = a.A\n\n[case testCrossModuleFunction_semanal]\nimport a\ng = a.f\n[file a.py]\ndef f(): ...\n[out]\nimport a\n\ng = a.f\n\n[case testPrivateAliasesExcluded_semanal]\nimport a, _a\n\nclass C: ...\n\nA = a._A\nB = _a.f\n_C = C\n[file a.py]\nclass _A: ...\n[file _a.py]\ndef f(): ...\n[out]\nfrom _typeshed import Incomplete\n\nclass C: ...\n\nA: Incomplete\nB: Incomplete\n\n[case testPrivateAliasesIncluded_semanal]\n# flags: --include-private\nimport a, _a\n\nclass C: ...\n\nA = a._A\nB = _a.f\n_C = C\n[file a.py]\nclass _A: ...\n[file _a.py]\ndef f(): ...\n[out]\nimport _a\nimport a\n\nclass C: ...\nA = a._A\nB = _a.f\n_C = C\n\n[case testFinalWrapped_semanal]\nfrom typing import Final\n\nx: Final = 1\ny: Final = x\nz: Final[object]\nt: Final\n[out]\nfrom _typeshed import Incomplete\nfrom typing import Final\n\nx: Final[int]\ny: Final[Incomplete]\nz: Final[object]\nt: Final[Incomplete]\n\n[case testFinalInvalid_semanal]\nFinal = 'boom'\n\nx: Final = 1\n[out]\nFinal: str\nx: Final\n\n[case testNoFunctionNested_semanal]\nimport a\nfrom typing import Dict, Any\n\nfuncs: Dict[Any, Any]\nf = funcs[a.f]\n[out]\nfrom _typeshed import Incomplete\nfrom typing import Any\n\nfuncs: dict[Any, Any]\nf: Incomplete\n\n[case testAbstractMethodNameExpr]\nfrom abc import ABCMeta, abstractmethod\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def meth(self):\n        pass\n[out]\nfrom abc import ABCMeta, abstractmethod\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def meth(self): ...\n\n[case testAbstractMethodMemberExpr]\nimport abc\n\nclass A(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def meth(self):\n        pass\n[out]\nimport abc\n\nclass A(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def meth(self): ...\n\n[case testAbstractMethodMemberExpr2]\nimport abc as _abc\n\nclass A(metaclass=abc.ABCMeta):\n    @_abc.abstractmethod\n    def meth(self):\n        pass\n[out]\nimport abc as _abc\n\nclass A(metaclass=abc.ABCMeta):\n    @_abc.abstractmethod\n    def meth(self): ...\n\n[case testABCMeta_semanal]\nfrom base import Base\nfrom abc import abstractmethod\n\nclass C(Base):\n    @abstractmethod\n    def other(self):\n        pass\n\n[file base.py]\nfrom abc import abstractmethod, ABCMeta\n\nclass Base(metaclass=ABCMeta):\n    @abstractmethod\n    def meth(self):\n        pass\n[out]\nimport abc\nfrom abc import abstractmethod\nfrom base import Base\n\nclass C(Base, metaclass=abc.ABCMeta):\n    @abstractmethod\n    def other(self): ...\n\n[case testInvalidNumberOfArgsInAnnotation]\ndef f(x):\n    # type: () -> int\n    return ''\n\n[out]\ndef f(x): ...\n\n[case testFunctionPartiallyAnnotated]\ndef f(x) -> None:\n    pass\n\ndef g(x, y: str):\n    pass\n\nclass A:\n    def f(self, x) -> None:\n        pass\n\n[out]\ndef f(x) -> None: ...\ndef g(x, y: str): ...\n\nclass A:\n    def f(self, x) -> None: ...\n\n-- Same as above\n[case testFunctionPartiallyAnnotated_inspect]\ndef f(x) -> None:\n    pass\n\ndef g(x, y: str):\n    pass\n\nclass A:\n    def f(self, x) -> None:\n        pass\n\n[out]\ndef f(x) -> None: ...\ndef g(x, y: str): ...\n\nclass A:\n    def f(self, x) -> None: ...\n\n[case testExplicitAnyArg]\nfrom typing import Any\n\ndef f(x: Any):\n    pass\ndef g(x, y: Any) -> str:\n    pass\ndef h(x: Any) -> str:\n    pass\n\n[out]\nfrom typing import Any\n\ndef f(x: Any): ...\ndef g(x, y: Any) -> str: ...\ndef h(x: Any) -> str: ...\n\n-- Same as above\n[case testExplicitAnyArg_inspect]\nfrom typing import Any\n\ndef f(x: Any):\n    pass\ndef g(x, y: Any) -> str:\n    pass\ndef h(x: Any) -> str:\n    pass\n\n[out]\nfrom typing import Any\n\ndef f(x: Any): ...\ndef g(x, y: Any) -> str: ...\ndef h(x: Any) -> str: ...\n\n[case testExplicitReturnedAny]\nfrom typing import Any\n\ndef f(x: str) -> Any:\n    pass\ndef g(x, y: str) -> Any:\n    pass\ndef h(x) -> Any:\n    pass\n\n[out]\nfrom typing import Any\n\ndef f(x: str) -> Any: ...\ndef g(x, y: str) -> Any: ...\ndef h(x) -> Any: ...\n\n[case testPlacementOfDecorators]\nclass A:\n    @property\n    def x(self):\n        self.y = 'y'\n        return 'x'\n\nclass B:\n    @property\n    def x(self):\n        return 'x'\n    @x.setter\n    def x(self, value):\n        self.y = 'y'\n    @x.deleter\n    def x(self):\n        del self.y\n\n[out]\nclass A:\n    y: str\n    @property\n    def x(self): ...\n\nclass B:\n    @property\n    def x(self): ...\n    y: str\n    @x.setter\n    def x(self, value) -> None: ...\n    @x.deleter\n    def x(self) -> None: ...\n\n[case testMisplacedTypeComment]\ndef f():\n    x = 0\n\n    # type: str\n    y = ''\n\n[out]\ndef f() -> None: ...\n\n[case testConditionalImportAll_semanal]\n__all__ = ['cookielib']\n\nif object():\n    from http import cookiejar as cookielib\nelse:\n    import cookielib\n\n[out]\nimport cookielib as cookielib\n\n__all__ = ['cookielib']\n\n[case testCannotCalculateMRO_semanal]\nclass X: pass\n\nclass int(int, X):  # Cycle\n    pass\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nclass D(A, B): pass # No consistent method resolution order\nclass E(C, D): pass # Ditto\n\n[out]\nclass X: ...\nclass int(int, X): ...\nclass A: ...\nclass B(A): ...\nclass C(B): ...\nclass D(A, B): ...\nclass E(C, D): ...\n\n[case testUnreachableCode_semanal]\nMYPY = False\nclass A: pass\nif MYPY:\n    class C(A):\n        def f(self) -> None: pass\nelse:\n    def f(i):\n        return i\n\n    class C(A):\n        def g(self) -> None: pass\n[out]\nMYPY: bool\n\nclass A: ...\n\nclass C(A):\n    def f(self) -> None: ...\n\n[case testAbstractPropertyImportAlias]\nimport abc as abc_alias\n\nclass A:\n    @abc_alias.abstractproperty\n    def x(self): pass\n\n[out]\nimport abc as abc_alias\n\nclass A:\n    @property\n    @abc_alias.abstractmethod\n    def x(self): ...\n\n[case testAbstractPropertyFromImportAlias]\nfrom abc import abstractproperty as ap\n\nclass A:\n    @ap\n    def x(self): pass\n\n[out]\nimport abc\n\nclass A:\n    @property\n    @abc.abstractmethod\n    def x(self): ...\n\n[case testAbstractProperty1_semanal]\nimport other\nimport abc\n\nclass A:\n    @abc.abstractproperty\n    def x(self): pass\n\n[out]\nimport abc\n\nclass A(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def x(self): ...\n\n[case testAbstractProperty2_semanal]\nimport other\nfrom abc import abstractproperty\n\nclass A:\n    @abstractproperty\n    def x(self): pass\n\n[out]\nimport abc\n\nclass A(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def x(self): ...\n\n[case testAbstractProperty3_semanal]\nimport other\nfrom abc import abstractproperty as alias_name\n\nclass A:\n    @alias_name\n    def x(self): pass\n\n[out]\nimport abc\n\nclass A(metaclass=abc.ABCMeta):\n    @property\n    @abc.abstractmethod\n    def x(self): ...\n\n[case testClassWithNameIncompleteOrOptional]\nY = object()\n\ndef g(x=None): pass\n\nx = g()\n\nclass Incomplete:\n    pass\n\ndef Optional():\n    return 0\n\n[out]\nfrom _typeshed import Incomplete as _Incomplete\n\nY: _Incomplete\n\ndef g(x: _Incomplete | None = None) -> None: ...\n\nx: _Incomplete\n\nclass Incomplete: ...\n\ndef Optional(): ...\n\n[case testExportedNameImported]\n# modules: main a b\nfrom a import C\n\nclass D(C): pass\n\n[file a.py]\nfrom b import C\n\n[file b.py]\nclass C: pass\n\n[out]\n# main.pyi\nfrom a import C\n\nclass D(C): ...\n# a.pyi\nfrom b import C as C\n# b.pyi\nclass C: ...\n\n[case testVendoredSix]\nfrom p1.vendored import six\nfrom p1.vendor.six import foobar\nfrom p1.packages.six.moves import http_client\nfrom .packages.six.moves import queue\nfrom p1.vendored.six.moves.http_client import foo\nfrom p1.vendored.six.moves.urllib.parse import bar\n\nclass C(http_client.HTTPMessage): pass\nclass D(six.Iterator): pass\n\n[out]\nimport six\nfrom six import foobar as foobar\nfrom six.moves import http_client, queue as queue\nfrom six.moves.http_client import foo as foo\nfrom six.moves.urllib.parse import bar as bar\n\nclass C(http_client.HTTPMessage): ...\nclass D(six.Iterator): ...\n\n[case testVendoredPackage]\n# modules: main p.vendored.requests p.sub.requests\nfrom p.vendored.requests import Request\nfrom p.sub.requests import Request2\n\nx = Request()\ny = Request2()\n\n[file p/__init__.py]\n\n[file p/vendored/__init__.py]\n\n[file p/vendored/requests.py]\nclass Request:\n    pass\n\n[file p/sub/__init__.py]\n\n[file p/sub/requests.py]\nclass Request2:\n    pass\n\n[out]\n# main.pyi\nfrom _typeshed import Incomplete\n\nx: Incomplete\ny: Incomplete\n<out/p/vendored/requests.pyi was not generated>\n# p/sub/requests.pyi\nclass Request2: ...\n\n[case testTestFiles]\n# modules: p p.x p.tests p.tests.test_foo\n\n[file p/__init__.py]\ndef f(): pass\n\n[file p/x.py]\ndef g(): pass\n\n[file p/tests/__init__.py]\n\n[file p/tests/test_foo.py]\ndef test_thing(): pass\n\n[out]\n# p/__init__.pyi\ndef f() -> None: ...\n# p/x.pyi\ndef g() -> None: ...\n<out/p/tests.pyi was not generated>\n<out/p/tests/test_foo.pyi was not generated>\n\n[case testTestFiles_import]\n# modules: p p.x p.tests p.tests.test_foo\n\n[file p/__init__.py]\ndef f(): pass\n\n[file p/x.py]\ndef g(): pass\n\n[file p/tests/__init__.py]\n\n[file p/tests/test_foo.py]\ndef test_thing(): pass\n\n[out]\n# p/__init__.pyi\ndef f() -> None: ...\n# p/x.pyi\ndef g() -> None: ...\n<out/p/tests.pyi was not generated>\n<out/p/tests/test_foo.pyi was not generated>\n\n[case testTestFiles_inspect]\n# modules: p p.x p.tests p.tests.test_foo\n\n[file p/__init__.py]\ndef f(): pass\n\n[file p/x.py]\ndef g(): pass\n\n[file p/tests/__init__.py]\n\n[file p/tests/test_foo.py]\ndef test_thing(): pass\n\n[out]\n# p/__init__.pyi\ndef f(): ...\n# p/x.pyi\ndef g(): ...\n<out/p/tests.pyi was not generated>\n<out/p/tests/test_foo.pyi was not generated>\n\n[case testVerboseFlag]\n# Just test that --verbose does not break anything in a basic test case.\n# flags: --verbose\n\ndef f(x, y): pass\n[out]\ndef f(x, y) -> None: ...\n\n[case testImportedModuleExits_import]\n# modules: a b c\n\n[file a.py]\ndef g(): pass\n\n[file b.py]\nimport sys\ndef f(): pass\nsys.exit(1)\n\n[file c.py]\nx = 0\n\n[out]\n# a.pyi\ndef g() -> None: ...\n# b.pyi\ndef f() -> None: ...\n# c.pyi\nx: int\n\n[case testImportedModuleHardExits_import]\n# modules: a b c\n\n[file a.py]\ndef g(): pass\n\n[file b.py]\nimport os\ndef f(): pass\nos._exit(1)  # Kill process\n\n[file c.py]\nx = 0\n\n[out]\n# a.pyi\ndef g() -> None: ...\n# b.pyi\ndef f() -> None: ...\n# c.pyi\nx: int\n\n[case testImportedModuleHardExits2_import]\n# modules: p/a p/b p/c\n\n[file p/__init__.py]\n\n[file p/a.py]\ndef g(): pass\n\n[file p/b.py]\nimport os\ndef f(): pass\nos._exit(1)  # Kill process\n\n[file p/c.py]\nx = 0\n\n[out]\n# p/a.pyi\ndef g() -> None: ...\n# p/b.pyi\ndef f() -> None: ...\n# p/c.pyi\nx: int\n\n[case testImportedModuleHardExits3_import]\n# modules: p p/a\n\n[file p/__init__.py]\nimport os\ndef f(): pass\nos._exit(1)  # Kill process\n\n[file p/a.py]\ndef g(): pass\n\n[out]\n# p/__init__.pyi\ndef f() -> None: ...\n# p/a.pyi\ndef g() -> None: ...\n\n[case testImportedModuleHardExits4_import]\n# flags: -p p\n# modules: p p/a\n\n[file p/__init__.py]\ndef ff(): pass\n\n[file p/a.py]\nimport os\ndef gg(): pass\nos._exit(1)  # Kill process\n\n[out]\n# p/__init__.pyi\ndef ff() -> None: ...\n# p/a.pyi\ndef gg() -> None: ...\n\n[case testExportInternalImportsByDefault]\n# modules: p p/a\n\n[file p/__init__.py]\nfrom p.a import A, f\nfrom m import C\n\na: A\nc: C\nf()\n\n[file p/a.py]\nclass A: pass\ndef f(): pass\n\n[file m.py]\nclass C: pass\n\n[out]\n# p/__init__.pyi\nfrom m import C\nfrom p.a import A as A, f as f\n\na: A\nc: C\n# p/a.pyi\nclass A: ...\n\ndef f() -> None: ...\n\n[case testNoExportOfInternalImportsIfAll_import]\n# modules: p p/a\n\n[file p/__init__.py]\nfrom p.a import A\n\n__all__ = ['a']\n\na = None  # type: A\nb = 0  # type: int\n\n[file p/a.py]\nclass A: pass\n\n[out]\n# p/__init__.pyi\nfrom p.a import A\n\n__all__ = ['a']\n\na: A\n# p/a.pyi\nclass A: ...\n\n[case testExportInternalImportsByDefaultFromUnderscorePackage]\n# modules: p\n\n[file p.py]\nfrom _p import A\nfrom _m import B\nfrom _pm import C\n\na: A\nb: B\nc: C\n\n[file _p.py]\nclass A: pass\n\n[file _m.py]\nclass B: pass\n\n[file _pm.py]\nclass C: pass\n\n[out]\nfrom _m import B\nfrom _p import A as A\nfrom _pm import C\n\na: A\nb: B\nc: C\n\n[case testDisableExportOfInternalImports]\n# flags: --export-less\n# modules: p p/a\n\n[file p/__init__.py]\nfrom p.a import A, B\nfrom m import C\n\na: A\nc: C\n\n[file p/a.py]\nclass A: pass\nclass B: pass\n\n[file m.py]\nclass C: pass\n\n[out]\n# p/__init__.pyi\nfrom m import C\nfrom p.a import A, B as B\n\na: A\nc: C\n# p/a.pyi\nclass A: ...\nclass B: ...\n\n[case testExportInternalImportsByDefaultUsingRelativeImport]\n# modules: p.a\n\n[file p/__init__.py]\n\n[file p/a.py]\nfrom .b import f\nf()\n\n[file p/b.py]\ndef f(): pass\n\n[out]\nfrom .b import f as f\n\n[case testExportInternalImportsByDefaultSkipPrivate]\n# modules: p.a\n\n[file p/__init__.py]\n\n[file p/a.py]\nfrom .b import _f, _g as _g, _i\nfrom p.b import _h\n_f()\n_h()\n\n[file p/b.py]\ndef _f(): pass\ndef _g(): pass\ndef _h(): pass\ndef _i(): pass\nx = 0\n\n[out]\n\n[case testExportInternalImportsByDefaultIncludePrivate]\n# flags: --include-private\n# modules: p.a\n\n[file p/__init__.py]\n\n[file p/a.py]\nfrom .b import _f\n_f()\n\n[file p/b.py]\ndef _f(): pass\n\n[out]\nfrom .b import _f as _f\n\n[case testHideDunderModuleAttributes]\nfrom m import (\n    __about__,\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__\n)\n\nclass A:\n    __uri__ = 0\n\n[file m.py]\n__about__ = ''\n__author__ = ''\n__copyright__ = ''\n__email__ = ''\n__license__ = ''\n__summary__ = ''\n__title__ = ''\n__uri__ = ''\n__version__ = ''\n\n[out]\nfrom m import __version__ as __version__\n\nclass A: ...\n\n[case testHideDunderModuleAttributesWithAll_import]\nfrom m import (\n    __about__,\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__\n)\n\n__all__ = ['__about__', '__author__', '__version__']\n\n[file m.py]\n__about__ = ''\n__author__ = ''\n__copyright__ = ''\n__email__ = ''\n__license__ = ''\n__summary__ = ''\n__title__ = ''\n__uri__ = ''\n__version__ = ''\n\n[out]\nfrom m import __about__ as __about__, __author__ as __author__, __version__ as __version__\n\n__all__ = ['__about__', '__author__', '__version__']\n\n[case testAttrsClass_semanal]\nimport attrs\n\n@attrs.define\nclass C:\n    x: int = attrs.field()\n\n[out]\nimport attrs\n\n@attrs.define\nclass C:\n    x: int = attrs.field()\n\n[case testNamedTupleInClass]\nfrom collections import namedtuple\n\nclass C:\n    N = namedtuple('N', ['x', 'y'])\n[out]\nfrom _typeshed import Incomplete\nfrom typing import NamedTuple\n\nclass C:\n    class N(NamedTuple):\n        x: Incomplete\n        y: Incomplete\n\n[case testImports_directImportsWithAlias]\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\n\n[out]\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\n\n[case testImports_directImportsMixed]\nimport p.a\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\nz: p.a.X\n\n[out]\nimport p.a\nimport p.a as a\nimport p.b as b\n\nx: a.X\ny: b.Y\nz: p.a.X\n\n[case testImport_overwrites_directWithAlias_from]\nimport p.a as a\nfrom p import a\n\nx: a.X\n\n[out]\nfrom p import a\n\nx: a.X\n\n[case testImport_overwrites_directWithAlias_fromWithAlias]\nimport p.a as a\nfrom p import b as a\n\nx: a.X\n\n[out]\nfrom p import b as a\n\nx: a.X\n\n[case testImports_overwrites_direct_from]\nimport a\nfrom p import a\n\nx: a.X\n\n[out]\nfrom p import a\n\nx: a.X\n\n[case testImports_overwrites_direct_fromWithAlias]\nimport a\nfrom p import b as a\n\nx: a.X\n\n[out]\nfrom p import b as a\n\nx: a.X\n\n[case testImports_overwrites_from_directWithAlias]\nfrom p import a\nimport p.a as a\n\nx: a.X\n\n[out]\nimport p.a as a\n\nx: a.X\n\n[case testImports_overwrites_fromWithAlias_direct]\nimport a\nfrom p import b as a\n\nx: a.X\n\n[out]\nfrom p import b as a\n\nx: a.X\n\n[case testImports_direct]\nimport p.a\nimport pp\n\nx: a.X\ny: p.a.Y\n\n[out]\nimport p.a\n\nx: a.X\ny: p.a.Y\n\n[case testNestedImports]\nimport p\nimport p.m1\nimport p.m2\n\nx: p.X\ny: p.m1.Y\nz: p.m2.Z\n\n[out]\nimport p\nimport p.m1\nimport p.m2\n\nx: p.X\ny: p.m1.Y\nz: p.m2.Z\n\n[case testNestedImportsAliased]\nimport p as t\nimport p.m1 as pm1\nimport p.m2 as pm2\n\nx: t.X\ny: pm1.Y\nz: pm2.Z\n\n[out]\nimport p as t\nimport p.m1 as pm1\nimport p.m2 as pm2\n\nx: t.X\ny: pm1.Y\nz: pm2.Z\n\n[case testNestedFromImports]\nfrom p import m1\nfrom p.m1 import sm1\nfrom p.m2 import sm2\n\nx: m1.X\ny: sm1.Y\nz: sm2.Z\n\n[out]\nfrom p import m1\nfrom p.m1 import sm1\nfrom p.m2 import sm2\n\nx: m1.X\ny: sm1.Y\nz: sm2.Z\n\n[case testOverload_fromTypingImport]\nfrom typing import Tuple, Union, overload\n\nclass A:\n    @overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @overload\n    def f(self, x: Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: Union[int, Tuple[int, int]]) -> int:\n        pass\n\n@overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@overload\ndef f(x: Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: Union[int, Tuple[int, int]]) -> int:\n    pass\n\n\n[out]\nfrom typing import overload\n\nclass A:\n    @overload\n    def f(self, x: int, y: int) -> int: ...\n    @overload\n    def f(self, x: tuple[int, int]) -> int: ...\n\n@overload\ndef f(x: int, y: int) -> int: ...\n@overload\ndef f(x: tuple[int, int]) -> int: ...\n\n[case testOverload_fromTypingExtensionsImport]\nfrom typing import Tuple, Union\nfrom typing_extensions import overload\n\nclass A:\n    @overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @overload\n    def f(self, x: Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: Union[int, Tuple[int, int]]) -> int:\n        pass\n\n@overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@overload\ndef f(x: Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: Union[int, Tuple[int, int]]) -> int:\n    pass\n\n\n[out]\nfrom typing_extensions import overload\n\nclass A:\n    @overload\n    def f(self, x: int, y: int) -> int: ...\n    @overload\n    def f(self, x: tuple[int, int]) -> int: ...\n\n@overload\ndef f(x: int, y: int) -> int: ...\n@overload\ndef f(x: tuple[int, int]) -> int: ...\n\n[case testOverload_importTyping]\nimport typing\nimport typing_extensions\n\nclass A:\n    @typing.overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @typing.overload\n    def f(self, x: typing.Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n        pass\n\n    @typing.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int:\n        ...\n\n    @typing.overload\n    @classmethod\n    def g(cls, x: typing.Tuple[int, int]) -> int:\n        ...\n\n    @classmethod\n    def g(self, *args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n        pass\n\n@typing.overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@typing.overload\ndef f(x: typing.Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n    pass\n\n@typing_extensions.overload\ndef g(x: int, y: int) -> int:\n    ...\n\n@typing_extensions.overload\ndef g(x: typing.Tuple[int, int]) -> int:\n    ...\n\ndef g(*args: typing.Union[int, typing.Tuple[int, int]]) -> int:\n    pass\n\n\n[out]\nimport typing\nimport typing_extensions\n\nclass A:\n    @typing.overload\n    def f(self, x: int, y: int) -> int: ...\n    @typing.overload\n    def f(self, x: tuple[int, int]) -> int: ...\n    @typing.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int: ...\n    @typing.overload\n    @classmethod\n    def g(cls, x: tuple[int, int]) -> int: ...\n\n@typing.overload\ndef f(x: int, y: int) -> int: ...\n@typing.overload\ndef f(x: tuple[int, int]) -> int: ...\n@typing_extensions.overload\ndef g(x: int, y: int) -> int: ...\n@typing_extensions.overload\ndef g(x: tuple[int, int]) -> int: ...\n\n[case testOverload_importTypingAs]\nimport typing as t\nimport typing_extensions as te\n\nclass A:\n    @t.overload\n    def f(self, x: int, y: int) -> int:\n        ...\n\n    @t.overload\n    def f(self, x: t.Tuple[int, int]) -> int:\n        ...\n\n    def f(self, *args: typing.Union[int, t.Tuple[int, int]]) -> int:\n        pass\n\n    @t.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int:\n        ...\n\n    @t.overload\n    @classmethod\n    def g(cls, x: t.Tuple[int, int]) -> int:\n        ...\n\n    @classmethod\n    def g(self, *args: t.Union[int, t.Tuple[int, int]]) -> int:\n        pass\n\n@t.overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@t.overload\ndef f(x: t.Tuple[int, int]) -> int:\n    ...\n\ndef f(*args: t.Union[int, t.Tuple[int, int]]) -> int:\n    pass\n\n\n@te.overload\ndef g(x: int, y: int) -> int:\n    ...\n\n@te.overload\ndef g(x: t.Tuple[int, int]) -> int:\n    ...\n\ndef g(*args: t.Union[int, t.Tuple[int, int]]) -> int:\n    pass\n\n[out]\nimport typing as t\nimport typing_extensions as te\n\nclass A:\n    @t.overload\n    def f(self, x: int, y: int) -> int: ...\n    @t.overload\n    def f(self, x: tuple[int, int]) -> int: ...\n    @t.overload\n    @classmethod\n    def g(cls, x: int, y: int) -> int: ...\n    @t.overload\n    @classmethod\n    def g(cls, x: tuple[int, int]) -> int: ...\n\n@t.overload\ndef f(x: int, y: int) -> int: ...\n@t.overload\ndef f(x: tuple[int, int]) -> int: ...\n@te.overload\ndef g(x: int, y: int) -> int: ...\n@te.overload\ndef g(x: tuple[int, int]) -> int: ...\n\n[case testOverloadFromImportAlias]\nfrom typing import overload as t_overload\nfrom typing_extensions import overload as te_overload\n\n@t_overload\ndef f(x: int, y: int) -> int:\n    ...\n\n@te_overload\ndef g(x: int, y: int) -> int:\n    ...\n\n[out]\nfrom typing import overload as t_overload\nfrom typing_extensions import overload as te_overload\n\n@t_overload\ndef f(x: int, y: int) -> int: ...\n@te_overload\ndef g(x: int, y: int) -> int: ...\n\n[case testProtocol_semanal]\nfrom typing import Protocol, TypeVar\n\nclass P(Protocol):\n    def f(self, x: int, y: int) -> str:\n        ...\n\nT = TypeVar('T')\nT2 = TypeVar('T2')\nclass PT(Protocol[T, T2]):\n    def f(self, x: T) -> T2:\n        ...\n\n[out]\nfrom typing import Protocol, TypeVar\n\nclass P(Protocol):\n    def f(self, x: int, y: int) -> str: ...\nT = TypeVar('T')\nT2 = TypeVar('T2')\n\nclass PT(Protocol[T, T2]):\n    def f(self, x: T) -> T2: ...\n\n[case testProtocolAbstractMethod_semanal]\nfrom abc import abstractmethod\nfrom typing import Protocol\n\nclass P(Protocol):\n    @abstractmethod\n    def f(self, x: int, y: int) -> str:\n        ...\n\n[out]\nfrom abc import abstractmethod\nfrom typing import Protocol\n\nclass P(Protocol):\n    @abstractmethod\n    def f(self, x: int, y: int) -> str: ...\n\n[case testNonDefaultKeywordOnlyArgAfterAsterisk]\ndef func(*, non_default_kwarg: bool, default_kwarg: bool = True): ...\n[out]\ndef func(*, non_default_kwarg: bool, default_kwarg: bool = True): ...\n\n[case testNestedGenerator]\ndef f1():\n    def g():\n        yield 0\n    return 0\ndef f2():\n    def g():\n        yield from [0]\n    return 0\n[out]\ndef f1(): ...\ndef f2(): ...\n\n[case testIncludeDocstrings]\n# flags:  --include-docstrings\nclass A:\n    \"\"\"class docstring\n\n    a multiline 😊 docstring\"\"\"\n    def func():\n        \"\"\"func docstring\n        don't forget to indent\"\"\"\n        ...\n    def nodoc():\n        ...\nclass B:\n    def quoteA():\n        '''func docstring with quotes\"\"\"\\\\n\n        and an end quote\\''''\n        ...\n    def quoteB():\n        '''func docstring with quotes\"\"\"\n        \\'\\'\\'\n        and an end quote\\\\\"'''\n        ...\n    def quoteC():\n        \"\"\"func docstring with end quote\\\\\\\"\"\"\"\n        ...\n    def quoteD():\n        r'''raw with quotes\\\"'''\n        ...\n[out]\nclass A:\n    \"\"\"class docstring\n\n    a multiline 😊 docstring\"\"\"\n    def func() -> None:\n        \"\"\"func docstring\n        don't forget to indent\"\"\"\n    def nodoc() -> None: ...\n\nclass B:\n    def quoteA() -> None:\n        '''func docstring with quotes\"\"\"\\\\n\n        and an end quote\\''''\n    def quoteB() -> None:\n        '''func docstring with quotes\"\"\"\n        \\'\\'\\'\n        and an end quote\\\\\"'''\n    def quoteC() -> None:\n        '''func docstring with end quote\\\\\"'''\n    def quoteD() -> None:\n        '''raw with quotes\\\\\"'''\n\n[case testIgnoreDocstrings]\nclass A:\n    \"\"\"class docstring\n\n    a multiline docstring\"\"\"\n    def func():\n        \"\"\"func docstring\n\n        don't forget to indent\"\"\"\n    def nodoc():\n        ...\n\nclass B:\n    def func():\n        \"\"\"func docstring\"\"\"\n        ...\n    def nodoc():\n        ...\n\n[out]\nclass A:\n    def func() -> None: ...\n    def nodoc() -> None: ...\n\nclass B:\n    def func() -> None: ...\n    def nodoc() -> None: ...\n\n[case testKnownMagicMethodsReturnTypes]\nclass Some:\n    def __len__(self): ...\n    def __length_hint__(self): ...\n    def __init__(self): ...\n    def __del__(self): ...\n    def __bool__(self): ...\n    def __bytes__(self): ...\n    def __format__(self, spec): ...\n    def __contains__(self, obj): ...\n    def __complex__(self): ...\n    def __int__(self): ...\n    def __float__(self): ...\n    def __index__(self): ...\n[out]\nclass Some:\n    def __len__(self) -> int: ...\n    def __length_hint__(self) -> int: ...\n    def __init__(self) -> None: ...\n    def __del__(self) -> None: ...\n    def __bool__(self) -> bool: ...\n    def __bytes__(self) -> bytes: ...\n    def __format__(self, spec) -> str: ...\n    def __contains__(self, obj) -> bool: ...\n    def __complex__(self) -> complex: ...\n    def __int__(self) -> int: ...\n    def __float__(self) -> float: ...\n    def __index__(self) -> int: ...\n\n-- Same as above\n[case testKnownMagicMethodsReturnTypes_inspect]\nclass Some:\n    def __len__(self): ...\n    def __length_hint__(self): ...\n    def __init__(self): ...\n    def __del__(self): ...\n    def __bool__(self): ...\n    def __bytes__(self): ...\n    def __format__(self, spec): ...\n    def __contains__(self, obj): ...\n    def __complex__(self): ...\n    def __int__(self): ...\n    def __float__(self): ...\n    def __index__(self): ...\n[out]\nclass Some:\n    def __len__(self) -> int: ...\n    def __length_hint__(self) -> int: ...\n    def __init__(self) -> None: ...\n    def __del__(self) -> None: ...\n    def __bool__(self) -> bool: ...\n    def __bytes__(self) -> bytes: ...\n    def __format__(self, spec) -> str: ...\n    def __contains__(self, obj) -> bool: ...\n    def __complex__(self) -> complex: ...\n    def __int__(self) -> int: ...\n    def __float__(self) -> float: ...\n    def __index__(self) -> int: ...\n\n\n[case testKnownMagicMethodsArgTypes]\nclass MismatchNames:\n    def __exit__(self, tp, val, tb): ...\n\nclass MatchNames:\n    def __exit__(self, type, value, traceback): ...\n\n[out]\nclass MismatchNames:\n    def __exit__(self, tp: type[BaseException] | None, val: BaseException | None, tb: types.TracebackType | None) -> None: ...\n\nclass MatchNames:\n    def __exit__(self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None) -> None: ...\n\n-- Same as above (but can generate import statements)\n[case testKnownMagicMethodsArgTypes_inspect]\nclass MismatchNames:\n    def __exit__(self, tp, val, tb): ...\n\nclass MatchNames:\n    def __exit__(self, type, value, traceback): ...\n\n[out]\nimport types\n\nclass MismatchNames:\n    def __exit__(self, tp: type[BaseException] | None, val: BaseException | None, tb: types.TracebackType | None): ...\n\nclass MatchNames:\n    def __exit__(self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None): ...\n\n[case testTypeVarPEP604Bound]\nfrom typing import TypeVar\nT = TypeVar(\"T\", bound=str | None)\n[out]\nfrom typing import TypeVar\n\nT = TypeVar('T', bound=str | None)\n\n\n[case testPEP604UnionType]\na: str | int\n\ndef f(x: str | None) -> None: ...\n[out]\na: str | int\n\ndef f(x: str | None) -> None: ...\n\n[case testTypeddict]\nimport typing, x\nX = typing.TypedDict('X', {'a': int, 'b': str})\nY = typing.TypedDict('X', {'a': int, 'b': str}, total=False)\n[out]\nfrom typing_extensions import TypedDict\n\nclass X(TypedDict):\n    a: int\n    b: str\n\nclass Y(TypedDict, total=False):\n    a: int\n    b: str\n\n[case testTypeddictClassWithKeyword]\nfrom typing import TypedDict\nclass MyDict(TypedDict, total=False):\n    foo: str\n    bar: int\n[out]\nfrom typing import TypedDict\n\nclass MyDict(TypedDict, total=False):\n    foo: str\n    bar: int\n\n[case testTypeddictKeywordSyntax]\nfrom typing import TypedDict\n\nX = TypedDict('X', a=int, b=str)\nY = TypedDict('X', a=int, b=str, total=False)\n[out]\nfrom typing_extensions import TypedDict\n\nclass X(TypedDict):\n    a: int\n    b: str\n\nclass Y(TypedDict, total=False):\n    a: int\n    b: str\n\n[case testTypeddictWithNonIdentifierOrKeywordKeys]\nfrom typing import TypedDict\nX = TypedDict('X', {'a-b': int, 'c': str})\nY = TypedDict('X', {'a-b': int, 'c': str}, total=False)\nZ = TypedDict('X', {'a': int, 'in': str})\n[out]\nfrom typing import TypedDict\n\nX = TypedDict('X', {'a-b': int, 'c': str})\nY = TypedDict('X', {'a-b': int, 'c': str}, total=False)\nZ = TypedDict('X', {'a': int, 'in': str})\n\n[case testEmptyTypeddict]\nimport typing\nX = typing.TypedDict('X', {})\nY = typing.TypedDict('Y', {}, total=False)\nZ = typing.TypedDict('Z')\nW = typing.TypedDict('W', total=False)\n[out]\nfrom typing_extensions import TypedDict\n\nclass X(TypedDict): ...\nclass Y(TypedDict, total=False): ...\nclass Z(TypedDict): ...\nclass W(TypedDict, total=False): ...\n\n[case testTypeddictAliased]\nfrom typing import TypedDict as t_TypedDict\nfrom typing_extensions import TypedDict as te_TypedDict\ndef f(): ...\nX = t_TypedDict('X', {'a': int, 'b': str})\nY = te_TypedDict('Y', {'a': int, 'b': str})\ndef g(): ...\n[out]\nfrom typing_extensions import TypedDict\n\ndef f() -> None: ...\n\nclass X(TypedDict):\n    a: int\n    b: str\n\nclass Y(TypedDict):\n    a: int\n    b: str\n\ndef g() -> None: ...\n\n[case testTypeddictFromImportAlias]\nimport typing as t\nimport typing_extensions as te\nX = t.TypedDict('X', {'a': int, 'b': str})\nY = te.TypedDict('Y', {'a': int, 'b': str})\n[out]\nfrom typing_extensions import TypedDict\n\nclass X(TypedDict):\n    a: int\n    b: str\n\nclass Y(TypedDict):\n    a: int\n    b: str\n\n[case testNotTypeddict]\nfrom x import TypedDict\nimport y\nX = TypedDict('X', {'a': int, 'b': str})\nY = y.TypedDict('Y', {'a': int, 'b': str})\n[out]\nfrom _typeshed import Incomplete\n\nX: Incomplete\nY: Incomplete\n\n[case testTypeddictWithWrongAttributesType]\nfrom typing import TypedDict\nR = TypedDict(\"R\", {\"a\": int, **{\"b\": str, \"c\": bytes}})\nS = TypedDict(\"S\", [(\"b\", str), (\"c\", bytes)])\nT = TypedDict(\"T\", {\"a\": int}, b=str, total=False)\nU = TypedDict(\"U\", {\"a\": int}, totale=False)\nV = TypedDict(\"V\", {\"a\": int}, {\"b\": str})\nW = TypedDict(\"W\", **{\"a\": int, \"b\": str})\n[out]\nfrom _typeshed import Incomplete\n\nR: Incomplete\nS: Incomplete\nT: Incomplete\nU: Incomplete\nV: Incomplete\nW: Incomplete\n\n[case testUseTypingName]\nimport collections\nimport typing\nfrom typing import NamedTuple, TypedDict\n\nclass Incomplete: ...\nclass Generator: ...\nclass NamedTuple: ...\nclass TypedDict: ...\n\nnt = collections.namedtuple(\"nt\", \"a b\")\nNT = typing.NamedTuple(\"NT\", [(\"a\", int), (\"b\", str)])\nNT1 = typing.NamedTuple(\"NT1\", [(\"a\", int)] + [(\"b\", str)])\nNT2 = typing.NamedTuple(\"NT2\", [(xx, int), (\"b\", str)])\nNT3 = typing.NamedTuple(xx, [(\"a\", int), (\"b\", str)])\nTD = typing.TypedDict(\"TD\", {\"a\": int, \"b\": str})\nTD1 = typing.TypedDict(\"TD1\", {\"a\": int, \"b\": str}, totale=False)\nTD2 = typing.TypedDict(\"TD2\", {xx: int, \"b\": str})\nTD3 = typing.TypedDict(xx, {\"a\": int, \"b\": str})\n\ndef gen():\n    y = yield x\n    return z\n\ndef gen2():\n    y = yield from x\n    return z\n\nclass X(unknown_call(\"X\", \"a b\")): ...\nclass Y(collections.namedtuple(\"Y\", xx)): ...\n[out]\nfrom _typeshed import Incomplete as _Incomplete\nfrom collections.abc import Generator as _Generator\nfrom typing import NamedTuple as _NamedTuple\nfrom typing_extensions import TypedDict as _TypedDict\n\nclass Incomplete: ...\nclass Generator: ...\nclass NamedTuple: ...\nclass TypedDict: ...\n\nclass nt(_NamedTuple):\n    a: _Incomplete\n    b: _Incomplete\n\nclass NT(_NamedTuple):\n    a: int\n    b: str\n\nNT1: _Incomplete\nNT2: _Incomplete\nNT3: _Incomplete\n\nclass TD(_TypedDict):\n    a: int\n    b: str\n\nTD1: _Incomplete\nTD2: _Incomplete\nTD3: _Incomplete\n\ndef gen() -> _Generator[_Incomplete, _Incomplete, _Incomplete]: ...\ndef gen2() -> _Generator[_Incomplete, _Incomplete, _Incomplete]: ...\n\nclass X(_Incomplete): ...\nclass Y(_Incomplete): ...\n\n[case testIgnoreLongDefaults]\ndef f(x='abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\\\nabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\\\nabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\\\nabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'): ...\n\ndef g(x=b'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\\\nabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\\\nabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\\\nabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'): ...\n\ndef h(x=123456789012345678901234567890123456789012345678901234567890\\\n123456789012345678901234567890123456789012345678901234567890\\\n123456789012345678901234567890123456789012345678901234567890\\\n123456789012345678901234567890123456789012345678901234567890): ...\n\n[out]\ndef f(x: str = ...) -> None: ...\ndef g(x: bytes = ...) -> None: ...\ndef h(x: int = ...) -> None: ...\n\n[case testDefaultsOfBuiltinContainers]\ndef f(x=(), y=(1,), z=(1, 2)): ...\ndef g(x=[], y=[1, 2]): ...\ndef h(x={}, y={1: 2, 3: 4}): ...\ndef i(x={1, 2, 3}): ...\ndef j(x=[(1,\"a\"), (2,\"b\")]): ...\n\n[out]\ndef f(x=(), y=(1,), z=(1, 2)) -> None: ...\ndef g(x=[], y=[1, 2]) -> None: ...\ndef h(x={}, y={1: 2, 3: 4}) -> None: ...\ndef i(x={1, 2, 3}) -> None: ...\ndef j(x=[(1, 'a'), (2, 'b')]) -> None: ...\n\n[case testDefaultsOfBuiltinContainersWithNonTrivialContent]\ndef f(x=(1, u.v), y=(k(),), z=(w,)): ...\ndef g(x=[1, u.v], y=[k()], z=[w]): ...\ndef h(x={1: u.v}, y={k(): 2}, z={m: m}, w={**n}): ...\ndef i(x={u.v, 2}, y={3, k()}, z={w}): ...\n\n[out]\ndef f(x=..., y=..., z=...) -> None: ...\ndef g(x=..., y=..., z=...) -> None: ...\ndef h(x=..., y=..., z=..., w=...) -> None: ...\ndef i(x=..., y=..., z=...) -> None: ...\n\n[case testDataclass]\nimport dataclasses\nimport dataclasses as dcs\nfrom dataclasses import dataclass, field, Field, InitVar, KW_ONLY\nfrom dataclasses import dataclass as dc\nfrom datetime import datetime\nfrom typing import ClassVar\n\n@dataclasses.dataclass\nclass X:\n    a: int\n    b: str = \"hello\"\n    c: ClassVar\n    d: ClassVar = 200\n    f: list[int] = field(init=False, default_factory=list)\n    g: int = field(default=2, kw_only=True)\n    _: KW_ONLY\n    h: int = 1\n    i: InitVar[str]\n    j: InitVar = 100\n    # Lambda not supported yet -> marked as Incomplete instead\n    k: str = Field(\n        default_factory=lambda: datetime.utcnow().isoformat(\" \", timespec=\"seconds\")\n    )\n    non_field = None\n\n@dcs.dataclass\nclass Y: ...\n\n@dataclass\nclass Z: ...\n\n@dc\nclass W: ...\n\n@dataclass(init=False, repr=False)\nclass V: ...\n\n[out]\nimport dataclasses\nimport dataclasses as dcs\nfrom _typeshed import Incomplete\nfrom dataclasses import Field, InitVar, KW_ONLY, dataclass, dataclass as dc, field\nfrom typing import ClassVar\n\n@dataclasses.dataclass\nclass X:\n    a: int\n    b: str = ...\n    c: ClassVar\n    d: ClassVar = ...\n    f: list[int] = field(init=False, default_factory=list)\n    g: int = field(default=2, kw_only=True)\n    _: KW_ONLY\n    h: int = ...\n    i: InitVar[str]\n    j: InitVar = ...\n    k: str = Field(default_factory=Incomplete)\n    non_field = ...\n\n@dcs.dataclass\nclass Y: ...\n@dataclass\nclass Z: ...\n@dc\nclass W: ...\n@dataclass(init=False, repr=False)\nclass V: ...\n\n[case testDataclass_semanal]\nfrom dataclasses import Field, InitVar, dataclass, field\nfrom typing import ClassVar\nfrom datetime import datetime\n\n@dataclass\nclass X:\n    a: int\n    b: InitVar[str]\n    c: str = \"hello\"\n    d: ClassVar\n    e: ClassVar = 200\n    f: list[int] = field(init=False, default_factory=list)\n    g: int = field(default=2, kw_only=True)\n    h: int = 1\n    i: InitVar = 100\n    j: list[int] = field(default_factory=list)\n    # Lambda not supported yet -> marked as Incomplete instead\n    k: str = Field(\n        default_factory=lambda: datetime.utcnow().isoformat(\" \", timespec=\"seconds\")\n    )\n    non_field = None\n\n@dataclass(init=False, repr=False, frozen=True)\nclass Y: ...\n\n[out]\nfrom _typeshed import Incomplete\nfrom dataclasses import Field, InitVar, dataclass, field\nfrom typing import ClassVar\n\n@dataclass\nclass X:\n    a: int\n    b: InitVar[str]\n    c: str = ...\n    d: ClassVar\n    e: ClassVar = ...\n    f: list[int] = field(init=False, default_factory=list)\n    g: int = field(default=2, kw_only=True)\n    h: int = ...\n    i: InitVar = ...\n    j: list[int] = field(default_factory=list)\n    k: str = Field(default_factory=Incomplete)\n    non_field = ...\n\n@dataclass(init=False, repr=False, frozen=True)\nclass Y: ...\n\n[case testDataclassWithKwOnlyField_semanal]\n# flags: --python-version=3.10\nfrom dataclasses import dataclass, field, InitVar, KW_ONLY\nfrom typing import ClassVar\n\n@dataclass\nclass X:\n    a: int\n    b: str = \"hello\"\n    c: ClassVar\n    d: ClassVar = 200\n    f: list[int] = field(init=False, default_factory=list)\n    g: int = field(default=2, kw_only=True)\n    _: KW_ONLY\n    h: int = 1\n    i: InitVar[str]\n    j: InitVar = 100\n    non_field = None\n\n@dataclass(init=False, repr=False, frozen=True)\nclass Y: ...\n\n[out]\nfrom dataclasses import InitVar, KW_ONLY, dataclass, field\nfrom typing import ClassVar\n\n@dataclass\nclass X:\n    a: int\n    b: str = ...\n    c: ClassVar\n    d: ClassVar = ...\n    f: list[int] = field(init=False, default_factory=list)\n    g: int = field(default=2, kw_only=True)\n    _: KW_ONLY\n    h: int = ...\n    i: InitVar[str]\n    j: InitVar = ...\n    non_field = ...\n\n@dataclass(init=False, repr=False, frozen=True)\nclass Y: ...\n\n[case testDataclassWithExplicitGeneratedMethodsOverrides_semanal]\nfrom dataclasses import dataclass\n\n@dataclass\nclass X:\n    a: int\n    def __init__(self, a: int, b: str = ...) -> None: ...\n    def __post_init__(self) -> None: ...\n\n[out]\nfrom dataclasses import dataclass\n\n@dataclass\nclass X:\n    a: int\n    def __init__(self, a: int, b: str = ...) -> None: ...\n    def __post_init__(self) -> None: ...\n\n[case testDataclassInheritsFromAny_semanal]\nfrom dataclasses import dataclass\nimport missing\n\n@dataclass\nclass X(missing.Base):\n    a: int\n\n@dataclass\nclass Y(missing.Base):\n    generated_args: str\n    generated_args_: str\n    generated_kwargs: float\n    generated_kwargs_: float\n\n[out]\nimport missing\nfrom dataclasses import dataclass\n\n@dataclass\nclass X(missing.Base):\n    a: int\n\n@dataclass\nclass Y(missing.Base):\n    generated_args: str\n    generated_args_: str\n    generated_kwargs: float\n    generated_kwargs_: float\n\n[case testDataclassTransform]\n# dataclass_transform detection only works with sementic analysis.\n# Test stubgen doesn't break too badly without it.\nfrom typing_extensions import dataclass_transform\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\ndef create_model(cls):\n    return cls\n\n@create_model\nclass X:\n    a: int\n    b: str = \"hello\"\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\nclass ModelBase: ...\n\nclass Y(ModelBase):\n    a: int\n    b: str = \"hello\"\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\nclass DCMeta(type): ...\n\nclass Z(metaclass=DCMeta):\n    a: int\n    b: str = \"hello\"\n\n[out]\n@typing_extensions.dataclass_transform(kw_only_default=True)\ndef create_model(cls): ...\n\nclass X:\n    a: int\n    b: str\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\nclass ModelBase: ...\n\nclass Y(ModelBase):\n    a: int\n    b: str\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\nclass DCMeta(type): ...\n\nclass Z(metaclass=DCMeta):\n    a: int\n    b: str\n\n[case testDataclassTransformDecorator_semanal]\nimport typing_extensions\nfrom dataclasses import field\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\ndef create_model(cls):\n    return cls\n\n@create_model\nclass X:\n    a: int\n    b: str = \"hello\"\n    c: bool = field(default=True)\n\n[out]\nimport typing_extensions\nfrom dataclasses import field\n\n@typing_extensions.dataclass_transform(kw_only_default=True)\ndef create_model(cls): ...\n\n@create_model\nclass X:\n    a: int\n    b: str = ...\n    c: bool = field(default=True)\n\n[case testDataclassTransformClass_semanal]\nfrom dataclasses import field\nfrom typing_extensions import dataclass_transform\n\n@dataclass_transform(kw_only_default=True)\nclass ModelBase: ...\n\nclass X(ModelBase):\n    a: int\n    b: str = \"hello\"\n    c: bool = field(default=True)\n\n[out]\nfrom dataclasses import field\nfrom typing_extensions import dataclass_transform\n\n@dataclass_transform(kw_only_default=True)\nclass ModelBase: ...\n\nclass X(ModelBase):\n    a: int\n    b: str = ...\n    c: bool = field(default=True)\n\n[case testDataclassTransformMetaclass_semanal]\nfrom dataclasses import field\nfrom typing import Any\nfrom typing_extensions import dataclass_transform\n\ndef custom_field(*, default: bool, kw_only: bool) -> Any: ...\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(custom_field,))\nclass DCMeta(type): ...\n\nclass X(metaclass=DCMeta):\n    a: int\n    b: str = \"hello\"\n    c: bool = field(default=True)  # should be ignored, not field_specifier here\n\nclass Y(X):\n    d: str = custom_field(default=\"Hello\")\n\n[out]\nfrom typing import Any\nfrom typing_extensions import dataclass_transform\n\ndef custom_field(*, default: bool, kw_only: bool) -> Any: ...\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(custom_field,))\nclass DCMeta(type): ...\n\nclass X(metaclass=DCMeta):\n    a: int\n    b: str = ...\n    c: bool = ...\n\nclass Y(X):\n    d: str = custom_field(default='Hello')\n\n[case testAlwaysUsePEP604Union]\nimport typing\nimport typing as t\nfrom typing import Optional, Union, Optional as O, Union as U\nimport x\n\nunion = Union[int, str]\nbad_union = Union[int]\nnested_union = Optional[Union[int, str]]\nnot_union = x.Union[int, str]\nu = U[int, str]\no = O[int]\n\ndef f1(a: Union[\"int\", Optional[tuple[int, t.Optional[int]]]]) -> int: ...\ndef f2(a: typing.Union[int | x.Union[int, int], O[float]]) -> int: ...\n\n[out]\nimport x\nfrom _typeshed import Incomplete\n\nunion = int | str\nbad_union = int\nnested_union = int | str | None\nnot_union: Incomplete\nu = int | str\no = int | None\n\ndef f1(a: int | tuple[int, int | None] | None) -> int: ...\ndef f2(a: int | x.Union[int, int] | float | None) -> int: ...\n\n[case testTypingBuiltinReplacements]\nimport typing\nimport typing as t\nfrom typing import Tuple\nimport typing_extensions\nimport typing_extensions as te\nfrom typing_extensions import List, Type\n\n# builtins are not builtins\ntuple = int\n[list,] = float\ndict, set, frozenset = str, float, int\n\nx: Tuple[t.Text, t.FrozenSet[typing.Type[float]]]\ny: typing.List[int]\nz: t.Dict[str, float]\nv: typing.Set[int]\nw: List[typing_extensions.Dict[te.FrozenSet[Type[int]], te.Tuple[te.Set[te.Text], ...]]]\n\nx_alias = Tuple[str, ...]\ny_alias = typing.List[int]\nz_alias = t.Dict[str, float]\nv_alias = typing.Set[int]\nw_alias = List[typing_extensions.Dict[str, te.Tuple[int, ...]]]\n\n[out]\nfrom _typeshed import Incomplete\nfrom builtins import dict as _dict, frozenset as _frozenset, list as _list, set as _set, tuple as _tuple\n\ntuple = int\nlist: Incomplete\ndict: Incomplete\nset: Incomplete\nfrozenset: Incomplete\nx: _tuple[str, _frozenset[type[float]]]\ny: _list[int]\nz: _dict[str, float]\nv: _set[int]\nw: _list[_dict[_frozenset[type[int]], _tuple[_set[str], ...]]]\nx_alias = _tuple[str, ...]\ny_alias = _list[int]\nz_alias = _dict[str, float]\nv_alias = _set[int]\nw_alias = _list[_dict[str, _tuple[int, ...]]]\n\n[case testHandlingNameCollisions]\n# flags: --include-private\nfrom typing import Tuple\ntuple = int\n_tuple = range\n__tuple = map\nx: Tuple[int, str]\n[out]\nfrom builtins import tuple as ___tuple\n\ntuple = int\n_tuple = range\n__tuple = map\nx: ___tuple[int, str]\n\n[case testPEP570PosOnlyParams]\ndef f(x=0, /): ...\ndef f1(x: int, /): ...\ndef f2(x: int, y: float = 1, /): ...\ndef f3(x: int, /, y: float): ...\ndef f4(x: int, /, y: float = 1): ...\ndef f5(x: int, /, *, y: float): ...\ndef f6(x: int = 0, /, *, y: float): ...\ndef f7(x: int, /, *, y: float = 1): ...\ndef f8(x: int = 0, /, *, y: float = 1): ...\n\n[out]\ndef f(x: int = 0, /) -> None: ...\ndef f1(x: int, /): ...\ndef f2(x: int, y: float = 1, /): ...\ndef f3(x: int, /, y: float): ...\ndef f4(x: int, /, y: float = 1): ...\ndef f5(x: int, /, *, y: float): ...\ndef f6(x: int = 0, /, *, y: float): ...\ndef f7(x: int, /, *, y: float = 1): ...\ndef f8(x: int = 0, /, *, y: float = 1): ...\n\n[case testPreserveEmptyTuple]\nann: tuple[()]\nalias = tuple[()]\ndef f(x: tuple[()]): ...\nclass C(tuple[()]): ...\n\n[out]\nann: tuple[()]\nalias = tuple[()]\n\ndef f(x: tuple[()]): ...\n\nclass C(tuple[()]): ...\n\n[case testPreserveEnumValue_semanal]\nfrom enum import Enum\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Bar(Enum):\n    A = object()\n    B = \"a\" + \"b\"\n\n[out]\nfrom enum import Enum\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Bar(Enum):\n    A = ...\n    B = ...\n\n[case testGracefullyHandleInvalidOptionalUsage]\nfrom typing import Optional\n\nx: Optional  # invalid\ny: Optional[int]  # valid\nz: Optional[int, str]  # invalid\nw: Optional[int | str]  # valid\nr: Optional[type[int | str]]\n\nX = Optional\nY = Optional[int]\nZ = Optional[int, str]\nW = Optional[int | str]\nR = Optional[type[int | str]]\n\n[out]\nfrom _typeshed import Incomplete\nfrom typing import Optional\n\nx: Incomplete\ny: int | None\nz: Incomplete\nw: int | str | None\nr: type[int | str] | None\nX = Optional\nY = int | None\nZ = Incomplete\nW = int | str | None\nR = type[int | str] | None\n\n[case testClassInheritanceWithKeywordsConstants]\nclass Test(Whatever, a=1, b='b', c=True, d=1.5, e=None, f=1j, g=b'123'): ...\n[out]\nclass Test(Whatever, a=1, b='b', c=True, d=1.5, e=None, f=1j, g=b'123'): ...\n\n[case testClassInheritanceWithKeywordsDynamic]\nclass Test(Whatever, keyword=SomeName * 2, attr=SomeName.attr): ...\n[out]\nclass Test(Whatever, keyword=SomeName * 2, attr=SomeName.attr): ...\n\n[case testPEP695GenericClass]\n# flags: --python-version=3.12\n\nclass C[T]: ...\nclass C1[T1](int): ...\nclass C2[T2: int]: ...\nclass C3[T3: str | bytes]: ...\nclass C4[T4: (str, bytes)]: ...\n\nclass Outer:\n    class Inner[T]: ...\n\n[out]\nclass C[T]: ...\nclass C1[T1](int): ...\nclass C2[T2: int]: ...\nclass C3[T3: str | bytes]: ...\nclass C4[T4: (str, bytes)]: ...\n\nclass Outer:\n    class Inner[T]: ...\n\n[case testPEP695GenericFunction]\n# flags: --python-version=3.12\n\ndef f1[T1](): ...\ndef f2[T2: int](): ...\ndef f3[T3: str | bytes](): ...\ndef f4[T4: (str, bytes)](): ...\n\nclass C:\n    def m[T](self, x: T) -> T: ...\n\n[out]\ndef f1[T1]() -> None: ...\ndef f2[T2: int]() -> None: ...\ndef f3[T3: str | bytes]() -> None: ...\ndef f4[T4: (str, bytes)]() -> None: ...\n\nclass C:\n    def m[T](self, x: T) -> T: ...\n\n[case testPEP695TypeAlias]\n# flags: --python-version=3.12\n\ntype Alias = int | str\ntype Alias1[T1] = list[T1] | set[T1]\ntype Alias2[T2: int] = list[T2] | set[T2]\ntype Alias3[T3: str | bytes] = list[T3] | set[T3]\ntype Alias4[T4: (str, bytes)] = list[T4] | set[T4]\n\nclass C:\n    type IndentedAlias[T] = list[T]\n\n[out]\ntype Alias = int | str\ntype Alias1[T1] = list[T1] | set[T1]\ntype Alias2[T2: int] = list[T2] | set[T2]\ntype Alias3[T3: str | bytes] = list[T3] | set[T3]\ntype Alias4[T4: (str, bytes)] = list[T4] | set[T4]\nclass C:\n    type IndentedAlias[T] = list[T]\n\n[case testPEP695Syntax_semanal]\n# flags: --python-version=3.12\n\nclass C[T]: ...\ndef f[S](): ...\ntype A[R] = list[R]\n\n[out]\nclass C[T]: ...\n\ndef f[S]() -> None: ...\ntype A[R] = list[R]\n\n[case testPEP696Syntax]\n# flags: --python-version=3.13\n\ntype Alias1[T1 = int] = list[T1] | set[T1]\ntype Alias2[T2: int | float = int] = list[T2] | set[T2]\nclass C3[T3 = int]: ...\nclass C4[T4: int | float = int](list[T4]): ...\ndef f5[T5 = int](): ...\n\n[out]\ntype Alias1[T1 = int] = list[T1] | set[T1]\ntype Alias2[T2: int | float = int] = list[T2] | set[T2]\nclass C3[T3 = int]: ...\nclass C4[T4: int | float = int](list[T4]): ...\n\ndef f5[T5 = int]() -> None: ...\n\n[case testIgnoreMypyGeneratedMethods_semanal]\n# flags: --include-private --python-version=3.13\nfrom typing_extensions import dataclass_transform\n\n@dataclass_transform()\nclass DCMeta(type): ...\nclass DC(metaclass=DCMeta):\n    x: str\n\n[out]\nfrom typing_extensions import dataclass_transform\n\n@dataclass_transform()\nclass DCMeta(type): ...\n\nclass DC(metaclass=DCMeta):\n    x: str\n"
  },
  {
    "path": "test-data/unit/typexport-basic.test",
    "content": "-- Test cases for exporting node types from the type checker.\n--\n-- Each test case consists of at least two sections.\n-- The first section contains [case NAME] followed by the input code,\n-- while the second section contains [out] followed by the output from the type\n-- checker.\n--\n-- The first line of input code should be a regexp in comment that describes\n-- the information to dump (prefix with ##). The regexp is matched against\n-- the following items:\n--\n--   * each name of an expression node\n--   * each type string of a node (e.g. OpExpr)\n--\n-- Lines starting with \"--\" in this file will be ignored.\n\n\n-- Expressions\n-- -----------\n\n\n[case testConstructorCall]\nimport typing\nclass A: pass\nclass B: pass\nA()\nB()\n[out]\nCallExpr(4) : A\nNameExpr(4) : def () -> A\nCallExpr(5) : B\nNameExpr(5) : def () -> B\n\n[case testLiterals]\nimport typing\n5\n2.3\n'foo'\n[builtins fixtures/primitives.pyi]\n[out]\nIntExpr(2) : Literal[5]?\nFloatExpr(3) : builtins.float\nStrExpr(4) : Literal['foo']?\n\n[case testNameExpression]\n\na: A\na # node\ndef f(aa: 'A') -> None:\n  b: B\n  aa # node\n  b  # node\nclass A:\n  def g(self) -> None:\n    self # node\nclass B: pass\n[out]\nNameExpr(3) : A\nNameExpr(6) : A\nNameExpr(7) : B\nNameExpr(10) : A\n\n[case testEllipsis]\nimport typing\n...\n[out]\nEllipsisExpr(2) : builtins.ellipsis\n\n[case testMemberAccess]\n## MemberExpr|CallExpr\n\na: A\na.m\na.f\na.f()\nclass A:\n  m: A\n  def f(self) -> 'B': pass\nclass B: pass\n[out]\nMemberExpr(4) : A\nMemberExpr(5) : def () -> B\nCallExpr(6) : B\nMemberExpr(6) : def () -> B\n\n[case testCastExpression]\n## CastExpr|[a-z]\nfrom typing import Any, cast\nd: Any\nb: B\nclass A: pass\nclass B(A): pass\ncast(A, d)\ncast(A, b)\ncast(B, b)\n[out]\nCastExpr(7) : A\nNameExpr(7) : Any\nCastExpr(8) : A\nNameExpr(8) : B\nCastExpr(9) : B\nNameExpr(9) : B\n\n[case testAssertTypeExpr]\n## AssertTypeExpr|[a-z]\nfrom typing import Any, assert_type\nd: Any\na: A\nb: B\nclass A: pass\nclass B(A): pass\nassert_type(d, Any)\nassert_type(a, A)\nassert_type(b, B)\n[out]\nAssertTypeExpr(8) : Any\nNameExpr(8) : Any\nAssertTypeExpr(9) : A\nNameExpr(9) : A\nAssertTypeExpr(10) : B\nNameExpr(10) : B\n\n[case testArithmeticOps]\n## OpExpr\nimport typing\na = 1 + 2\n1.2 * 3\n2.2 - 3\n1 / 2\n[file builtins.py]\nclass object:\n    def __init__(self) -> None: pass\nclass function: pass\nclass int:\n    def __add__(self, x: int) -> int: pass\n    def __truediv__(self, x: int) -> float: pass\nclass float:\n    def __mul__(self, x: int) -> float: pass\n    def __sub__(self, x: int) -> float: pass\nclass type: pass\nclass str: pass\nclass list: pass\nclass dict: pass\n[out]\nOpExpr(3) : builtins.int\nOpExpr(4) : builtins.float\nOpExpr(5) : builtins.float\nOpExpr(6) : builtins.float\n\n[case testComparisonOps]\n## ComparisonExpr\nimport typing\n1 == object()\n1 == 2\n2 < 3\n1 < 2 < 3\n8 > 3\n4 < 6 > 2\n[file builtins.py]\nimport typing\n\nclass object:\n    def __init__(self) -> None: pass\nclass int:\n    def __eq__(self, x: object) -> bool: pass\n    def __lt__(self, x: int) -> bool: pass\n    def __gt__(self, x: int) -> int: pass\nclass bool: pass\nclass type: pass\nclass function: pass\nclass str: pass\nclass list: pass\nclass dict: pass\n[out]\nComparisonExpr(3) : builtins.bool\nComparisonExpr(4) : builtins.bool\nComparisonExpr(5) : builtins.bool\nComparisonExpr(6) : builtins.bool\nComparisonExpr(7) : builtins.int\nComparisonExpr(8) : builtins.object\n\n[case testBooleanOps]\n## OpExpr|UnaryExpr\nimport typing\na = 1\na and a\na or a\nnot a\n[builtins fixtures/bool.pyi]\n[out]\nOpExpr(4) : builtins.int\nOpExpr(5) : builtins.int\nUnaryExpr(6) : builtins.bool\n\n[case testBooleanOpsOnBools]\n## OpExpr|UnaryExpr\nimport typing\na = bool()\na and a\na or a\nnot a\n[builtins fixtures/bool.pyi]\n[out]\nOpExpr(4) : builtins.bool\nOpExpr(5) : builtins.bool\nUnaryExpr(6) : builtins.bool\n\n[case testFunctionCall]\n## CallExpr\nfrom typing import Tuple\nclass A: pass\nclass B: pass\ndef f(a: A, b: B) -> Tuple[A, B]: pass\nf(\n  A(),\n  B())\n[builtins fixtures/tuple-simple.pyi]\n[out]\nCallExpr(6) : Tuple[A, B]\nCallExpr(7) : A\nCallExpr(8) : B\n\n\n-- Statements\n-- ----------\n\n\n[case testSimpleAssignment]\nfrom typing import Any\na: A\nb = a # type: Any\nif b:\n    b = a\n    a = b\n\nclass A: pass\n[out]\nNameExpr(3) : A\nNameExpr(4) : Any\nNameExpr(5) : A\nNameExpr(5) : Any\nNameExpr(6) : A\nNameExpr(6) : Any\n\n[case testMemberAssignment]\nfrom typing import Any\nclass A:\n  a = None # type: A\n  b = None # type: Any\n  def f(self) -> None:\n    self.b = self.a\n    self.a.a = self.b\n[out]\nMemberExpr(6) : A\nMemberExpr(6) : Any\nNameExpr(6) : A\nNameExpr(6) : A\nMemberExpr(7) : A\nMemberExpr(7) : A\nMemberExpr(7) : A\nNameExpr(7) : A\nNameExpr(7) : A\n\n[case testIf]\n\na: bool\nif a:\n  1\nelif not a:\n  1\n[builtins fixtures/bool.pyi]\n[out]\nNameExpr(3) : builtins.bool\nIntExpr(4) : Literal[1]?\nNameExpr(5) : Literal[False]\nUnaryExpr(5) : builtins.bool\nIntExpr(6) : Literal[1]?\n\n[case testWhile]\n\na: bool\nwhile a:\n  a\n[builtins fixtures/bool.pyi]\n[out]\nNameExpr(3) : builtins.bool\nNameExpr(4) : Literal[True]\n\n\n-- Simple type inference\n-- ---------------------\n\n\n[case testInferSingleType]\nimport typing\nx = ()\n[builtins fixtures/primitives.pyi]\n[out]\nNameExpr(2) : Tuple[()]\nTupleExpr(2) : Tuple[()]\n\n[case testInferTwoTypes]\n## NameExpr\nimport typing\n(s,\ni) = 'x', 1\n[builtins fixtures/primitives.pyi]\n[out]\nNameExpr(3) : builtins.str\nNameExpr(4) : builtins.int\n\n[case testInferSingleLocalVarType]\nimport typing\ndef f() -> None:\n    x = ()\n[builtins fixtures/primitives.pyi]\n[out]\nNameExpr(3) : Tuple[()]\nTupleExpr(3) : Tuple[()]\n\n\n-- Basic generics\n-- --------------\n\n\n[case testImplicitBoundTypeVarsForMethod]\n## MemberExpr\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n  def f(self) -> T: pass\nclass B: pass\ndef g() -> None:\n  a: A[B]\n  f = a.f\n[out]\nMemberExpr(9) : def () -> B\n\n[case testImplicitBoundTypeVarsForSelfMethodReference]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n  def f(self) -> T:\n    return self.f()\n[out]\nCallExpr(5) : T`1\nMemberExpr(5) : def () -> T`1\nNameExpr(5) : A[T`1]\n\n[case testGenericFunctionCallWithTypeApp-skip]\n## CallExpr|TypeApplication|NameExpr\nfrom typing import Any, TypeVar, Tuple\nT = TypeVar('T')\nclass A: pass\nf[A](A())\nf[Any](A())\ndef f(a: T) -> Tuple[T, T]: pass\n[builtins fixtures/tuple.pyi]\n[out]\nCallExpr(5) : A\nCallExpr(5) : Tuple[A, A]\nNameExpr(5) : def () -> A\nNameExpr(5) : def (a: A) -> Tuple[A, A]\nTypeApplication(5) : def (a: A) -> Tuple[A, A]\nCallExpr(6) : A\nCallExpr(6) : Tuple[Any, Any]\nNameExpr(6) : def () -> A\nNameExpr(6) : def (a: Any) -> Tuple[Any, Any]\nTypeApplication(6) : def (a: Any) -> Tuple[Any, Any]\n\n-- NOTE: Type applications are not supported for generic methods, so the\n--       following test cases are commented out.\n\n--[case testGenericMethodCallWithTypeApp]\n--## CallExpr|MemberExpr|TypeApplication\n--from typing import Any, TypeVar, Tuple\n--T = TypeVar('T')\n--class A:\n--  def f(self, a: T) -> Tuple[T, T]: pass\n--a.f[A](a)\n--a.f[Any](a)\n--a = None # type: A\n--[builtins fixtures/tuple.py]\n--[out]\n--CallExpr(2) : Tuple[A, A]\n--MemberExpr(2) : def (A a) -> Tuple[A, A]\n--TypeApplication(2) : def (A a) -> Tuple[A, A]\n--CallExpr(3) : Tuple[Any, Any]\n--MemberExpr(3) : def (any a) -> Tuple[Any, Any]\n--TypeApplication(3) : def (any a) -> Tuple[Any, Any]\n\n--[case testGenericMethodCallInGenericTypeWithTypeApp]\n--## CallExpr|MemberExpr|TypeApplication\n--from typing import Any, TypeVar, Generic, Tuple\n--T = TypeVar('T')\n--S = TypeVar('S')\n--class B: pass\n--class C: pass\n--a.f[B](b)\n--a.f[Any](b)\n--class A(Generic[T]):\n--  def f(self, a: S) -> Tuple[T, S]: pass\n--a = None # type: A[C]\n--b = None # type: B\n--[builtins fixtures/tuple.py]\n--[out]\n--CallExpr(6) : Tuple[C, B]\n--MemberExpr(6) : def (B a) -> Tuple[C, B]\n--TypeApplication(6) : def (B a) -> Tuple[C, B]\n--CallExpr(7) : Tuple[C, Any]\n--MemberExpr(7) : def (any a) -> Tuple[C, Any]\n--TypeApplication(7) : def (any a) -> Tuple[C, Any]\n\n[case testGenericTypeVariableInference]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n  def __init__(self, a: T) -> None: pass\nclass B: pass\nA(A(B()))\n[out]\nCallExpr(6) : A[A[B]]\nCallExpr(6) : A[B]\nCallExpr(6) : B\nNameExpr(6) : def (a: A[B]) -> A[A[B]]\nNameExpr(6) : def (a: B) -> A[B]\nNameExpr(6) : def () -> B\n\n\n-- Generic inheritance\n-- -------------------\n\n\n[case testInheritedMethodReferenceWithGenericInheritance]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C: pass\nclass A(Generic[T]):\n  def f(self, a: T) -> None: pass\nclass B(A[C]):\n  def g(self, c: C) -> None:\n    self.f(c)\n[out]\nCallExpr(8) : None\nMemberExpr(8) : def (a: C)\nNameExpr(8) : C\nNameExpr(8) : B\n\n[case testInheritedMethodReferenceWithGenericSubclass]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\nclass C: pass\nclass A(Generic[S, T]):\n  def f(self, a: C) -> None: pass\nclass B(A[C, T], Generic[T]):\n  def g(self, c: C) -> None:\n    self.f(c)\n[out]\nCallExpr(9) : None\nMemberExpr(9) : def (a: C)\nNameExpr(9) : C\nNameExpr(9) : B[T`1]\n\n[case testExternalReferenceWithGenericInheritance]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C: pass\nclass A(Generic[T]):\n  def f(self, a: T) -> None: pass\nclass B(A[C]): pass\nb: B\nc: C\nb.f(c)\n[out]\nCallExpr(9) : None\nMemberExpr(9) : def (a: C)\nNameExpr(9) : B\nNameExpr(9) : C\n\n\n-- Implicit Any types\n-- ------------------\n\n\n[case testDynamicallyTypedFunction]\n\ndef f(x):\n  y = x + o\n  z = o\n  z\no = None # type: object\n[out]\nNameExpr(3) : builtins.object\nNameExpr(3) : Any\nNameExpr(3) : Any\nOpExpr(3) : Any\nNameExpr(4) : builtins.object\nNameExpr(4) : Any\nNameExpr(5) : Any\n\n[case testDynamicallyTypedMethod]\n\nclass A:\n  def f(self, x):\n    y = (\n         o)  # Place y and o on separate lines\n    x\n    y\no = None # type: object\n[out]\nNameExpr(4) : Any\nNameExpr(5) : builtins.object\nNameExpr(6) : Any\nNameExpr(7) : Any\n\n[case testDynamicallyTypedConstructor]\n\nclass A:\n  def __init__(self, x):\n    y = o\n    x\n    y\no = None # type: object\n[out]\nNameExpr(4) : builtins.object\nNameExpr(4) : Any\nNameExpr(5) : Any\nNameExpr(6) : Any\n\n[case testCallInDynamicallyTypedFunction]\n\ndef f():\n  g(o)\ndef g(a: object) -> object: pass\no = None # type: object\n[out]\nCallExpr(3) : Any\nNameExpr(3) : def (a: builtins.object) -> builtins.object\nNameExpr(3) : builtins.object\n\n[case testExpressionInDynamicallyTypedFn]\nimport typing\ndef f():\n  x = None\n  x.f()\n[out]\nCallExpr(4) : Any\nMemberExpr(4) : Any\nNameExpr(4) : Any\n\n[case testGenericCall]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef f() -> None:\n  a1 = A(b) # type: A[B]\n  a2 = A(b) # type: A[object]\nclass A(Generic[T]):\n  def __init__(self, a: T) -> None: pass\nclass B: pass\nb = None # type: B\n[out]\nCallExpr(4) : A[B]\nNameExpr(4) : def (a: B) -> A[B]\nNameExpr(4) : B\nCallExpr(5) : A[builtins.object]\nNameExpr(5) : def (a: builtins.object) -> A[builtins.object]\nNameExpr(5) : B\n\n[case testGenericCallInDynamicallyTypedFunction]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef f():\n  A()\nclass A(Generic[T]): pass\n[out]\nCallExpr(4) : Any\nNameExpr(4) : def [T] () -> A[T`1]\n\n[case testGenericCallInDynamicallyTypedFunction2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef f():\n  A(f)\nclass A(Generic[T]):\n    def __init__(self, x: T) -> None: pass\n[out]\nCallExpr(4) : Any\nNameExpr(4) : def [T] (x: T`1) -> A[T`1]\nNameExpr(4) : def () -> Any\n\n[case testGenericCallInDynamicallyTypedFunction3]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef f():\n  g(None)\ndef g(x: t) -> t: pass\n[out]\nCallExpr(4) : Any\nNameExpr(4) : def [t] (x: t`-1) -> t`-1\n\n\n-- Generic types and type inference\n-- --------------------------------\n\n\n[case testInferenceInArgumentContext]\n## CallExpr\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): pass\nclass B: pass\nclass C(B): pass\ndef f(a: 'A[B]') -> None: pass\ndef g() -> 'A[T]': pass\ndef h(a: T) -> 'A[T]': pass\n\nb = None # type: B\nc = None # type: C\n\nf(g())\nf(h(b))\nf(h(c))\n[out]\nCallExpr(14) : None\nCallExpr(14) : A[B]\nCallExpr(15) : None\nCallExpr(15) : A[B]\nCallExpr(16) : None\nCallExpr(16) : A[B]\n\n[case testInferGenericTypeForLocalVariable]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef f() -> None:\n  a = A(b)\n  a\n  a2, a3 = A(b), A(c)\n  a2\n  a3\nb = None # type: B\nc = None # type: C\nclass A(Generic[T]):\n  def __init__(self, x: T) -> None: pass\nclass B: pass\nclass C: pass\n[out]\nCallExpr(4) : A[B]\nNameExpr(4) : def (x: B) -> A[B]\nNameExpr(4) : A[B]\nNameExpr(4) : B\nNameExpr(5) : A[B]\nCallExpr(6) : A[B]\nCallExpr(6) : A[C]\nNameExpr(6) : def (x: B) -> A[B]\nNameExpr(6) : def (x: C) -> A[C]\nNameExpr(6) : A[B]\nNameExpr(6) : A[C]\nNameExpr(6) : B\nNameExpr(6) : C\nNameExpr(7) : A[B]\nNameExpr(8) : A[C]\n\n[case testNestedGenericCalls]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\ndef h() -> None:\n  g(f(c))\n\nc = None # type: C\n\nclass A(Generic[T]): pass\nclass B(Generic[T]): pass\nclass C: pass\ndef f(a: T) -> A[T]: pass\ndef g(a: S) -> B[S]: pass\n[out]\nCallExpr(5) : A[C]\nCallExpr(5) : B[A[C]]\nNameExpr(5) : C\nNameExpr(5) : def (a: C) -> A[C]\nNameExpr(5) : def (a: A[C]) -> B[A[C]]\n\n[case testInferListLiterals]\nfrom typing import List\na = [] # type: List[A]\nclass A: pass\n[builtins fixtures/list.pyi]\n[out]\nListExpr(2) : builtins.list[A]\n\n[case testInferGenericTypeInTypeAnyContext]\nfrom typing import Any\na = [] # type: Any\n[builtins fixtures/list.pyi]\n[out]\nListExpr(2) : builtins.list[Any]\n\n[case testHigherOrderFunction]\nfrom typing import TypeVar, Callable, List\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: Callable[[t], s], a: List[t]) -> List[s]: pass\nclass A: pass\nclass B: pass\ndef f(a: A) -> B: pass\nmap(\n    f,\n    [A()])\n[builtins fixtures/list.pyi]\n[out]\nCallExpr(8) : builtins.list[B]\nNameExpr(8) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B]\nNameExpr(9) : def (a: A) -> B\nCallExpr(10) : A\nListExpr(10) : builtins.list[A]\nNameExpr(10) : def () -> A\n\n\n-- Lambdas\n-- -------\n\n\n[case testLambdaWithTypeInferredFromContext]\nfrom typing import Callable\nf = lambda x: x.a # type: Callable[[B], A]\nclass A: pass\nclass B:\n  a = None # type: A\n[out]\nLambdaExpr(2) : def (x: B) -> A\nMemberExpr(2) : A\nNameExpr(2) : B\n\n[case testLambdaWithInferredType]\n## LambdaExpr|NameExpr\nimport typing\nf = lambda: 1\n[out]\nLambdaExpr(3) : def () -> Literal[1]?\nNameExpr(3) : def () -> builtins.int\n\n[case testLambdaWithInferredType2]\n## LambdaExpr|NameExpr\nimport typing\nf = lambda: [1]\n[builtins fixtures/list.pyi]\n[out]\nLambdaExpr(3) : def () -> builtins.list[builtins.int]\nNameExpr(3) : def () -> builtins.list[builtins.int]\n\n[case testLambdaWithInferredType3]\nfrom typing import List, Callable\nf = lambda x: [] # type: Callable[[B], List[A]]\nclass A: pass\nclass B:\n  a = None # type: A\n[builtins fixtures/list.pyi]\n[out]\nLambdaExpr(2) : def (x: B) -> builtins.list[A]\nListExpr(2) : builtins.list[A]\n\n[case testLambdaAndHigherOrderFunction]\nfrom typing import TypeVar, Callable, List\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: Callable[[t], s], a: List[t]) -> List[s]: pass\nclass A: pass\nclass B: pass\ndef f(a: A) -> B: pass\nl: List[A]\nmap(\n  lambda x: f(x), l)\n[builtins fixtures/list.pyi]\n[out]\nCallExpr(9) : builtins.list[B]\nNameExpr(9) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B]\nCallExpr(10) : B\nLambdaExpr(10) : def (x: A) -> B\nNameExpr(10) : def (a: A) -> B\nNameExpr(10) : builtins.list[A]\nNameExpr(10) : A\n\n[case testLambdaAndHigherOrderFunction2]\n## LambdaExpr|NameExpr|ListExpr\nfrom typing import TypeVar, List, Callable\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: Callable[[t], List[s]], a: List[t]) -> List[s]: pass\nclass A: pass\nclass B: pass\ndef f(a: A) -> B: pass\nl: List[A]\nmap(\n  lambda x: [f(x)], l)\n[builtins fixtures/list.pyi]\n[out]\nNameExpr(10) : def (f: def (A) -> builtins.list[B], a: builtins.list[A]) -> builtins.list[B]\nLambdaExpr(11) : def (x: A) -> builtins.list[B]\nListExpr(11) : builtins.list[B]\nNameExpr(11) : def (a: A) -> B\nNameExpr(11) : builtins.list[A]\nNameExpr(11) : A\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\nl: List[A]\nmap(\n  [lambda x: x],\n  l)\n[builtins fixtures/list.pyi]\n[out]\n-- TODO We probably should not silently infer 'Any' types in statically typed\n--      context. Perhaps just fail instead?\nCallExpr(7) : builtins.list[Any]\nNameExpr(7) : def (f: builtins.list[def (A) -> Any], a: builtins.list[A]) -> builtins.list[Any]\nLambdaExpr(8) : def (x: A) -> A\nListExpr(8) : builtins.list[def (A) -> Any]\nNameExpr(8) : A\nNameExpr(9) : builtins.list[A]\n\n[case testLambdaAndHigherOrderFunction3]\nfrom typing import TypeVar, Callable, List\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: Callable[[t], s], a: List[t]) -> List[s]: pass\nclass A:\n  b: B\nclass B: pass\nl: List[A]\nmap(\n  lambda x: x.b,\n  l)\n[builtins fixtures/list.pyi]\n[out]\nCallExpr(9) : builtins.list[B]\nNameExpr(9) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B]\nLambdaExpr(10) : def (x: A) -> B\nMemberExpr(10) : B\nNameExpr(10) : A\nNameExpr(11) : builtins.list[A]\n\n[case testLambdaAndHigherOrderFunctionAndKeywordArgs]\nfrom typing import TypeVar, Callable, List\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: Callable[[t], s], a: List[t]) -> List[s]: pass\nclass A:\n    b: B\nclass B: pass\nl: List[A]\nmap(\n  a=l,\n  f=lambda x: x.b)\n[builtins fixtures/list.pyi]\n[out]\nCallExpr(9) : builtins.list[B]\nNameExpr(9) : def (f: def (A) -> B, a: builtins.list[A]) -> builtins.list[B]\nNameExpr(10) : builtins.list[A]\nLambdaExpr(11) : def (x: A) -> B\nMemberExpr(11) : B\nNameExpr(11) : A\n\n\n-- Boolean operations\n-- ------------------\n\n\n[case testBooleanOr]\nfrom typing import List\na: List[A]\na or []\na = a or []\nif int():\n    a = [] or a\nclass A: pass\n[builtins fixtures/list.pyi]\n[out]\nListExpr(3) : builtins.list[A]\nNameExpr(3) : builtins.list[A]\nOpExpr(3) : builtins.list[A]\nListExpr(4) : builtins.list[A]\nNameExpr(4) : builtins.list[A]\nNameExpr(4) : builtins.list[A]\nOpExpr(4) : builtins.list[A]\nCallExpr(5) : builtins.int\nNameExpr(5) : def () -> builtins.int\nListExpr(6) : builtins.list[A]\nNameExpr(6) : builtins.list[A]\nNameExpr(6) : builtins.list[A]\nOpExpr(6) : builtins.list[A]\n\n\n-- Class attributes\n-- ----------------\n\n\n[case testUnboundMethod]\n## MemberExpr\nimport typing\nclass A:\n    def f(self) -> None: pass\nA.f\n[out]\nMemberExpr(5) : def (self: A)\n\n[case testUnboundMethodWithImplicitSig]\n## MemberExpr\nimport typing\nclass A:\n    def f(self): pass\nA.f\n[out]\nMemberExpr(5) : def (self: A) -> Any\n\n[case testOverloadedUnboundMethod]\n## MemberExpr\nfrom typing import overload\nclass A:\n    @overload\n    def f(self) -> None: pass\n    @overload\n    def f(self, __x: object) -> None: pass\n\n    def f(self, *args) -> None: pass\nA.f\n[builtins fixtures/tuple.pyi]\n[out]\nMemberExpr(10) : Overload(def (self: A), def (self: A, builtins.object))\n\n[case testOverloadedUnboundMethodWithImplicitSig]\n## MemberExpr\nfrom typing import overload\nclass A:\n    @overload\n    def f(self): pass\n    @overload\n    def f(self, __x): pass\n\n    def f(self, *args): pass\nA.f\n[builtins fixtures/tuple.pyi]\n[out]\nMemberExpr(10) : Overload(def (self: A) -> Any, def (self: A, Any) -> Any)\n\n[case testUnboundMethodWithInheritance]\n## MemberExpr\nimport typing\nclass A:\n    def __init__(self) -> None: pass\n    def f(self) -> None: pass\nclass B(A):\n    pass\nB.f\n[out]\nMemberExpr(8) : def (self: A)\n\n[case testUnboundGenericMethod]\n## MemberExpr\nfrom typing import TypeVar\nt = TypeVar('t')\nclass B: pass\nclass A:\n    def f(self, x: t) -> None: pass\nA.f(A(), B())\n[out]\nMemberExpr(7) : def (self: A, x: B)\n\n[case testUnboundMethodOfGenericClass]\n## MemberExpr\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass B: pass\nclass A(Generic[t]):\n    def f(self, x: t) -> None: pass\nA.f\na_b = A() # type: A[B]\nA.f(a_b, B())\n[out]\nMemberExpr(7) : def [t] (self: A[t`1], x: t`1)\nMemberExpr(9) : def (self: A[B], x: B)\n\n[case testUnboundOverloadedMethodOfGenericClass]\n## CallExpr\nfrom typing import TypeVar, Generic, overload\nt = TypeVar('t')\nclass B: pass\nclass A(Generic[t]):\n    @overload\n    def f(self, x: t) -> t: pass\n    @overload\n    def f(self) -> object: pass\n    def f(self, *args): pass\n\nab, b = None, None # type: (A[B], B)\nA.f(ab, b)\n[builtins fixtures/tuple.pyi]\n[out]\nCallExpr(13) : B\n\n[case testUnboundMethodOfGenericClassWithImplicitSig]\n## MemberExpr\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass B: pass\nclass A(Generic[t]):\n    def f(self, x): pass\nA.f(None, None)\n[out]\nMemberExpr(7) : def (self: A[t`1], x: Any) -> Any\n\n[case testGenericMethodOfGenericClass]\n## MemberExpr\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\ns = TypeVar('s')\nclass B: pass\nclass A(Generic[t]):\n    def f(self, y: s) -> None: pass\nab: A[B]\no: object\nA.f(ab, o)\n[out]\nMemberExpr(10) : def (self: A[B], y: builtins.object)\n\n\n-- Type variables with value restriction\n-- -------------------------------------\n\n\n[case testTypeVariableWithValueRestriction]\n## NameExpr\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> None: pass\nf(1)\nf('x')\n[out]\nNameExpr(5) : def (x: builtins.int)\nNameExpr(6) : def (x: builtins.str)\n\n[case testTypeVariableWithValueRestrictionAndSubtype]\n## NameExpr|CallExpr\nfrom typing import TypeVar\nT = TypeVar('T', int, str)\ndef f(x: T) -> T: pass\nclass S(str): pass\ns: S\nf(s)\n[out]\nCallExpr(7) : builtins.str\nNameExpr(7) : def (x: builtins.str) -> builtins.str\nNameExpr(7) : S\n\n[case testTypeVariableWithValueRestrictionInFunction]\n## NameExpr\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", int, str)\n\ndef f(x: T) -> T:\n    y = 1\n    return x\n[out]\nNameExpr(7) : builtins.int\nNameExpr(7) : builtins.int\nNameExpr(8) : builtins.int\nNameExpr(8) : builtins.str\n\n\n-- Binary operations\n-- -----------------\n\n\n[case testBinaryOperatorWithAnyLeftOperand]\n## OpExpr\nfrom typing import Any, cast\nclass B:\n    def __add__(self, x: int) -> str: pass\nclass A:\n    def __radd__(self, x: B) -> int: pass\ncast(Any, 1) + A()\nB() + A()\n[out]\nOpExpr(7) : Any\nOpExpr(8) : builtins.int\n\n[case testBinaryOperatorWithAnyRightOperand]\n## OpExpr\nfrom typing import Any, cast\nclass A:\n    def __add__(self, x: str) -> int: pass\nA() + cast(Any, 1)\n[out]\nOpExpr(5) : Any\n\n\n-- Callable overloading\n-- --------------------\n\n\n[case testOverloadedFunctionType]\n## CallExpr\nfrom typing import overload\n@overload\ndef f(x: int) -> str: pass\n@overload\ndef f(x: str) -> int: pass\ndef f(x): pass\nf(1)\nf('')\n[out]\nCallExpr(8) : builtins.str\nCallExpr(9) : builtins.int\n\n[case testOverlappingOverloadedFunctionType]\n## CallExpr\nfrom typing import overload, Any\nclass A: pass\nclass B(A): pass\n@overload\ndef f(x: B) -> B: pass\n@overload\ndef f(x: A) -> A: pass\n\ndef f(x) -> Any: pass\n\na: A\nb: B\nf(a)\nf(b)\n[out]\nCallExpr(14) : A\nCallExpr(15) : B\n\n\n\n[case testOverloadedErasedType]\nfrom typing import Callable\nfrom typing import List\nfrom typing import overload\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\nV = TypeVar(\"V\")\n\ndef fun(s: int) -> int: pass\n\ndef m(fun: Callable[[T], V], iter: List[T]) -> None: pass\n\nnums = [1] # type: List[int]\nm(fun,\n  nums)\n[builtins fixtures/list.pyi]\n[out]\nIntExpr(13) : Literal[1]?\nListExpr(13) : builtins.list[builtins.int]\nCallExpr(14) : None\nNameExpr(14) : def (s: builtins.int) -> builtins.int\nNameExpr(14) : def (fun: def (builtins.int) -> builtins.int, iter: builtins.list[builtins.int])\nNameExpr(15) : builtins.list[builtins.int]\n\n\n-- Special cases\n-- -------------\n\n\n[case testImplicitDataAttributeInit]\n## NameExpr\nimport typing\nclass A:\n    def __init__(self) -> None:\n        self.x = (\n                  A())\n[out]\nNameExpr(5) : A\nNameExpr(6) : def () -> A\n\n[case testListMultiplicationInContext]\n## ListExpr|OpExpr|IntExpr\nfrom typing import List\na = [None] * 3 # type: List[str]\n[builtins fixtures/list.pyi]\n[out]\nIntExpr(3) : Literal[3]?\nListExpr(3) : builtins.list[builtins.str]\nOpExpr(3) : builtins.list[builtins.str]\n\n[case testStringFormatting]\n## IntExpr|OpExpr|StrExpr\n'%d' % 1\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\nIntExpr(2) : Literal[1]?\nOpExpr(2) : builtins.str\nStrExpr(2) : Literal['%d']?\n\n[case testExportOverloadArgType]\n## LambdaExpr|NameExpr\nfrom typing import List, overload, Callable\n@overload\ndef f(x: int, f: Callable[[int], int]) -> None: ...\n@overload\ndef f(x: str, f: Callable[[str], str]) -> None: ...\ndef f(x): ...\nf(\n    1, lambda x: x)\n[builtins fixtures/list.pyi]\n[out]\nNameExpr(8) : Overload(def (x: builtins.int, f: def (builtins.int) -> builtins.int), def (x: builtins.str, f: def (builtins.str) -> builtins.str))\nLambdaExpr(9) : def (x: builtins.int) -> builtins.int\nNameExpr(9) : builtins.int\n\n[case testExportOverloadArgTypeNested]\n## LambdaExpr\nfrom typing import overload, Callable\n@overload\ndef f(x: int, f: Callable[[int], int]) -> int: ...\n@overload\ndef f(x: str, f: Callable[[str], str]) -> str: ...\ndef f(x): ...\nf(\n    f(1, lambda y: y),\n    lambda x: x)\nf(\n    f('x', lambda y: y),\n    lambda x: x)\n[builtins fixtures/list.pyi]\n[out]\nLambdaExpr(9) : def (y: builtins.int) -> builtins.int\nLambdaExpr(10) : def (x: builtins.int) -> builtins.int\nLambdaExpr(12) : def (y: builtins.str) -> builtins.str\nLambdaExpr(13) : def (x: builtins.str) -> builtins.str\n\n[case testExportOverloadArgTypeDict]\n## DictExpr\nfrom typing import TypeVar, Generic, Any, overload, Dict\nT = TypeVar(\"T\")\nclass Key(Generic[T]): ...\n@overload\ndef f(x: Key[T], y: T) -> T: ...\n@overload\ndef f(x: int, y: Any) -> Any: ...\ndef f(x, y): ...\nd: Dict = {}\nd.get(\n  \"\", {})\nf(\n  2, {})\n[builtins fixtures/dict.pyi]\n[out]\nDictExpr(10) : builtins.dict[Any, Any]\nDictExpr(12) : builtins.dict[Any, Any]\nDictExpr(14) : builtins.dict[Any, Any]\n\n-- TODO\n--\n-- test expressions\n--   list literal\n--   tuple literal\n--   unary minus\n--   indexing\n--   super expression\n--   more complex lambda (multiple arguments etc.)\n--   list comprehension\n--   generator expression\n-- other things\n--   type inference\n--   default argument value\n--   for loop variable\n--   exception variable\n--   varargs\n-- generics\n--   explicit types\n-- type of 'None' (currently stripped, but sometimes we may want to dump it)\n"
  },
  {
    "path": "test-requirements.in",
    "content": "# If you change this file (or mypy-requirements.txt or build-requirements.txt), please run:\n# pip-compile --output-file=test-requirements.txt --strip-extras --allow-unsafe test-requirements.in\n\n-r mypy-requirements.txt\n-r build-requirements.txt\nattrs>=18.0\nfilelock>=3.3.0\n# lxml 4.9.3 switched to manylinux_2_28, the wheel builder still uses manylinux2014\nlxml>=4.9.1,<4.9.3; (python_version<'3.11' or sys_platform!='win32') and python_version<'3.12'\npsutil>=4.0\npytest>=8.1.0\npytest-xdist>=1.34.0\npytest-cov>=2.10.0\nsetuptools>=75.1.0\ntomli>=1.1.0  # needed even on py311+ so the self check passes with --python-version 3.9\npre_commit>=3.5.0\n"
  },
  {
    "path": "test-requirements.txt",
    "content": "#\n# This file is autogenerated by pip-compile with Python 3.11\n# by the following command:\n#\n#    pip-compile --allow-unsafe --output-file=test-requirements.txt --strip-extras test-requirements.in\n#\nattrs==24.2.0\n    # via -r test-requirements.in\ncfgv==3.4.0\n    # via pre-commit\ncoverage==7.6.1\n    # via pytest-cov\ndistlib==0.3.9\n    # via virtualenv\nexecnet==2.1.1\n    # via pytest-xdist\nfilelock==3.16.1\n    # via\n    #   -r test-requirements.in\n    #   virtualenv\nidentify==2.6.1\n    # via pre-commit\niniconfig==2.0.0\n    # via pytest\nlxml==4.9.2 ; (python_version < \"3.11\" or sys_platform != \"win32\") and python_version < \"3.12\"\n    # via -r test-requirements.in\nmypy-extensions==1.0.0\n    # via -r mypy-requirements.txt\nnodeenv==1.9.1\n    # via pre-commit\npackaging==24.1\n    # via pytest\nplatformdirs==4.3.6\n    # via virtualenv\npluggy==1.5.0\n    # via pytest\npre-commit==3.5.0\n    # via -r test-requirements.in\npsutil==6.0.0\n    # via -r test-requirements.in\npytest==8.3.3\n    # via\n    #   -r test-requirements.in\n    #   pytest-cov\n    #   pytest-xdist\npytest-cov==5.0.0\n    # via -r test-requirements.in\npytest-xdist==3.6.1\n    # via -r test-requirements.in\npyyaml==6.0.2\n    # via pre-commit\ntomli==2.0.2\n    # via -r test-requirements.in\ntypes-psutil==6.0.0.20241011\n    # via -r build-requirements.txt\ntypes-setuptools==75.1.0.20241014\n    # via -r build-requirements.txt\ntyping-extensions==4.12.2\n    # via -r mypy-requirements.txt\nvirtualenv==20.26.6\n    # via pre-commit\n\n# The following packages are considered to be unsafe in a requirements file:\nsetuptools==75.1.0\n    # via -r test-requirements.in\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nminversion = 4.4.4\nskip_missing_interpreters = {env:TOX_SKIP_MISSING_INTERPRETERS:True}\nenvlist =\n    py38,\n    py39,\n    py310,\n    py311,\n    py312,\n    py313,\n    docs,\n    lint,\n    type,\nisolated_build = true\n\n[testenv]\ndescription = run the test driver with {basepython}\npassenv =\n    PYTEST_XDIST_WORKER_COUNT\n    PROGRAMDATA\n    PROGRAMFILES(X86)\n    PYTEST_ADDOPTS\ndeps =\n    -r test-requirements.txt\n    # This is a bit of a hack, but ensures the faster-cache path is tested in CI\n    orjson;python_version=='3.12'\ncommands = python -m pytest {posargs}\n\n[testenv:dev]\ndescription = generate a DEV environment, that has all project libraries\nusedevelop = True\ndeps =\n    -r test-requirements.txt\n    -r docs/requirements-docs.txt\ncommands =\n    python -m pip list --format=columns\n    python -c 'import sys; print(sys.executable)'\n    {posargs}\n\n[testenv:docs]\ndescription = invoke sphinx-build to build the HTML docs\npassenv =\n    VERIFY_MYPY_ERROR_CODES\ndeps = -r docs/requirements-docs.txt\ncommands =\n    sphinx-build -n -d \"{toxworkdir}/docs_doctree\" docs/source \"{toxworkdir}/docs_out\" --color -W -bhtml {posargs}\n    python -c 'import pathlib; print(\"documentation available under file://\\{0\\}\".format(pathlib.Path(r\"{toxworkdir}\") / \"docs_out\" / \"index.html\"))'\n\n[testenv:lint]\ndescription = check the code style\nskip_install = true\ndeps = pre-commit\ncommands = pre-commit run --all-files --show-diff-on-failure\n\n[testenv:type]\ndescription = type check ourselves\ncommands =\n    python runtests.py self\n    python -m mypy --config-file mypy_self_check_strict.ini -p mypy -p mypyc\n    python -m mypy --config-file mypy_self_check.ini misc --exclude misc/sync-typeshed.py\n    python -m mypy --config-file mypy_self_check.ini test-data/unit/plugins\n"
  }
]